@xingtukeji/micro 1.1.27 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,6 +26,34 @@ function traverseMenu(menu) {
26
26
  traverseMenu(window.$config.menus);
27
27
  ```
28
28
 
29
+ 推荐在不会被路由销毁的布局中挂载 Host:
30
+
31
+ ```vue
32
+ <script setup>
33
+ import { computed } from "vue";
34
+ import { useRoute } from "vue-router";
35
+ import { XTMicroHost } from "@xingtukeji/micro";
36
+
37
+ const route = useRoute();
38
+ const activeMicroApp = computed(() =>
39
+ route.name === "micro" ? String(route.params.appId) : undefined
40
+ );
41
+ </script>
42
+
43
+ <template>
44
+ <div class="content">
45
+ <XTMicroHost :active-app="activeMicroApp" />
46
+ <router-view v-show="!activeMicroApp" />
47
+ </div>
48
+ </template>
49
+
50
+ <style>
51
+ .content { position: relative; min-width: 0; min-height: 0; }
52
+ </style>
53
+ ```
54
+
55
+ `preload: true` 的应用会在浏览器空闲时串行加载。iframe 始终留在 Host 中,切换应用只改变可见性。`XTMicroView` 继续兼容非 preload 的旧接入方式。
56
+
29
57
  子应用初始化:
30
58
 
31
59
  ```javascript
@@ -39,9 +67,21 @@ microInit({
39
67
  },
40
68
  //简易处理微应用环境下,隐藏 header
41
69
  hideHeaderCssSelector: "#app ._hedaui-header",
70
+ onActivated() {
71
+ // 图表、地图等可在这里重新计算尺寸
72
+ },
73
+ onDeactivated() {
74
+ // 可在这里暂停轮询或动画
75
+ },
42
76
  });
