Compare commits

8 Commits

13 changed files with 1983 additions and 788 deletions

View File

@@ -1,21 +0,0 @@
import Invoker, { InvokerModName } from "./src/components/Invoker";
import { hh } from './src/components/DemiHelper';
import { InvokerItem } from "./src/components/InvokerItem";
import { InvokerContext } from "./src/types/InvokerContext";
import { Vue2Instance } from "./src/types/Vue2Instance";
import { ModContext } from "./src/types/ModContext";
import Receiver from "./src/components/Receiver";
import { ConfigureModPage, modPageConfig } from "./src/modPageConfig";
export {
modPageConfig,
ConfigureModPage,
Invoker,
Receiver,
type InvokerItem,
type InvokerContext,
type InvokerModName,
type Vue2Instance,
type ModContext,
hh,
}

View File

@@ -1,11 +1,24 @@
{
"name": "vue-modpage",
"private": true,
"version": "1.0.0",
"version": "1.0.4",
"type": "module",
"files": [
"public",
"src",
"README.md"
],
"main": "src/index.ts",
"module": "src/index.ts",
"exports": {
".": {
"import": "./src/index.ts",
"require": "./src/index.ts"
}
},
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"build": "vue-tsc --skipLibCheck && vite build",
"preview": "vite preview",
"switch:2": "vue-demi-switch 2.7 vue2",
"switch:3": "vue-demi-switch 3",
@@ -24,6 +37,7 @@
"@vitejs/plugin-vue-jsx": "^4.1.1",
"@vitejs/plugin-vue2": "^2.2.0",
"@vitejs/plugin-vue2-jsx": "^1.1.0",
"npm-run-all": "^4.1.5",
"typescript": "~5.6.2",
"vite": "^6.0.1",
"vitest": "^2.1.8",

2430
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
<template>
<div>
vue-{{ vueVer }}
<Invoker url="/child.html#?id={id}" style="border:1px solid red;height: 400px;overflow-y: scroll;" :items="items" />
<Invoker style="border:1px solid red;height: 400px;overflow-y: scroll;" :items="items" />
<component :is="dom" />
</div>
</template>

View File

@@ -1,8 +1,7 @@
import * as Vue3 from "vue";
// @ts-ignore
import { h, isVue2, isVue3, type VNode, type VNodeChildren, type VNodeData } from "vue-demi";
import { ComponentInternalInstance, h, isVue2, isVue3, type VNode, type VNodeChildren, type VNodeData } from "vue-demi";
import { InvokerItem } from "./InvokerItem";
import { ComponentInternalInstance } from "vue-demi/lib/v2/index.js";
function splitAttrs(obj: object) : { attrs: Record<string, any>, on: Record<string, any> } {
const attrs: Record<string, any> = {};
@@ -21,11 +20,11 @@ function splitAttrs(obj: object) : { attrs: Record<string, any>, on: Record<stri
/**
* 将扁平化的组件数据对象分离为Vue2形式的data对象
* @param rawData
* @returns
* @param rawData
* @returns
*/
function splitVue2Data(rawData?: Record<string, any> | null) {
console.warn("Handling Vue2 data: ", rawData);
// console.warn("Handling Vue2 data: ", rawData);
if (!rawData) return {};
if (isVue3) throw new Error("Vue3 data object is not supported in Vue2");
@@ -54,11 +53,11 @@ function splitVue2Data(rawData?: Record<string, any> | null) {
/**
* 渲染具名插槽
* @param slotFn
* @param args
* @returns
* @param slotFn
* @param args
* @returns
*/
function renderSlot(slotFn: Function, args: any, ctx?: ComponentInternalInstance) {
function renderSlot(slotFn: Function, args: any, renderFunction?: Function) {
let child: string | Array<InvokerItem> | InvokerItem = slotFn(args);
// console.warn("Rendering Slot: ", child);
// 字符串情况
@@ -67,17 +66,18 @@ function renderSlot(slotFn: Function, args: any, ctx?: ComponentInternalInstance
}
// Array<InvokerItem>情况
else if (Array.isArray(child)) {
return child.map((c: InvokerItem) => hh(c.tag, c.data, c.children, ctx));
return child.map((c: InvokerItem) => hh(c.tag, c.data, c.children, renderFunction));
}
// InvokerItem情况
else {
return hh(child.tag, child.data, child.children, ctx);
return hh(child.tag, child.data, child.children, renderFunction);
}
}
export function hh(tag: string, data?: Record<string, any> | null, children?: string | Array<InvokerItem> | Record<string, Function>, ctx?: ComponentInternalInstance) {
export function hh(tag: string | object, data?: Record<string, any> | null, children?: string | Array<InvokerItem> | Record<string, Function>, renderFunction?: Function) {
// 适配Vue2渲染函数结构
// console.debug("Rendering", tag, data, children, `Vue Version: ${isVue2 ? 'Vue2' : 'Vue3'}`);
const render = renderFunction || h;
// 处理tag
let processedTag: string | object = tag;
@@ -103,7 +103,8 @@ export function hh(tag: string, data?: Record<string, any> | null, children?: st
}
// 子节点列表则递归处理
else if (Array.isArray(children)) {
processedChildren = children.map(child => hh(child.tag, child.data, child.children, ctx));
processedChildren = children.map(child => hh(child.tag, child.data, child.children, renderFunction));
// console.warn("Processed Children: ", processedChildren);
}
// 处理具名插槽对象
else if (children && typeof children == 'object') {
@@ -111,7 +112,7 @@ export function hh(tag: string, data?: Record<string, any> | null, children?: st
processedChildren = Object.fromEntries(
Object.entries(children).map(([name, slotFn]) => [
name,
(args) => renderSlot(slotFn, args, ctx)
(args) => renderSlot(slotFn, args, renderFunction)
])
)
}
@@ -121,13 +122,15 @@ export function hh(tag: string, data?: Record<string, any> | null, children?: st
Object.entries(children).map(([name, slotFn]) => [
name,
(args) => {
return renderSlot(slotFn, args);
return renderSlot(slotFn, args, renderFunction);
}
])
);
}
}
console.debug("Processed", processedTag, processedData, processedChildren);
return h(processedTag, processedData, processedChildren);
}
// console.debug("Processed", {
// processedTag, processedData, processedChildren
// });
return render(processedTag, processedData, processedChildren);
}

View File

@@ -1,12 +1,17 @@
import {
defineComponent,
onBeforeUpdate,
h,
isVue2,
onMounted,
onUnmounted,
ref,
watch,
type PropType
} from "vue-demi";
import { ModContext } from "../types/ModContext";
import { InvokerItem } from "./InvokerItem";
import { modPageConfig } from "../modPageConfig";
import { hh } from "./DemiHelper";
let idCount = 0;
export type InvokerModName = string;
@@ -37,9 +42,13 @@ export default defineComponent({
const id = ++idCount;
/** vue实例上下文此处获取的是Receiver的vue组件实例 */
let receiver: ModContext | null = null;
const invokerKey = modPageConfig.Invoker.invokerKey;
const url = ref<string | undefined>('');
window["MES_MOD_INVOKERS"] ||= {};
window["MES_MOD_INVOKERS"][id] = {
console.log(`[Mod-Invoker] 1. setting up invoker, id: ${id}, name: ${props.name}, invokerKey: ${invokerKey}`);
window[invokerKey] ||= {};
window[invokerKey][id] = {
getRenderContext,
initFinish,
receiver,
@@ -50,6 +59,7 @@ export default defineComponent({
function updateComponent() {
// 判断子页面vue对象是否存在
receiver?.Update(); // 强制渲染
console.log("[Mod-Invoker] update component");
}
// 子组件调用
@@ -61,10 +71,10 @@ export default defineComponent({
}
}
/** 当Receiver初始化完毕后触发 */
/** 当Receiver初始化完毕后由它触发 */
function initFinish(context: ModContext) {
receiver = context;
console.log('[Mod-Invoker]initFinish')
console.log('[Mod-Invoker] 3.1. invoker init finished', receiver)
}
function getRefs() {
@@ -83,6 +93,7 @@ export default defineComponent({
getRenderContext,
eventCallback,
initFinish,
updateComponent
});
watch(
@@ -92,26 +103,25 @@ export default defineComponent({
}
);
onBeforeUpdate(() => {
onMounted(async () => {
url.value = await modPageConfig.Invoker.GetModUrl?.(props.name ?? '', id.toString(), invokerKey);
})
});
onUnmounted(() => {
console.log("[Mod-Invoker] invoker-destroyed");
emit('destroyed');
});
return (h) => {
return (createElem) => {
const render = isVue2 ? createElem : h;
if (slots.default) {
return <div>{slots.default()}</div>;
return render('div', {}, slots.default());
}
return (
<iframe
src={props.url.replace('{id}',id.toString())}
scrolling={props.scroll ? "yes" : "no"}
style={`border: none; width: 100%; height: ${props.height}; `}
></iframe>
);
return hh('iframe', {
src: url.value,
scrolling: props.scroll ? "yes" : "no",
style: `border: none; width: 100%; height: ${props.height}; `
});
};
},
});

View File

@@ -1,94 +1,7 @@
import { defineComponent, nextTick, onMounted, ref, getCurrentInstance, isVue3 } from 'vue-demi';
import { defineComponent, nextTick, onMounted, ref, getCurrentInstance, isVue3, h, isVue2 } from 'vue-demi';
import { hh } from './DemiHelper';
import { InvokerContext } from '../types/InvokerContext';
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: {
@@ -98,59 +11,60 @@ export default defineComponent({
},
parentKey: {
type: String,
default: () => 'modInvoker'
default: () => 'MES_MOD_INVOKERS'
}
},
setup(props) {
const instance = getCurrentInstance();
let invokerContext: InvokerContext = null!;
const renderVersion = ref(0);
console.log(`[Mod-Receiver] 2. receiver setup, invokerId: ${props.parentId}, invokerKey: ${props.parentKey}`);
if (window.parent != window) {
const invoker = window.parent[props.parentKey][props.parentId];
invokerContext = invoker;
console.log("[Mod-Receiver] 3. got invoker context", invokerContext);
}
else {
throw new Error("[Receiver] 组件必须在iframe中使用");
throw new Error("[Mod-Receiver] the receiver must be in an iframe");
}
const renderItems = ref(invokerContext.getRenderContext() ?? []);
onMounted(() => {
nextTick().then(() => {
console.log('mounted-finish');
if (!invokerContext['modContext']) {
invokerContext.initFinish({
get renderVersion() {
return renderVersion.value;
},
Update: function (): void {
console.log('[Receiver] Force Update', renderVersion.value);
renderVersion.value += 1;
renderItems.value = invokerContext.getRenderContext() ?? [];
instance?.proxy?.$forceUpdate();
},
get refs() {
return instance?.proxy?.$refs;
}
});
// 若Invoker未接收到当前实例(首次初始化),则进行初始化
if (!invokerContext.receiver) {
invokerContext.initFinish({
get renderVersion() {
return renderVersion.value;
},
Update: function (): void {
renderVersion.value += 1;
renderItems.value = invokerContext.getRenderContext() ?? [];
instance?.proxy?.$forceUpdate();
},
// @ts-ignore
get refs() {
return instance?.proxy?.$refs;
}
});
});
return () => {
}
return (createElem) => {
const render = isVue2 ? createElem : h;
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);
console.log("[Mod-Receiver] 4. rendering: ", itemList);
// @ts-ignore
return hh('div', undefined, itemList, render);
}
return hh('div');
console.warn("[Mod-Receiver] 'getRenderContext' method not found");
return hh('div', undefined, undefined, render);
}
catch (e) {
console.error("[Receiver] 渲染节点过程中出现错误", e);
console.error("[Mod-Receiver] 渲染节点过程中出现错误", e);
}
};
}

21
src/index.ts Normal file
View File

@@ -0,0 +1,21 @@
import Invoker, { InvokerModName } from "./components/Invoker";
import { hh } from './components/DemiHelper';
import { InvokerItem } from "./components/InvokerItem";
import { InvokerContext } from "./types/InvokerContext";
import { Vue2Instance } from "./types/Vue2Instance";
import { ModContext } from "./types/ModContext";
import Receiver from "./components/Receiver";
import { ConfigureModPage, modPageConfig } from "./modPageConfig";
export {
modPageConfig,
ConfigureModPage,
Invoker,
Receiver,
type InvokerItem,
type InvokerContext,
type InvokerModName,
type Vue2Instance,
type ModContext,
hh,
}

View File

@@ -1,5 +1,19 @@
import { createApp, Vue2 } from 'vue-demi'
import App from './App.vue'
import { ConfigureModPage } from './modPageConfig'
ConfigureModPage({
Invoker: {
GetModUrl: (modName, invokerId, invokerKey) => {
const query: Record<string, string> = {
id: invokerId,
key: invokerKey
};
const searchParam = new URLSearchParams(query);
return `/child.html#/?${searchParam.toString()}`
}
}
})
const app = createApp(App)
app.mount('#app')

View File

@@ -3,17 +3,29 @@ import { InvokerModName } from "./components/Invoker";
let _modPageConfig = {
Invoker: {
invokerKey: "MES_MOD_INVOKERS",
/** Invoker中计算ModUrl的方法 */
GetModUrl: undefined as ((modName: InvokerModName) => string | Promise<string>) | undefined,
GetModUrl: undefined as ((modName: InvokerModName, invokerId: string, invokerKey: string) => string | Promise<string>) | undefined,
}
}
export function ConfigureModPage(config: typeof _modPageConfig) {
export function ConfigureModPage(config: DeepPartial<typeof _modPageConfig>) {
Object.assign(_modPageConfig, {
..._modPageConfig,
...config,
Invoker: {
...config.Invoker,
..._modPageConfig.Invoker,
...config?.Invoker
}
});
}
export const modPageConfig: DeepReadonly<typeof _modPageConfig> = _modPageConfig;
type DeepPartial<T> = T extends Function // 排除Function因为Function也是object
? T
: T extends object
? {
[P in keyof T]?: DeepPartial<T[P]>;
}
: T;

View File

@@ -23,5 +23,5 @@
"noUncheckedSideEffectImports": true,
"noImplicitAny": false
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "index.ts"]
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "src/index.ts"]
}

View File

@@ -4,14 +4,14 @@ import vueJsx from '@vitejs/plugin-vue-jsx'
import vue2 from '@vitejs/plugin-vue2'
import vue2Jsx from '@vitejs/plugin-vue2-jsx'
import { isVue2, isVue3,version } from 'vue-demi'
import { isVue2, isVue3, version } from 'vue-demi'
import path from 'node:path'
import { createRequire } from 'node:module'
const resolve = (str: string) => {
return path.resolve(__dirname, str)
}
console.log('vue',version)
console.log('vue', version)
function getV2Compiler() {
const req = createRequire(import.meta.url);
@@ -24,15 +24,15 @@ function getV2Compiler() {
// https://vite.dev/config/
export default defineConfig({
plugins: isVue3 ? [vue(), vueJsx()] : [vue2({
compiler: getV2Compiler()
}), vue2Jsx()],
resolve:{
alias:{
plugins: isVue3 ?
[vue(), vueJsx()] :
[vue2({ compiler: getV2Compiler() }), vue2Jsx()],
resolve: {
alias: {
vue: isVue2 ? resolve('./node_modules/vue2') : resolve('./node_modules/vue'),
}
},
optimizeDeps: {
exclude: ['vue-demi']
},
}
})

BIN
vue-modpage-1.0.4.tgz Normal file

Binary file not shown.