Skip to content

Commit

Permalink
🐛 fix the simulated head issues (#2121)
Browse files Browse the repository at this point in the history
Co-authored-by: youzhi.lk <youzhi.lk@antfin.com>
  • Loading branch information
kuitos and youzhi.lk committed May 29, 2022
1 parent bbae701 commit 3d80797
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 41 deletions.
12 changes: 6 additions & 6 deletions examples/main/index.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import 'zone.js'; // for angular subapp
import { registerMicroApps, runAfterFirstMounted, setDefaultMountApp, start, initGlobalState } from '../../es';
import { initGlobalState, registerMicroApps, runAfterFirstMounted, setDefaultMountApp, start } from '../../es';
import './index.less';

/**
* 主应用 **可以使用任意技术栈**
* 以下分别是 React 和 Vue 的示例,可切换尝试
*/
import render from './render/ReactRender';

// import render from './render/VueRender';

/**
* Step1 初始化应用(可选)
*/
render({ loading: true });

const loader = loading => render({ loading });
const loader = (loading) => render({ loading });

/**
* Step2 注册子应用
Expand Down Expand Up @@ -67,17 +67,17 @@ registerMicroApps(
],
{
beforeLoad: [
app => {
(app) => {
console.log('[LifeCycle] before load %c%s', 'color: green;', app.name);
},
],
beforeMount: [
app => {
(app) => {
console.log('[LifeCycle] before mount %c%s', 'color: green;', app.name);
},
],
afterUnmount: [
app => {
(app) => {
console.log('[LifeCycle] after unmount %c%s', 'color: green;', app.name);
},
],
Expand Down
13 changes: 10 additions & 3 deletions examples/react15/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
* @author Kuitos
* @since 2019-05-16
*/
import './public-path';
import 'antd/dist/antd.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

import 'antd/dist/antd.min.css';
import './index.css';
import './public-path';

export async function bootstrap() {
console.log('[react15] react app bootstraped');
Expand All @@ -24,6 +23,14 @@ export async function mount(props = {}) {
import('./dynamic.css').then(() => {
console.log('[react15] dynamic style load');
});

const styleElement = document.createElement('style');
styleElement.innerText = '.react15-icon { height: 400px }';
document.head.appendChild(styleElement);

setTimeout(() => {
document.head.removeChild(styleElement);
}, 2000);
}

export async function unmount(props) {
Expand Down
3 changes: 2 additions & 1 deletion src/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ test('should wrap string with div', () => {
const ret = factory(tpl);

expect(ret).toBe(
`<div id="__qiankun_microapp_wrapper_for_react_16__" data-name="react16" data-version="${version}">${tpl}</div>`,
// eslint-disable-next-line max-len
`<div id="__qiankun_microapp_wrapper_for_react_16__" data-name="react16" data-version="${version}"><qiankun-head></qiankun-head>${tpl}</div>`,
);
});

Expand Down
50 changes: 25 additions & 25 deletions src/sandbox/patchers/dynamicAppend/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,19 @@ const STYLE_TAG_NAME = 'STYLE';

export const styleElementTargetSymbol = Symbol('target');

type DynamicAppendTarget = 'head' | 'body';
type DynamicDomMutationTarget = 'head' | 'body';

declare global {
interface HTMLLinkElement {
[styleElementTargetSymbol]: DynamicAppendTarget;
[styleElementTargetSymbol]: DynamicDomMutationTarget;
}

interface HTMLStyleElement {
[styleElementTargetSymbol]: DynamicAppendTarget;
[styleElementTargetSymbol]: DynamicDomMutationTarget;
}
}

export const getAppWrapperHeadElement = (appWrapper: Element | ShadowRoot) => {
export const getAppWrapperHeadElement = (appWrapper: Element | ShadowRoot): Element => {
const rootElement = 'host' in appWrapper ? appWrapper.host : appWrapper;
return rootElement.getElementsByTagName(qiankunHeadTagName)[0];
};
Expand Down Expand Up @@ -158,7 +158,7 @@ export type ContainerConfig = {
appName: string;
proxy: WindowProxy;
strictGlobal: boolean;
dynamicStyleSheetElements: HTMLStyleElement[];
dynamicStyleSheetElements: Array<HTMLStyleElement | HTMLLinkElement>;
appWrapperGetter: CallableFunction;
scopedCSS: boolean;
excludeAssetFilter?: CallableFunction;
Expand All @@ -168,7 +168,7 @@ function getOverwrittenAppendChildOrInsertBefore(opts: {
rawDOMAppendOrInsertBefore: <T extends Node>(newChild: T, refChild?: Node | null) => T;
isInvokedByMicroApp: (element: HTMLElement) => boolean;
containerConfigGetter: (element: HTMLElement) => ContainerConfig;
target: DynamicAppendTarget;
target: DynamicDomMutationTarget;
}) {
return function appendChildOrInsertBefore<T extends Node>(
this: HTMLHeadElement | HTMLBodyElement,
Expand Down Expand Up @@ -209,7 +209,6 @@ function getOverwrittenAppendChildOrInsertBefore(opts: {
});

const appWrapper = appWrapperGetter();
const mountDOM = target === 'head' ? getAppWrapperHeadElement(appWrapper) : appWrapper;

if (scopedCSS) {
// exclude link elements like <link rel="icon" href="favicon.ico">
Expand All @@ -224,16 +223,17 @@ function getOverwrittenAppendChildOrInsertBefore(opts: {
: frameworkConfiguration.fetch?.fn;
stylesheetElement = convertLinkAsStyle(
element,
(styleElement) => css.process(mountDOM, styleElement, appName),
(styleElement) => css.process(appWrapper, styleElement, appName),
fetch,
);
dynamicLinkAttachedInlineStyleMap.set(element, stylesheetElement);
} else {
css.process(mountDOM, stylesheetElement, appName);
css.process(appWrapper, stylesheetElement, appName);
}
}

// eslint-disable-next-line no-shadow
const mountDOM = target === 'head' ? getAppWrapperHeadElement(appWrapper) : appWrapper;

dynamicStyleSheetElements.push(stylesheetElement);
const referenceNode = mountDOM.contains(refChild) ? refChild : null;
return rawDOMAppendOrInsertBefore.call(mountDOM, stylesheetElement, referenceNode);
Expand Down Expand Up @@ -301,22 +301,28 @@ function getOverwrittenAppendChildOrInsertBefore(opts: {

function getNewRemoveChild(
headOrBodyRemoveChild: typeof HTMLElement.prototype.removeChild,
appWrapperGetterGetter: (element: HTMLElement) => ContainerConfig['appWrapperGetter'],
containerConfigGetter: (element: HTMLElement) => ContainerConfig,
target: DynamicDomMutationTarget,
) {
return function removeChild<T extends Node>(this: HTMLHeadElement | HTMLBodyElement, child: T) {
const { tagName } = child as any;
if (!isHijackingTag(tagName)) return headOrBodyRemoveChild.call(this, child) as T;

try {
let attachedElement: Node;
const { appWrapperGetter, dynamicStyleSheetElements } = containerConfigGetter(child as any);

switch (tagName) {
case STYLE_TAG_NAME:
case LINK_TAG_NAME: {
attachedElement = (dynamicLinkAttachedInlineStyleMap.get(child as any) as Node) || child;
attachedElement = dynamicLinkAttachedInlineStyleMap.get(child as any) || child;
// try to remove the dynamic style sheet
dynamicStyleSheetElements.splice(dynamicStyleSheetElements.indexOf(attachedElement as any), 1);
break;
}

case SCRIPT_TAG_NAME: {
attachedElement = (dynamicScriptAttachedCommentMap.get(child as any) as Node) || child;
attachedElement = dynamicScriptAttachedCommentMap.get(child as any) || child;
break;
}

Expand All @@ -325,11 +331,11 @@ function getNewRemoveChild(
}
}

// container may had been removed while app unmounting if the removeChild action was async
const appWrapperGetter = appWrapperGetterGetter(child as any);
const container = appWrapperGetter();
const appWrapper = appWrapperGetter();
const container = target === 'head' ? getAppWrapperHeadElement(appWrapper) : appWrapper;
// container might have been removed while app unmounting if the removeChild action was async
if (container.contains(attachedElement)) {
return rawRemoveChild.call(container, attachedElement) as T;
return rawRemoveChild.call(attachedElement.parentNode, attachedElement) as T;
}
} catch (e) {
console.warn(e);
Expand Down Expand Up @@ -375,14 +381,8 @@ export function patchHTMLDynamicAppendPrototypeFunctions(
HTMLHeadElement.prototype.removeChild === rawHeadRemoveChild &&
HTMLBodyElement.prototype.removeChild === rawBodyRemoveChild
) {
HTMLHeadElement.prototype.removeChild = getNewRemoveChild(
rawHeadRemoveChild,
(element) => containerConfigGetter(element).appWrapperGetter,
);
HTMLBodyElement.prototype.removeChild = getNewRemoveChild(
rawBodyRemoveChild,
(element) => containerConfigGetter(element).appWrapperGetter,
);
HTMLHeadElement.prototype.removeChild = getNewRemoveChild(rawHeadRemoveChild, containerConfigGetter, 'head');
HTMLBodyElement.prototype.removeChild = getNewRemoveChild(rawBodyRemoveChild, containerConfigGetter, 'body');
}

return function unpatch() {
Expand Down
2 changes: 1 addition & 1 deletion src/sandbox/patchers/dynamicAppend/forStrictSandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export function patchStrictSandbox(
if (mounting) mountingPatchCount--;

const allMicroAppUnmounted = mountingPatchCount === 0 && bootstrappingPatchCount === 0;
// release the overwrite prototype after all the micro apps unmounted
// release the overwritten prototype after all the micro apps unmounted
if (allMicroAppUnmounted) {
unpatchDynamicAppendPrototypeFunctions();
unpatchDocumentCreate();
Expand Down
16 changes: 12 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,18 @@ export const qiankunHeadTagName = 'qiankun-head';

export function getDefaultTplWrapper(name: string) {
return (tpl: string) => {
// We need to mock a head placeholder as native head element will be erased by browser in micro app
const tplWithSimulatedHead = tpl
.replace('<head>', `<${qiankunHeadTagName}>`)
.replace('</head>', `</${qiankunHeadTagName}>`);
let tplWithSimulatedHead: string;

if (tpl.indexOf('<head>') !== -1) {
// We need to mock a head placeholder as native head element will be erased by browser in micro app
tplWithSimulatedHead = tpl
.replace('<head>', `<${qiankunHeadTagName}>`)
.replace('</head>', `</${qiankunHeadTagName}>`);
} else {
// Some template might not be a standard html document, thus we need to add a simulated head tag for them
tplWithSimulatedHead = `<${qiankunHeadTagName}></${qiankunHeadTagName}>${tpl}`;
}

return `<div id="${getWrapperId(
name,
)}" data-name="${name}" data-version="${version}">${tplWithSimulatedHead}</div>`;
Expand Down
2 changes: 1 addition & 1 deletion src/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { version } from '../package.json';
export const version = '2.7.1';

1 comment on commit 3d80797

@vercel
Copy link

@vercel vercel bot commented on 3d80797 May 29, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.