43
77
  ```
44
78
 
79
+ 开启调试日志:
80
+
81
+ ```javascript
82
+ window.micro_api.debug(true);
83
+ ```
84
+
45
85
  当需要新标签打开子项目时,还想保留父项目加载的方式(不直接访问子项目),可以在父项目的 url 中添加参数 `__XT_MICRO_${子项目名称}=${子项目 url}`
46
86
  但要注意,子项目的 url 需要用 encodeURIComponent 编码,否则会导致参数解析错误
47
87
 
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- (function(){try{if(typeof document<`u`){var e=document.createElement(`style`);e.appendChild(document.createTextNode(`.xt-micro{background-color:transparent;width:100%;height:100%;overflow:hidden}.micro-iframe{border:none;width:100%;height:100%;margin:0;padding:0}`)),document.head.appendChild(e)}}catch(e){console.error(`vite-plugin-css-injected-by-js`,e)}})();import { createElementBlock, defineComponent, mergeProps, onMounted, onUnmounted, openBlock, ref, watch } from "vue";
2
- var __defProp = Object.defineProperty, __export = (g) => {
3
- let B = {};
4
- for (var V in g) __defProp(B, V, {
5
- get: g[V],
1
+ (function(){try{if(typeof document<`u`){var e=document.createElement(`style`);e.appendChild(document.createTextNode(`.xt-micro{background-color:transparent;width:100%;height:100%;overflow:hidden}.micro-iframe{border:none;width:100%;height:100%;margin:0;padding:0}.xt-micro-host,.xt-micro-panel{position:absolute;top:0;bottom:0;left:0;right:0;overflow:hidden}.xt-micro-panel{visibility:hidden;pointer-events:none}.xt-micro-panel.is-active{visibility:visible;pointer-events:auto}`)),document.head.appendChild(e)}}catch(e){console.error(`vite-plugin-css-injected-by-js`,e)}})();import { Fragment, createElementBlock, defineComponent, mergeProps, nextTick, normalizeClass, onBeforeUnmount, onMounted, openBlock, ref, renderList, unref, watch } from "vue";
2
+ var __defProp = Object.defineProperty, __export = (s) => {
3
+ let I = {};
4
+ for (var L in s) __defProp(I, L, {
5
+ get: s[L],
6
6
  enumerable: !0
7
7
  });
8
- return B;
8
+ return I;
9
9
  };
10
10
  const CONSTANT = {
11
11
  KEY: "$xtm",
@@ -17,7 +17,7 @@ const CONSTANT = {
17
17
  DOM_ID_PREFIX: "xt-micro-ifr-",
18
18
  URL_PARAM_PREFIX: "__XT_MICRO_",
19
19
  MICRO_VERSION: "__XT_MICRO_VERSION"
20
- }, version = "1.1.27";
20
+ }, version = "1.2.0";
21
21
  var utils_exports = /* @__PURE__ */ __export({
22
22
  ConsoleUtil: () => ConsoleUtil,
23
23
  addOrReplaceUrlParam: () => addOrReplaceUrlParam,
@@ -28,247 +28,279 @@ var utils_exports = /* @__PURE__ */ __export({
28
28
  getQueryParameter: () => getQueryParameter,
29
29
  ipcSyncAppInfo: () => ipcSyncAppInfo
30
30
  });
31
- function getQueryParameter(g, B = window.location.href) {
32
- g = g.replace(/[\[\]]/g, "\\$&");
33
- var V = (/* @__PURE__ */ RegExp("[?&]" + g + "(=([^&#]*)|&|#|$)")).exec(B);
34
- return V ? V[2] ? decodeURIComponent(V[2].replace(/\+/g, " ")).trim() : "" : null;
31
+ function getQueryParameter(s, I = window.location.href) {
32
+ s = s.replace(/[\[\]]/g, "\\$&");
33
+ var L = (/* @__PURE__ */ RegExp("[?&]" + s + "(=([^&#]*)|&|#|$)")).exec(I);
34
+ return L ? L[2] ? decodeURIComponent(L[2].replace(/\+/g, " ")).trim() : "" : null;
35
35
  }
36
- function getAbsolutePath(g, B, V) {
36
+ function getAbsolutePath(s, I, L) {
37
37
  try {
38
- return g && (V && g.startsWith("#") ? g : new URL(g, B).href);
38
+ return s && (L && s.startsWith("#") ? s : new URL(s, I).href);
39
39
  } catch {
40
- return g;
40
+ return s;
41
41
  }
42
42
  }
43
- function anchorElementGenerator(g) {
44
- let B = window.document.createElement("a");
45
- return B.href = g, B.href = B.href, B;
43
+ function anchorElementGenerator(s) {
44
+ let I = window.document.createElement("a");
45
+ return I.href = s, I.href = I.href, I;
46
46
  }
47
- function getAnchorElementQueryMap(g) {
48
- let B = g.search || "";
49
- return [...new URLSearchParams(B).entries()].reduce((g, B) => (g[B[0]] = B[1], g), {});
47
+ function getAnchorElementQueryMap(s) {
48
+ let I = s.search || "";
49
+ return [...new URLSearchParams(I).entries()].reduce((s, I) => (s[I[0]] = I[1], s), {});
50
50
  }
51
- function debounce(g, B) {
52
- let V = null;
53
- return function(...H) {
54
- let U = this;
55
- V && clearTimeout(V), V = setTimeout(() => {
56
- g.apply(U, H);
57
- }, B);
51
+ function debounce(s, I) {
52
+ let L = null;
53
+ return function(...R) {
54
+ let z = this;
55
+ L && clearTimeout(L), L = setTimeout(() => {
56
+ s.apply(z, R);
57
+ }, I);
58
58
  };
59
59
  }
60
- function addOrReplaceUrlParam(g, B, V) {
61
- let [H, U] = g.split("#"), W = new URL(H), G = W.searchParams;
62
- return B = CONSTANT.URL_PARAM_PREFIX + B, G.has(B) ? G.set(B, V) : G.append(B, V), U && (W.hash = U), W.search = G.toString(), ConsoleUtil.trace("urlObj", W), W.origin + W.pathname + W.search + W.hash;
60
+ function addOrReplaceUrlParam(s, I, L) {
61
+ let [R, z] = s.split("#"), B = new URL(R), V = B.searchParams;
62
+ return I = CONSTANT.URL_PARAM_PREFIX + I, V.has(I) ? V.set(I, L) : V.append(I, L), z && (B.hash = z), B.search = V.toString(), ConsoleUtil.trace("urlObj", B), B.origin + B.pathname + B.search + B.hash;
63
63
  }
64
- const ipcSyncAppInfo = async (g) => new Promise((B) => {
65
- window.addEventListener("message", (V) => {
66
- ConsoleUtil.trace("child ipcSyncAppInfo receive message", V.data), V.data.cmd === "$xt/micro/info" && (V.data.data.mainMicroVersion !== "1.1.27" && ConsoleUtil.warn(`子应用版本与主应用版本不一致,${g}子应用版本:${version},主应用版本:${V.data.data.mainMicroVersion}`), B(V.data.data));
67
- }), ConsoleUtil.trace("child ipcSyncAppInfo send message", g), window.parent.postMessage({
64
+ const ipcSyncAppInfo = async (s) => new Promise((I, L) => {
65
+ let R = window.setTimeout(() => {
66
+ window.removeEventListener("message", z), L(/* @__PURE__ */ Error(`micro app info timeout: ${s}`));
67
+ }, 1e4), z = (L) => {
68
+ ConsoleUtil.trace("child ipcSyncAppInfo receive message", L.data), L.source === window.parent && L.data?.cmd === "$xt/micro/info" && L.data?.data?.name === s && L.data?.data?.mainLocation?.origin === L.origin && (window.clearTimeout(R), window.removeEventListener("message", z), L.data.data.mainMicroVersion !== "1.2.0" && ConsoleUtil.warn(`子应用版本与主应用版本不一致,${s}子应用版本:${version},主应用版本:${L.data.data.mainMicroVersion}`), I(L.data.data));
69
+ };
70
+ window.addEventListener("message", z), ConsoleUtil.trace("child ipcSyncAppInfo send message", s), window.parent.postMessage({
68
71
  cmd: "$xt/micro/info",
69
- data: g
72
+ data: s
70
73
  }, "*");
71
74
  });
72
- var ConsoleUtil = class g {
75
+ var ConsoleUtil = class s {
73
76
  static STORAGE_KEY = "@xt/micro/console/enable";
74
77
  static get enable() {
75
- return localStorage.getItem(g.STORAGE_KEY) === "true";
78
+ return localStorage.getItem(s.STORAGE_KEY) === "true";
76
79
  }
77
- static setEnable(B) {
78
- localStorage.setItem(g.STORAGE_KEY, B.toString());
80
+ static setEnable(I) {
81
+ localStorage.setItem(s.STORAGE_KEY, I.toString());
79
82
  }
80
83
  static getEnable() {
81
- return g.enable;
84
+ return s.enable;
82
85
  }
83
86
  static getCallerInfo() {
84
87
  try {
85
- let g = /* @__PURE__ */ ((/* @__PURE__ */ Error()).stack || "").split("\n").slice(4);
86
- if (g.length === 0) return "unknown location";
87
- let B = g[0].trim(), V = B.match(/(?:http[s]?:\/\/.*?\/|)([^:]+):(\d+):(\d+)/);
88
- if (V) {
89
- let [, g, B] = V;
90
- return `[${g.split("/").slice(-2).join("/")}:${B}]`;
88
+ let s = /* @__PURE__ */ ((/* @__PURE__ */ Error()).stack || "").split("\n").slice(4);
89
+ if (s.length === 0) return "unknown location";
90
+ let I = s[0].trim(), L = I.match(/(?:http[s]?:\/\/.*?\/|)([^:]+):(\d+):(\d+)/);
91
+ if (L) {
92
+ let [, s, I] = L;
93
+ return `[${s.split("/").slice(-2).join("/")}:${I}]`;
91
94
  }
92
- return `[${B}]`;
95
+ return `[${I}]`;
93
96
  } catch {
94
97
  return "[unknown location]";
95
98
  }
96
99
  }
97
- static _log(B, ...V) {
98
- if (g.enable && typeof console[B] == "function") {
99
- let g = this.getCallerInfo();
100
- console[B](g, ...V);
100
+ static _log(I, ...L) {
101
+ if (s.enable && typeof console[I] == "function") {
102
+ let s = this.getCallerInfo();
103
+ console[I](s, ...L);
101
104
  }
102
105
  }
103
- static log(...g) {
104
- this._log("log", ...g);
106
+ static log(...s) {
107
+ this._log("log", ...s);
105
108
  }
106
- static info(...g) {
107
- this._log("info", ...g);
109
+ static info(...s) {
110
+ this._log("info", ...s);
108
111
  }
109
- static warn(...g) {
110
- this._log("warn", ...g);
112
+ static warn(...s) {
113
+ this._log("warn", ...s);
111
114
  }
112
- static error(...g) {
113
- this._log("error", ...g);
115
+ static error(...s) {
116
+ this._log("error", ...s);
114
117
  }
115
- static debug(...g) {
116
- this._log("debug", ...g);
118
+ static debug(...s) {
119
+ this._log("debug", ...s);
117
120
  }
118
- static trace(...g) {
119
- this._log("trace", ...g);
121
+ static trace(...s) {
122
+ this._log("trace", ...s);
120
123
  }
121
- static table(g, B) {
122
- this.enable && console.table(g, B);
124
+ static table(s, I) {
125
+ this.enable && console.table(s, I);
123
126
  }
124
- static time(g) {
125
- this.enable && console.time(g);
127
+ static time(s) {
128
+ this.enable && console.time(s);
126
129
  }
127
- static timeEnd(g) {
128
- this.enable && console.timeEnd(g);
130
+ static timeEnd(s) {
131
+ this.enable && console.timeEnd(s);
129
132
  }
130
133
  }, _isMicro = ref(!1), descriptor = Object.getOwnPropertyDescriptor(window, CONSTANT.IS_MICRO);
131
134
  descriptor ? descriptor.configurable ? Object.defineProperty(window, "__XT_MICRO", {
132
135
  get: () => _isMicro.value,
133
- set: (g) => {
134
- _isMicro.value = g;
136
+ set: (s) => {
137
+ _isMicro.value = s;
135
138
  },
136
139
  configurable: !0,
137
140
  enumerable: !0
138
141
  }) : console.warn("__XT_MICRO 不可配置,无法重定义,已跳过") : Object.defineProperty(window, "__XT_MICRO", {
139
142
  get: () => _isMicro.value,
140
- set: (g) => {
141
- _isMicro.value = g;
143
+ set: (s) => {
144
+ _isMicro.value = s;
142
145
  },
143
146
  configurable: !0,
144
147
  enumerable: !0
145
148
  });
146
- var generateId = (g) => `${CONSTANT.DOM_ID_PREFIX}${g}`, generateURL = (g, B = !1) => {
147
- function V(g) {
148
- return typeof g == "object" && !!g && !Array.isArray(g);
149
- }
150
- let H = typeof g.params == "function" ? g.params() : V(g.params) ? g.params : {}, U = typeof g.token == "function" ? g.token() : V(g.token) ? g.token : "", W = new URL(g.url.indexOf("http") > -1 ? g.url : window.location.origin + g.url), G = getQueryParameter(CONSTANT.URL_PARAM_PREFIX + g.name);
151
- if (!B && G) {
152
- let B = getAbsolutePath(G, W.origin, !0);
153
- if (B) {
154
- ConsoleUtil.log("获取绝对路径", B, g), console.log("123123123================>");
155
- let V = new URL(B, W.origin);
156
- V.searchParams.forEach((g, B) => {
157
- W.searchParams.set(B, g);
158
- }), W.hash = V.hash;
149
+ var generateId = (s) => `${CONSTANT.DOM_ID_PREFIX}${s}`, generateURL = (s, I = !1) => {
150
+ function L(s) {
151
+ return typeof s == "object" && !!s && !Array.isArray(s);
152
+ }
153
+ let R = typeof s.params == "function" ? s.params() : L(s.params) ? s.params : {}, z = typeof s.token == "function" ? s.token() : s.token || "", B = new URL(s.url, window.location.origin), V = getQueryParameter(CONSTANT.URL_PARAM_PREFIX + s.name);
154
+ if (!I && V) {
155
+ let I = getAbsolutePath(V, B.origin, !0);
156
+ if (I) {
157
+ ConsoleUtil.log("获取绝对路径", I, s);
158
+ let L = new URL(I, B.origin);
159
+ L.searchParams.forEach((s, I) => {
160
+ B.searchParams.set(I, s);
161
+ }), B.hash = L.hash;
159
162
  }
160
- clearParentUrl(g.name);
161
- }
162
- if (W.searchParams.set(CONSTANT.IS_MICRO, "true"), W.searchParams.set(CONSTANT.MICRO_NAME, g.name), U && W.searchParams.set(CONSTANT.MICRO_TOKEN, U), H) for (let g of Object.keys(H)) W.searchParams.set(g, H[g]);
163
- return clearParentUrl(g.name), W.href;
164
- }, generateLoading = (g) => {
165
- ConsoleUtil.log("generateLoading", g);
166
- let B = document.createElement("div");
167
- return B.id = generateId(g) + "-loading", B.innerHTML = "应用加载中...", B.style.textAlign = "center", B.style.lineHeight = "100px", B.style.fontSize = "20px", B.style.color = "#999", B.style.position = "absolute", B.style.top = "0", B.style.left = "0", B.style.right = "0", B.style.bottom = "0", B.style.zIndex = "999", B.style.background = "transparent", B.style["mix-blend-mode"] = "difference", B;
168
- }, removeLoading = (g) => {
169
- g.style.opacity = "0", setTimeout(() => {
170
- document.querySelectorAll("#" + g.id).forEach((g) => {
171
- g.remove();
163
+ }
164
+ if (B.searchParams.set(CONSTANT.IS_MICRO, "true"), B.searchParams.set(CONSTANT.MICRO_NAME, s.name), z && B.searchParams.set(CONSTANT.MICRO_TOKEN, z), R) for (let s of Object.keys(R)) B.searchParams.set(s, R[s]);
165
+ return B.href;
166
+ }, generateLoading = (s) => {
167
+ ConsoleUtil.log("generateLoading", s);
168
+ let I = document.createElement("div");
169
+ return I.id = generateId(s) + "-loading", I.innerHTML = "应用加载中...", I.style.textAlign = "center", I.style.lineHeight = "100px", I.style.fontSize = "20px", I.style.color = "#999", I.style.position = "absolute", I.style.top = "0", I.style.left = "0", I.style.right = "0", I.style.bottom = "0", I.style.zIndex = "999", I.style.background = "transparent", I.style["mix-blend-mode"] = "difference", I;
170
+ }, removeLoading = (s) => {
171
+ s.style.opacity = "0", setTimeout(() => {
172
+ document.querySelectorAll("#" + s.id).forEach((s) => {
173
+ s.remove();
172
174
  });
173
175
  }, 500);
174
- }, generateIframe = (g) => {
175
- let B = document.createElement("iframe");
176
- B.id = generateId(g.app.name), B.src = generateURL(g.app), B.style.width = "100%", B.style.height = "100%", B.style.border = "none", B.style.margin = "0", B.style.padding = "0", B.style.backgroundColor = "transparent", B.style["color-scheme"] = "unset", B.style.visibility = "hidden", B.addEventListener("load", (V) => (B.style.visibility = "visible", g.onLoad.call(g, V))), B.addEventListener("error", (B) => g.onError.call(g, B)), B.addEventListener("unload", (B) => g.onUnload.call(g, B));
177
- let V = new MutationObserver((H) => {
178
- ConsoleUtil.trace("监听 body 中子节点的变化2", g.panel), H.forEach((H) => {
179
- Array.from(H.removedNodes).includes(B) && (g.onUnload(new Event("unload")), V.disconnect());
180
- });
181
- });
182
- return V.observe(g.panel.parentNode, {
183
- childList: !0,
184
- subtree: !1
185
- }), B;
176
+ }, activeMicroApp;
177
+ const getActiveMicroApp = () => activeMicroApp, setActiveMicroApp = (s) => {
178
+ activeMicroApp = s;
179
+ };
180
+ var generateIframe = (s) => {
181
+ let I = document.createElement("iframe");
182
+ return I.id = generateId(s.app.name), I.src = generateURL(s.app), I.style.width = "100%", I.style.height = "100%", I.style.border = "none", I.style.margin = "0", I.style.padding = "0", I.style.backgroundColor = "transparent", I.style["color-scheme"] = "unset", I.style.visibility = "hidden", I.addEventListener("load", (I) => s.onLoad.call(s, I)), I.addEventListener("error", (I) => s.onError.call(s, I)), I.addEventListener("unload", (I) => s.onUnload.call(s, I)), I;
186
183
  }, MicroApp = class {
187
184
  app;
188
185
  dom;
189
186
  panel;
190
187
  loading;
191
188
  loadingTimer;
192
- constructor(g) {
193
- return this.app = g, this.dom = void 0, this.panel = void 0, this;
194
- }
195
- mount(g, B = !1) {
196
- let V;
197
- if (g ? (V = typeof g == "string" ? document.querySelector(g) : g, V.innerHTML = "") : V = document.body, V) {
198
- this.panel = V;
199
- let g = !0, H = document.getElementById(generateId(this.app.name));
200
- if (H || (g = !1, H = generateIframe(this), this.dom = H), B ? H.style.display = "none" : H.style.removeProperty("display"), !B) {
201
- let g = generateLoading(this.app.name);
202
- this.loading = g, V.appendChild(g);
203
- }
204
- ConsoleUtil.trace("micro app", this.app.name, g ? "已加载迁移 dom" : "首次加载"), V.appendChild(H);
205
- } else throw Error("没有找到转载子元素的父容器");
189
+ state = "idle";
190
+ active = !1;
191
+ loadPromise;
192
+ resolveLoad;
193
+ observer;
194
+ destroying = !1;
195
+ constructor(s) {
196
+ return this.app = s, this.dom = void 0, this.panel = void 0, this;
197
+ }
198
+ getPanel(s) {
199
+ let I;
200
+ if (s) {
201
+ if (I = typeof s == "string" ? document.querySelector(s) : s, !I) throw Error(`没有找到微应用容器: ${s}`);
202
+ } else I = document.body;
203
+ return I;
204
+ }
205
+ ensureLoaded(s) {
206
+ let I = this.getPanel(s);
207
+ if (this.dom) {
208
+ if (this.panel !== I) throw Error(`微应用 ${this.app.name} 已挂载到其他容器`);
209
+ return this.loadPromise || Promise.resolve();
210
+ }
211
+ this.panel = I, this.state = "loading", this.loadPromise = new Promise((s) => this.resolveLoad = s);
212
+ let L = generateIframe(this);
213
+ return this.dom = L, this.observer = new MutationObserver((s) => {
214
+ !this.destroying && s.some((s) => Array.from(s.removedNodes).includes(L)) && (this.reset(), this.onUnload(new Event("unload")));
215
+ }), this.observer.observe(I, { childList: !0 }), I.appendChild(L), this.loadPromise;
216
+ }
217
+ showLoading() {
218
+ !this.panel || this.loading || (this.loading = generateLoading(this.app.name), this.panel.appendChild(this.loading));
219
+ }
220
+ mount(s) {
221
+ return this.activate(s);
222
+ }
223
+ preload(s) {
224
+ return ConsoleUtil.trace("preload started", this.app.name), this.active = !1, this.ensureLoaded(s);
225
+ }
226
+ activate(s) {
227
+ this.state === "error" && this.destroy(), this.active = !0, setActiveMicroApp(this.app.name);
228
+ let I = this.ensureLoaded(s);
229
+ return this.state === "loading" && this.showLoading(), this.dom && (this.dom.style.visibility = "visible"), (this.state === "loaded" || this.state === "active") && (this.state = "active", this.postLifecycle("activated")), ConsoleUtil.trace("app activated", this.app.name), I;
230
+ }
231
+ deactivate() {
232
+ !this.dom || !this.active || (this.active = !1, this.dom && (this.dom.style.visibility = "hidden"), this.state === "active" && (this.state = "loaded"), this.postLifecycle("deactivated"), ConsoleUtil.trace("app deactivated", this.app.name));
206
233
  }
207
234
  unmount() {
208
- ConsoleUtil.trace("micro unmount app", this.app.name);
209
- let g = document.getElementById(generateId(this.app.name));
210
- if (g) this.app.preload ? (g.style.display = "none", document.body.appendChild(g)) : this.panel?.removeChild(g);
211
- else throw Error("app dom not found");
235
+ this.destroy();
212
236
  }
213
- preloadRender(g) {
214
- this.mount(g);
237
+ preloadRender(s) {
238
+ return this.activate(s);
215
239
  }
216
- preload() {
217
- this.mount(void 0, !0);
240
+ destroy() {
241
+ this.dom && (ConsoleUtil.trace("app destroyed", this.app.name), this.destroying = !0, this.observer?.disconnect(), this.dom.remove(), this.onUnload(new Event("unload")), this.reset(), getActiveMicroApp() === this.app.name && setActiveMicroApp(), this.destroying = !1);
218
242
  }
219
- reload(g = !1) {
220
- let B = this.dom.src;
221
- g && (B = generateURL(this.app, !0), ConsoleUtil.trace("go home", B)), ConsoleUtil.trace("reload app", this.app, B);
222
- let V = new URL(B);
223
- V.searchParams.set("__t", Date.now().toString()), this.dom.style.visibility = "hidden", this.dom.src = V.toString();
243
+ reload(s = !1) {
244
+ if (!this.dom) throw Error(`app dom not found: ${this.app.name}`);
245
+ let I = this.dom.src;
246
+ s && (I = generateURL(this.app, !0), ConsoleUtil.trace("go home", I)), ConsoleUtil.trace("reload app", this.app, I);
247
+ let L = new URL(I);
248
+ L.searchParams.set("__t", Date.now().toString()), this.dom.style.visibility = "hidden", this.state = "loading", this.loadPromise = new Promise((s) => this.resolveLoad = s), this.active && this.showLoading(), this.dom.src = L.toString();
224
249
  }
225
- changeOptions(g) {
226
- ConsoleUtil.trace("changeOptions", this.app, g), this.app = {
250
+ changeOptions(s) {
251
+ ConsoleUtil.trace("changeOptions", this.app, s), this.app = {
227
252
  ...this.app,
228
- ...g
253
+ ...s
229
254
  };
230
255
  }
231
- onLoad(g) {
232
- ConsoleUtil.trace("app onLoad", this.app.name, this.loadingTimer, this.loading), this.loadingTimer && clearTimeout(this.loadingTimer), this.loading && removeLoading(this.loading), _postMicro(this), ConsoleUtil.trace("this.app.onLoad", this.app.onLoad), this.app.onLoad && this.app.onLoad(g, this);
256
+ onLoad(s) {
257
+ ConsoleUtil.trace("app onLoad", this.app.name, this.loadingTimer, this.loading), this.loadingTimer && clearTimeout(this.loadingTimer), this.loading && removeLoading(this.loading), this.loading = void 0, this.state = this.active ? "active" : "loaded", this.dom && (this.dom.style.visibility = this.active ? "visible" : "hidden"), _postMicro(this), this.active && this.postLifecycle("activated"), this.resolveLoad?.(), this.resolveLoad = void 0, ConsoleUtil.trace("preload loaded", this.app.name), ConsoleUtil.trace("this.app.onLoad", this.app.onLoad), this.app.onLoad && this.app.onLoad(s, this);
258
+ }
259
+ onUnload(s) {
260
+ ConsoleUtil.trace("app onUnload", this.app.name), getActiveMicroApp() === this.app.name && clearParentUrl(this.app.name), this.app.onUnload && this.app.onUnload(s, this);
261
+ }
262
+ onError(s) {
263
+ this.state = "error", this.resolveLoad?.(), this.resolveLoad = void 0, ConsoleUtil.error("app onError", this.app.name), this.app.onError && this.app.onError(s, this);
233
264
  }
234
- onUnload(g) {
235
- ConsoleUtil.trace("app onUnload", this.app.name), clearParentUrl(this.app.name), this.app.onUnload && this.app.onUnload(g, this);
265
+ postLifecycle(s) {
266
+ this.dom?.contentWindow?.postMessage({ cmd: `$xt/micro/${this.app.name}/${s}` }, new URL(this.app.url, window.location.origin).origin);
236
267
  }
237
- onError(g) {
238
- ConsoleUtil.error("app onError", this.app.name), this.app.onError && this.app.onError(g, this);
268
+ reset() {
269
+ this.observer?.disconnect(), this.observer = void 0, this.dom = void 0, this.panel = void 0, this.loading = void 0, this.loadPromise = void 0, this.resolveLoad = void 0, this.state = "idle", this.active = !1;
239
270
  }
240
- }, _postMicro = (g) => {
241
- g.dom?.contentWindow?.postMessage({
242
- cmd: `$xt/micro/${g.app.name}`,
271
+ }, _postMicro = (s) => {
272
+ s.dom?.contentWindow?.postMessage({
273
+ cmd: `$xt/micro/${s.app.name}`,
243
274
  data: {
244
- name: g.app.name,
245
- url: g.app.url,
246
- preload: g.app.preload,
247
- sync: g.app.sync || !0
275
+ name: s.app.name,
276
+ url: s.app.url,
277
+ preload: s.app.preload,
278
+ sync: s.app.sync ?? !0
248
279
  }
249
- }, "*");
250
- };
280
+ }, new URL(s.app.url, window.location.origin).origin);
281
+ }, initialized = !1;
251
282
  const mainMicroInit = () => {
252
- window[CONSTANT.MICRO_TYPE] = "parent", window.addEventListener("message", (g) => {
253
- if (g.data.cmd === "$xt/micro/sync") {
254
- ConsoleUtil.trace("父页面接受子应用同步路由信息", g.data);
255
- let B = [
283
+ initialized || (initialized = !0, window[CONSTANT.MICRO_TYPE] = "parent", window.addEventListener("message", (s) => {
284
+ if (s.data?.cmd === "$xt/micro/sync") {
285
+ let I = getApp(s.data?.data?.name);
286
+ if (!isAppMessage(s, I) || getActiveMicroApp() !== I.name) return;
287
+ ConsoleUtil.trace("父页面接受子应用同步路由信息", s.data);
288
+ let L = [
256
289
  CONSTANT.IS_MICRO,
257
290
  CONSTANT.MICRO_NAME,
258
291
  CONSTANT.MICRO_TOKEN
259
- ], V = new URL(window.decodeURIComponent(g.data.data.url), g.origin);
260
- for (let g of B) V.searchParams.delete(g);
261
- ConsoleUtil.trace("tempUrl", V);
262
- let H = clearParentUrl(g.data.data.name), U = new URL(H);
263
- U.searchParams.forEach((g, B) => {
264
- B.startsWith(CONSTANT.URL_PARAM_PREFIX) && U.searchParams.delete(B);
265
- }), ConsoleUtil.trace("mainURL.href", U.href);
266
- let W = addOrReplaceUrlParam(U.href, g.data.data.name, V.href);
267
- ConsoleUtil.trace("curUrl", W), window.history.replaceState(null, "", W);
268
- } else if (g.data.cmd === "$xt/micro/info") {
269
- ConsoleUtil.trace("parent 「$xt/micro/info」 receive message", g.data);
270
- let B = getApp(g.data.data);
271
- g.source.postMessage({
292
+ ], R = new URL(window.decodeURIComponent(s.data.data.url), s.origin);
293
+ for (let s of L) R.searchParams.delete(s);
294
+ ConsoleUtil.trace("tempUrl", R);
295
+ let z = clearParentUrl(s.data.data.name), B = new URL(z);
296
+ ConsoleUtil.trace("mainURL.href", B.href);
297
+ let V = addOrReplaceUrlParam(B.href, s.data.data.name, R.href);
298
+ ConsoleUtil.trace("curUrl", V), window.history.replaceState(window.history.state, "", V);
299
+ } else if (s.data?.cmd === "$xt/micro/info") {
300
+ ConsoleUtil.trace("parent 「$xt/micro/info」 receive message", s.data);
301
+ let I = getApp(s.data.data);
302
+ if (!isAppMessage(s, I)) return;
303
+ s.source.postMessage({
272
304
  cmd: "$xt/micro/info",
273
305
  data: {
274
306
  mainLocation: {
@@ -283,68 +315,76 @@ const mainMicroInit = () => {
283
315
  protocol: window.location.protocol
284
316
  },
285
317
  mainMicroVersion: version,
286
- name: B.name,
287
- url: B.url,
288
- params: B.params,
289
- sync: B.sync,
290
- preload: B.preload
318
+ name: I.name,
319
+ url: I.url,
320
+ params: I.params,
321
+ sync: I.sync,
322
+ preload: I.preload
291
323
  }
292
- }, { targetOrigin: g.origin });
324
+ }, { targetOrigin: s.origin });
293
325
  }
294
- });
295
- }, microInit = async (g = {}) => {
326
+ }));
327
+ };
328
+ var isAppMessage = (s, I) => {
329
+ if (!I?.instance.dom?.contentWindow) return !1;
330
+ let L = new URL(I.url, window.location.origin).origin;
331
+ return s.source === I.instance.dom.contentWindow && s.origin === L;
332
+ };
333
+ const microInit = async (s = {}) => {
296
334
  window[CONSTANT.MICRO_TYPE] = "child";
297
- let B = getQueryParameter(CONSTANT.IS_MICRO), V = getQueryParameter(CONSTANT.MICRO_NAME), H = getQueryParameter(CONSTANT.MICRO_TOKEN);
298
- if (g.authHandler && await g.authHandler(H), ConsoleUtil.trace("child microInit", B, V), B && (window[CONSTANT.IS_MICRO] = B === "true", V && await syncAppInfo(V)), window[CONSTANT.IS_MICRO]) {
299
- function B(g) {
300
- var B = document.styleSheets[0];
301
- if (!B) {
302
- var V = document.createElement("style");
303
- document.head.appendChild(V), B = V.sheet;
335
+ let I = getQueryParameter(CONSTANT.IS_MICRO), L = getQueryParameter(CONSTANT.MICRO_NAME), R = getQueryParameter(CONSTANT.MICRO_TOKEN);
336
+ if (s.authHandler && await s.authHandler(R), ConsoleUtil.trace("child microInit", I, L), I && (window[CONSTANT.IS_MICRO] = I === "true", L && await syncAppInfo(L)), window[CONSTANT.IS_MICRO]) {
337
+ function I(s) {
338
+ var I = document.styleSheets[0];
339
+ if (!I) {
340
+ var L = document.createElement("style");
341
+ document.head.appendChild(L), I = L.sheet;
304
342
  }
305
- B.insertRule(g, B.cssRules.length);
343
+ I.insertRule(s, I.cssRules.length);
306
344
  }
307
- window[CONSTANT.IS_MICRO] && g.hideHeaderCssSelector && (Array.isArray(g.hideHeaderCssSelector) ? g.hideHeaderCssSelector.forEach((g) => {
308
- B(`${g} { display: none !important; }`);
309
- }) : B(`${g.hideHeaderCssSelector} { display: none !important; }`)), await patchIframeHistory(V, window), window.addEventListener("message", async (g) => {
310
- g.data.cmd === `$xt/micro/${V}` && syncUrlToWindow(V);
311
- });
345
+ window[CONSTANT.IS_MICRO] && s.hideHeaderCssSelector && (Array.isArray(s.hideHeaderCssSelector) ? s.hideHeaderCssSelector.forEach((s) => {
346
+ I(`${s} { display: none !important; }`);
347
+ }) : I(`${s.hideHeaderCssSelector} { display: none !important; }`)), await patchIframeHistory(L, window), window.addEventListener("message", async (I) => {
348
+ I.source === window.parent && I.origin === window[CONSTANT.MICRO_APP]?.mainLocation.origin && I.data?.cmd === `$xt/micro/${L}` ? syncUrlToWindow(L) : I.source === window.parent && I.origin === window[CONSTANT.MICRO_APP]?.mainLocation.origin && I.data?.cmd === `$xt/micro/${L}/activated` ? (await syncUrlToWindow(L), await s.onActivated?.()) : I.source === window.parent && I.origin === window[CONSTANT.MICRO_APP]?.mainLocation.origin && I.data?.cmd === `$xt/micro/${L}/deactivated` && await s.onDeactivated?.();
349
+ }), L && await syncUrlToWindow(L);
312
350
  } else ConsoleUtil.warn("当前环境非微应用环境");
313
351
  };
314
- function patchIframeHistory(g, B) {
315
- let V = B.history, H = V.pushState, U = V.replaceState;
316
- V.pushState = function(B, U, W) {
317
- let G = {
318
- ...V.state || {},
319
- ...B,
352
+ function patchIframeHistory(s, I) {
353
+ let L = I.history, R = L.pushState, z = L.replaceState;
354
+ L.pushState = function(I, z, B) {
355
+ let V = {
356
+ ...L.state || {},
357
+ ...I,
320
358
  _patchedByParent: !0
321
359
  };
322
- H.call(V, G, U, W), syncUrlToWindow(g);
323
- }, V.replaceState = function(g, B, H) {
324
- let W = {
325
- ...V.state || {},
326
- ...g,
360
+ R.call(L, V, z, B), syncUrlToWindow(s);
361
+ }, L.replaceState = function(s, I, R) {
362
+ let B = {
363
+ ...L.state || {},
364
+ ...s,
327
365
  _patchedByParent: !0
328
366
  };
329
- U.call(V, W, B, H);
367
+ z.call(L, B, I, R);
330
368
  };
331
369
  }
332
- var syncAppInfo = async (g) => await ipcSyncAppInfo(g).then((g) => {
370
+ var syncAppInfo = async (s) => await ipcSyncAppInfo(s).then((s) => {
333
371
  window[CONSTANT.MICRO_APP] = {
334
372
  microVersion: version,
335
- ...g
373
+ ...s
336
374
  };
337
375
  });
338
- async function syncUrlToWindow(g) {
339
- console.log("syncUrlToWindow", g, window[CONSTANT.MICRO_APP], window.location.href.match(/__XT_MICRO_([^=]+)=/), getQueryParameter(CONSTANT.MICRO_NAME)), ConsoleUtil.trace("syncUrlToWindow", g, window[CONSTANT.MICRO_APP]), window[CONSTANT.MICRO_APP] || await syncAppInfo(g);
340
- let { name: B, sync: V, mainLocation: H } = window[CONSTANT.MICRO_APP], U = window.location.pathname + window.location.search + window.location.hash;
341
- ConsoleUtil.trace("curUrl", U), ConsoleUtil.trace("child", "「$xt/micro/sync」", "send", B, U), window.parent.postMessage({
376
+ async function syncUrlToWindow(s) {
377
+ ConsoleUtil.trace("syncUrlToWindow", s, window[CONSTANT.MICRO_APP]), window[CONSTANT.MICRO_APP] || await syncAppInfo(s);
378
+ let { name: I, sync: L, mainLocation: R } = window[CONSTANT.MICRO_APP];
379
+ if (!L) return;
380
+ let z = window.location.pathname + window.location.search + window.location.hash;
381
+ ConsoleUtil.trace("curUrl", z), ConsoleUtil.trace("child", "「$xt/micro/sync」", "send", I, z), window.parent.postMessage({
342
382
  cmd: "$xt/micro/sync",
343
383
  data: {
344
- name: B,
345
- url: window.encodeURIComponent(U)
384
+ name: I,
385
+ url: window.encodeURIComponent(z)
346
386
  }
347
- }, H.origin);
387
+ }, R.origin);
348
388
  }
349
389
  var _apps = {}, defaultAppOption = {
350
390
  url: "",
@@ -352,78 +392,117 @@ var _apps = {}, defaultAppOption = {
352
392
  sync: !0,
353
393
  preload: !1
354
394
  };
355
- const setupApp = (g) => {
356
- if (!g.url || g.url === "" || g.url === "undefined") {
357
- ConsoleUtil.error("app url is required", g);
395
+ const setupApp = (s) => {
396
+ if (!s.url || s.url === "" || s.url === "undefined") {
397
+ ConsoleUtil.error("app url is required", s);
358
398
  return;
359
399
  }
360
- let B = Object.assign({}, defaultAppOption, g), V = _apps[g.name];
361
- return V ? _apps[g.name] = {
362
- ...V,
363
- ...B
364
- } : _apps[g.name] = {
365
- ...B,
366
- instance: new MicroApp(g)
367
- }, _apps[g.name];
368
- }, getApp = (g) => _apps[g];
369
- var setApp = (g, B) => _apps[g.name] = {
370
- ...g,
371
- ...B
400
+ let I = Object.assign({}, defaultAppOption, s), L = _apps[s.name];
401
+ return L ? (L.instance.changeOptions(I), _apps[s.name] = {
402
+ ...L,
403
+ ...I
404
+ }) : _apps[s.name] = {
405
+ ...I,
406
+ instance: new MicroApp(s)
407
+ }, _apps[s.name];
408
+ }, getApp = (s) => _apps[s], getApps = () => Object.values(_apps);
409
+ var setApp = (s, I) => _apps[s.name] = {
410
+ ...s,
411
+ ...I
372
412
  };
373
- const startApp = (g, B) => new Promise((V, H) => {
374
- let U = getApp(g);
375
- U ? (B && (U.instance.changeOptions(B), U = setApp(U, B)), U.preload ? U.instance.preloadRender(U.el) : U.instance.mount(U.el), V(U)) : H("app not found, please setup app first");
376
- }), stopApp = (g) => {
377
- let B = getApp(g);
378
- B && B.instance.unmount();
379
- }, reloadApp = (g, B = !1) => {
380
- let V = getApp(g);
381
- V && V.instance.reload(B);
382
- }, clearParentUrl = (g) => {
383
- ConsoleUtil.trace("clearParentUrl", g, CONSTANT.URL_PARAM_PREFIX + g);
384
- let B = window.location.href.split("#");
385
- ConsoleUtil.trace("url", B);
386
- let V = new URL(B[0]);
387
- V.searchParams.delete(CONSTANT.URL_PARAM_PREFIX + g);
388
- let H = B.length > 1 ? V.href + "#" + B[1] : V.href;
389
- return window.history.replaceState({}, "", H), H;
390
- }, isMicro = () => window[CONSTANT.IS_MICRO] === !0, isParent = () => window[CONSTANT.MICRO_TYPE] === "parent", createAppUrl = (g, B = window.__XT_MICRO_APP?.name) => {
391
- let V = window.location;
392
- if (isMicro()) V = window.__XT_MICRO_APP.mainLocation;
393
- else if (!B) {
413
+ const startApp = (s, I) => new Promise((L, R) => {
414
+ let z = getApp(s);
415
+ z ? (I && (z.instance.changeOptions(I), z = setApp(z, I)), z.instance.activate(z.el), L(z)) : R("app not found, please setup app first");
416
+ }), stopApp = (s) => {
417
+ let I = getApp(s);
418
+ I && I.instance.destroy();
419
+ }, reloadApp = (s, I = !1) => {
420
+ let L = getApp(s);
421
+ L && L.instance.reload(I);
422
+ }, clearParentUrl = (s) => {
423
+ ConsoleUtil.trace("clearParentUrl", s, CONSTANT.URL_PARAM_PREFIX + s);
424
+ let I = window.location.href.split("#");
425
+ ConsoleUtil.trace("url", I);
426
+ let L = new URL(I[0]);
427
+ L.searchParams.delete(CONSTANT.URL_PARAM_PREFIX + s);
428
+ let R = I.length > 1 ? L.href + "#" + I[1] : L.href;
429
+ return window.history.replaceState(window.history.state, "", R), R;
430
+ }, isMicro = () => window[CONSTANT.IS_MICRO] === !0, isParent = () => window[CONSTANT.MICRO_TYPE] === "parent", createAppUrl = (s, I = window.__XT_MICRO_APP?.name) => {
431
+ let L = window.location;
432
+ if (isMicro()) L = window.__XT_MICRO_APP.mainLocation;
433
+ else if (!I) {
394
434
  ConsoleUtil.error("在主应用中需要传入应用名称");
395
435
  return;
396
436
  }
397
- return `${V.origin}${V.pathname}?__XT_MICRO_${B}=${encodeURIComponent(g)}${V.hash}`;
437
+ let R = new URL(L.href);
438
+ return R.searchParams.set(CONSTANT.URL_PARAM_PREFIX + I, s), R.href;
398
439
  };
399
440
  var XTMicroView_default = /* @__PURE__ */ defineComponent({
400
441
  __name: "XTMicroView",
401
442
  props: { appId: String },
402
- setup(B) {
403
- let K = B, q = ref(), J = () => {
404
- K.appId && startApp(K.appId, {
405
- el: q.value,
406
- onUnload(g, B) {
407
- ConsoleUtil.trace("on unload", B.app.name);
443
+ setup(s) {
444
+ let L = s, z = ref(), B = () => {
445
+ L.appId && getApp(L.appId)?.preload && ConsoleUtil.warn(`微应用 ${L.appId} 的 preload 需要使用 XTMicroHost,当前按即时加载处理`), L.appId && startApp(L.appId, {
446
+ el: z.value,
447
+ onUnload(s, I) {
448
+ ConsoleUtil.trace("on unload", I.app.name);
408
449
  }
409
- }).then((g) => {
410
- ConsoleUtil.trace("app mounted", K.appId);
450
+ }).then((s) => {
451
+ ConsoleUtil.trace("app mounted", L.appId);
411
452
  });
412
453
  };
413
- return watch(() => K.appId, (g, B) => {
414
- g !== B && B && stopApp(B), J();
454
+ return watch(() => L.appId, (s, I) => {
455
+ s !== I && I && stopApp(I), B();
415
456
  }), onMounted(() => {
416
- J();
417
- }), onUnmounted(() => {
418
- ConsoleUtil.trace("「micro」", "app unmount", K.appId), clearParentUrl(K.appId);
419
- }), (B, H) => (openBlock(), createElementBlock("div", mergeProps({
457
+ B();
458
+ }), onBeforeUnmount(() => {
459
+ ConsoleUtil.trace("「micro」", "app unmount", L.appId), L.appId && stopApp(L.appId), L.appId && clearParentUrl(L.appId);
460
+ }), (s, L) => (openBlock(), createElementBlock("div", mergeProps({
420
461
  ref_key: "refPanel",
421
- ref: q
422
- }, B.$attrs, { class: "xt-micro" }), null, 16));
462
+ ref: z
463
+ }, s.$attrs, { class: "xt-micro" }), null, 16));
464
+ }
465
+ }), _hoisted_1 = { class: "xt-micro-host" }, XTMicroHost_default = /* @__PURE__ */ defineComponent({
466
+ __name: "XTMicroHost",
467
+ props: { activeApp: {} },
468
+ setup(L) {
469
+ let R = L, H = getApps(), U = {}, W = /* @__PURE__ */ new Set(), G = !1, K, q, J, Y = (s, I) => {
470
+ I instanceof HTMLElement && (U[s] = I);
471
+ }, X = async (s) => {
472
+ for (let I of H) I.name !== s && I.instance.deactivate();
473
+ if (setActiveMicroApp(s), !s) return;
474
+ let I = H.find((I) => I.name === s), L = U[s];
475
+ !I || !L || (W.add(s), await I.instance.activate(L));
476
+ }, Z = (s) => new Promise((I) => {
477
+ J = window.setTimeout(I, s);
478
+ }), Q = (s) => {
479
+ typeof window.requestIdleCallback == "function" ? K = window.requestIdleCallback(s) : q = setTimeout(s, 200);
480
+ }, $ = async (s) => {
481
+ let I = s.shift();
482
+ if (!I || G) return;
483
+ let L = U[I.name];
484
+ if (!L || I.instance.state !== "idle") {
485
+ Q(() => $(s));
486
+ return;
487
+ }
488
+ W.add(I.name), await Promise.race([I.instance.preload(L), Z(15e3)]), J !== void 0 && clearTimeout(J), G || Q(() => $(s));
489
+ };
490
+ return onMounted(async () => {
491
+ await nextTick(), await X(R.activeApp);
492
+ let s = H.filter((s) => s.preload && s.name !== R.activeApp);
493
+ s.forEach((s) => ConsoleUtil.trace("preload queued", s.name)), Q(() => $(s));
494
+ }), watch(() => R.activeApp, X), onBeforeUnmount(() => {
495
+ G = !0, K !== void 0 && window.cancelIdleCallback(K), q !== void 0 && clearTimeout(q), J !== void 0 && window.clearTimeout(J), W.forEach((s) => H.find((I) => I.name === s)?.instance.destroy()), setActiveMicroApp();
496
+ }), (R, z) => (openBlock(), createElementBlock("div", _hoisted_1, [(openBlock(!0), createElementBlock(Fragment, null, renderList(unref(H), (s) => (openBlock(), createElementBlock("div", {
497
+ key: s.name,
498
+ ref_for: !0,
499
+ ref: (I) => Y(s.name, I),
500
+ class: normalizeClass(["xt-micro-panel", { "is-active": s.name === L.activeApp }])
501
+ }, null, 2))), 128))]));
423
502
  }
424
503
  });
425
504
  window[CONSTANT.MICRO_VERSION] = version, window.micro_api = { debug: ConsoleUtil.setEnable };
426
- var src_default = { install: (g, B = {}) => {
427
- g.component("xt-micro-view", XTMicroView_default), mainMicroInit();
505
+ var src_default = { install: (s, I = {}) => {
506
+ s.component("xt-micro-view", XTMicroView_default), s.component("xt-micro-host", XTMicroHost_default), mainMicroInit();
428
507
  } };
429
- export { XTMicroView_default as XTMicroView, clearParentUrl, createAppUrl, src_default as default, getApp, isMicro, isParent, microInit, reloadApp, setupApp, startApp, stopApp, utils_exports as utils };
508
+ export { XTMicroHost_default as XTMicroHost, XTMicroView_default as XTMicroView, clearParentUrl, createAppUrl, src_default as default, getApp, getApps, isMicro, isParent, microInit, reloadApp, setupApp, startApp, stopApp, utils_exports as utils };
@@ -6,6 +6,7 @@ import { microInit } from './child';
6
6
  */
7
7
  export declare const setupApp: (AppOption: AppOption) => App | undefined;
8
8
  export declare const getApp: (name: string) => App;
9
+ export declare const getApps: () => App[];
9
10
  /**
10
11
  * 启动微应用
11
12
  * @param name 应用名称
@@ -0,0 +1,5 @@
1
+ type __VLS_Props = {
2
+ activeApp?: string;
3
+ };
4
+ declare const _default: import('vue').DefineComponent<__VLS_Props, {}, {}, {}, {}, import('vue').ComponentOptionsMixin, import('vue').ComponentOptionsMixin, {}, string, import('vue').PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import('vue').ComponentProvideOptions, true, {}, HTMLDivElement>;
5
+ export default _default;
@@ -1,8 +1,9 @@
1
1
  import { App } from 'vue';
2
2
  import { default as XTMicroView } from './components/XTMicroView.vue';
3
+ import { default as XTMicroHost } from './components/XTMicroHost.vue';
3
4
  export * from './api';
4
5
  import * as utils from "./utils";
5
- export { XTMicroView, utils };
6
+ export { XTMicroHost, XTMicroView, utils };
6
7
  declare const _default: {
7
8
  install: (app: App, _options?: any) => void;
8
9
  };
@@ -1,32 +1,44 @@
1
- import { AppOption, App } from './types';
1
+ import { AppOption, App, MicroAppState } from './types';
2
2
  export declare const isMicro: import('vue').Ref<boolean, boolean>;
3
+ export declare const getActiveMicroApp: () => string;
4
+ export declare const setActiveMicroApp: (name?: string) => void;
3
5
  export declare class MicroApp {
4
6
  app: App | AppOption;
5
7
  dom: HTMLIFrameElement | undefined;
6
8
  panel: HTMLElement | undefined;
7
9
  loading: HTMLElement | undefined;
8
10
  loadingTimer: NodeJS.Timeout | undefined;
11
+ state: MicroAppState;
12
+ active: boolean;
13
+ private loadPromise?;
14
+ private resolveLoad?;
15
+ private observer?;
16
+ private destroying;
9
17
  constructor(app: AppOption);
10
- mount(el: HTMLElement | string | undefined, isHide?: boolean): void;
18
+ private getPanel;
19
+ private ensureLoaded;
20
+ private showLoading;
21
+ mount(el: HTMLElement | string | undefined): Promise<void>;
22
+ preload(el: HTMLElement | string | undefined): Promise<void>;
23
+ activate(el: HTMLElement | string | undefined): Promise<void>;
24
+ deactivate(): void;
11
25
  unmount(): void;
12
26
  /**
13
27
  * 预加载渲染
14
28
  * TODO 还差用户切走之后,如何将ifr还原回去,等待下次载入
15
29
  * @param el 挂载dom对象
16
30
  */
17
- preloadRender(el: HTMLElement | string | undefined): void;
31
+ preloadRender(el: HTMLElement | string | undefined): Promise<void>;
18
32
  /**
19
33
  * 预加载app,先放到body,待启动时,挪过来
20
34
  */
21
- preload(): void;
35
+ destroy(): void;
22
36
  reload(isGoHome?: boolean): void;
23
37
  changeOptions(options: Partial<AppOption>): void;
24
38
  onLoad(_event: Event): void;
25
39
  onUnload(_event: Event): void;
26
40
  onError(_event: Event): void;
41
+ private postLifecycle;
42
+ private reset;
27
43
  }
28
- /**
29
- * 初始化主应用微前端
30
- * 包括:监听子应用消息,同步子应用路由到主应用上
31
- */
32
44
  export declare const mainMicroInit: () => void;
@@ -5,7 +5,7 @@ export interface AppOption {
5
5
  url: string;
6
6
  el?: HTMLElement | string;
7
7
  preload?: boolean;
8
- token?: () => string | string;
8
+ token?: string | (() => string);
9
9
  params?: {
10
10
  [key: string]: any;
11
11
  };
@@ -19,8 +19,11 @@ export interface App extends AppOption {
19
19
  }
20
20
  export interface MicroInitOptions {
21
21
  hideHeaderCssSelector?: string | string[];
22
- authHandler?: (token: string) => void;
22
+ authHandler?: (token: string | null) => void | Promise<void>;
23
+ onActivated?: () => void | Promise<void>;
24
+ onDeactivated?: () => void | Promise<void>;
23
25
  }
26
+ export type MicroAppState = "idle" | "loading" | "loaded" | "error" | "active";
24
27
  declare global {
25
28
  interface Window {
26
29
  [key: string]: any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xingtukeji/micro",
3
- "version": "1.1.27",
3
+ "version": "1.2.0",
4
4
  "private": false,
5
5
  "description": "",
6
6
  "main": "dist/index.js",