Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 121 additions & 0 deletions packages/wujie-core/__test__/unit/event-listener-cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/**
* 降级模式下节点事件监听缓存需与原生语义一致:
* 以 type + handler + capture 识别监听;once 监听触发后不再被恢复。
*/

export {};

const { recordEventListeners, recoverEventListeners, recoverDocumentListeners } = require("../../src/iframe");

describe("recordEventListeners", () => {
let iframeWindow: Window;
let iframeDocument: Document;
let sandbox: { elementEventCacheMap: WeakMap<Node, any[]> };

beforeEach(() => {
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
iframeWindow = iframe.contentWindow;
iframeDocument = iframe.contentDocument;
sandbox = { elementEventCacheMap: new WeakMap() };
(iframeWindow as any).__WUJIE = sandbox;
recordEventListeners(iframeWindow);
});

afterEach(() => {
document.body.innerHTML = "";
});

function createButton(): HTMLElement {
const el = iframeDocument.createElement("button");
iframeDocument.body.appendChild(el);
return el;
}

const records = (node: Node) => (sandbox.elementEventCacheMap.get(node) || []).map((r) => [r.type, r.capture]);

it("同一 handler 的 capture 与 bubble 分别记录,重复添加不重复记录", () => {
const el = createButton();
const handler = jest.fn();
el.addEventListener("click", handler);
el.addEventListener("click", handler, true);
el.addEventListener("click", handler, { capture: true });
el.addEventListener("click", handler, false);
expect(records(el)).toEqual([
["click", false],
["click", true],
]);
});

it("移除 capture 监听只删除 capture 记录", () => {
const el = createButton();
const handler = jest.fn();
el.addEventListener("click", handler);
el.addEventListener("click", handler, true);
el.removeEventListener("click", handler, { capture: true });
expect(records(el)).toEqual([["click", false]]);
el.removeEventListener("click", handler);
expect(sandbox.elementEventCacheMap.has(el)).toBe(false);
});

it("once 监听触发后删除记录,恢复后不会再次触发", () => {
const el = createButton();
const handler = jest.fn();
el.addEventListener("click", handler, { once: true });
el.click();
expect(handler).toHaveBeenCalledTimes(1);
expect(sandbox.elementEventCacheMap.has(el)).toBe(false);

recoverEventListeners(iframeDocument.documentElement, iframeWindow);
el.click();
expect(handler).toHaveBeenCalledTimes(1);
});

it("once 监听触发前被移除时,同时移除内部清理监听", () => {
const el = createButton();
const handler = jest.fn();
el.addEventListener("click", handler, { once: true });
el.removeEventListener("click", handler);
expect(sandbox.elementEventCacheMap.has(el)).toBe(false);

const other = jest.fn();
el.addEventListener("click", other);
el.click();
expect(handler).not.toHaveBeenCalled();
expect(records(el)).toEqual([["click", false]]);
});

it("once 监听被更早的 stopImmediatePropagation 拦截时保留记录", () => {
const el = createButton();
const handler = jest.fn();
let block = true;
el.addEventListener("click", (e) => block && e.stopImmediatePropagation());
el.addEventListener("click", handler, { once: true });
el.click();
expect(handler).not.toHaveBeenCalled();
expect(records(el)).toEqual([
["click", false],
["click", false],
]);

block = false;
el.click();
expect(handler).toHaveBeenCalledTimes(1);
expect(records(el)).toEqual([["click", false]]);
});

it("恢复到新根节点后,once 监听触发时清理新节点上的记录", () => {
const oldRoot = iframeDocument.documentElement;
const newRoot = iframeDocument.createElement("html");
const handler = jest.fn();
oldRoot.addEventListener("click", handler, { once: true });

recoverDocumentListeners(oldRoot, newRoot, iframeWindow);
expect(records(newRoot)).toEqual([["click", false]]);

newRoot.dispatchEvent(new (iframeWindow as any).Event("click"));
newRoot.dispatchEvent(new (iframeWindow as any).Event("click"));
expect(handler).toHaveBeenCalledTimes(1);
expect(sandbox.elementEventCacheMap.has(newRoot)).toBe(false);
});
});
84 changes: 54 additions & 30 deletions packages/wujie-core/src/iframe.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import WuJie from "./sandbox";
import WuJie, { EventListenerRecord } from "./sandbox";
import { ScriptObject } from "./template";
import { renderElementToContainer } from "./shadow";
import { syncUrlToWindow } from "./sync";
Expand Down Expand Up @@ -407,20 +407,48 @@ export function patchDegradeInstanceofAcrossRealms(appWindow: Window, renderWind
/**
* 记录节点的监听事件
*/
function recordEventListeners(iframeWindow: Window) {
function getListenerCapture(options?: boolean | EventListenerOptions): boolean {
return typeof options === "boolean" ? options : !!options?.capture;
}

/**
* 记录节点上的事件监听,供降级保活场景恢复。
* 与原生一致,以 type + handler + capture 识别同一个监听;
* once 监听触发后原生会自动移除且不经过 removeEventListener,需同步清理记录,否则恢复时会被重新绑定。
*/
export function recordEventListeners(iframeWindow: Window) {
const sandbox = iframeWindow.__WUJIE;
const removeRecord = (node: Node, record: EventListenerRecord) => {
const list = sandbox.elementEventCacheMap?.get(node);
if (!list) return;
const index = list.indexOf(record);
if (index !== -1) list.splice(index, 1);
if (!list.length) sandbox.elementEventCacheMap.delete(node);
};

iframeWindow.Node.prototype.addEventListener = function (
type: string,
handler: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions
): void {
// 添加事件缓存
const elementListenerList = sandbox.elementEventCacheMap.get(this);
if (elementListenerList) {
if (!elementListenerList.find((listener) => listener.type === type && listener.handler === handler)) {
elementListenerList.push({ type, handler, options });
const capture = getListenerCapture(options);
const elementListenerList = sandbox.elementEventCacheMap.get(this) || [];
const exists = elementListenerList.some(
(listener) => listener.type === type && listener.handler === handler && listener.capture === capture
);
if (!exists) {
const record: EventListenerRecord = { type, handler, options, capture };
if (handler && typeof options === "object" && options.once) {
// 先于业务监听注册:业务监听被更早的 stopImmediatePropagation 拦截时(原生不会消耗 once),清理也不执行。
// 以 this(currentTarget)定位节点,记录在恢复时被迁移到新节点后依然有效
record.onceCleanup = function (this: Node) {
removeRecord(this, record);
};
rawAddEventListener.call(this, type, record.onceCleanup, { capture, once: true });
}
} else sandbox.elementEventCacheMap.set(this, [{ type, handler, options }]);
elementListenerList.push(record);
sandbox.elementEventCacheMap.set(this, elementListenerList);
}
return rawAddEventListener.call(this, type, handler, options);
};

Expand All @@ -429,37 +457,38 @@ function recordEventListeners(iframeWindow: Window) {
handler: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions
): void {
// 清除缓存
const elementListenerList = sandbox.elementEventCacheMap.get(this);
if (elementListenerList) {
const index = elementListenerList?.findIndex((ele) => ele.type === type && ele.handler === handler);
index !== -1 && elementListenerList.splice(index, 1);
}
if (!elementListenerList?.length) {
sandbox.elementEventCacheMap.delete(this);
const capture = getListenerCapture(options);
const record = sandbox.elementEventCacheMap
.get(this)
?.find((listener) => listener.type === type && listener.handler === handler && listener.capture === capture);
if (record) {
if (record.onceCleanup) rawRemoveEventListener.call(this, type, record.onceCleanup, { capture });
removeRecord(this, record);
}
return rawRemoveEventListener.call(this, type, handler, options);
};
}

function rebindListener(node: Node, listener: EventListenerRecord) {
if (listener.onceCleanup) {
rawAddEventListener.call(node, listener.type, listener.onceCleanup, { capture: listener.capture, once: true });
}
node.addEventListener(listener.type, listener.handler, listener.options);
}

/**
* 恢复节点的监听事件
*/
export function recoverEventListeners(rootElement: Element | ChildNode, iframeWindow: Window) {
const sandbox = iframeWindow.__WUJIE;
const elementEventCacheMap: WeakMap<
Node,
Array<{ type: string; handler: EventListenerOrEventListenerObject; options: any }>
> = new WeakMap();
const elementEventCacheMap: WeakMap<Node, Array<EventListenerRecord>> = new WeakMap();
const ElementIterator = document.createTreeWalker(rootElement, NodeFilter.SHOW_ELEMENT, null, false);
let nextElement = ElementIterator.currentNode;
while (nextElement) {
const elementListenerList = sandbox.elementEventCacheMap.get(nextElement);
if (elementListenerList?.length) {
elementEventCacheMap.set(nextElement, elementListenerList);
elementListenerList.forEach((listener) => {
nextElement.addEventListener(listener.type, listener.handler, listener.options);
});
elementListenerList.forEach((listener) => rebindListener(nextElement, listener));
}
nextElement = ElementIterator.nextNode() as HTMLElement;
}
Expand All @@ -475,16 +504,11 @@ export function recoverDocumentListeners(
iframeWindow: Window
) {
const sandbox = iframeWindow.__WUJIE;
const elementEventCacheMap: WeakMap<
Node,
Array<{ type: string; handler: EventListenerOrEventListenerObject; options: any }>
> = new WeakMap();
const elementEventCacheMap: WeakMap<Node, Array<EventListenerRecord>> = new WeakMap();
const elementListenerList = sandbox.elementEventCacheMap.get(oldRootElement);
if (elementListenerList?.length) {
elementEventCacheMap.set(newRootElement, elementListenerList);
elementListenerList.forEach((listener) => {
newRootElement.addEventListener(listener.type, listener.handler, listener.options);
});
elementListenerList.forEach((listener) => rebindListener(newRootElement, listener));
}
sandbox.elementEventCacheMap = elementEventCacheMap;
}
Expand Down
14 changes: 10 additions & 4 deletions packages/wujie-core/src/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ import { WUJIE_DATA_ATTACH_CSS_FLAG, WUJIE_APP_ID, WUJIE_FONT_STYLE_CONTAINER_AT
import { plugin, ScriptObjectLoader, loadErrorHandler } from "./index";

export type lifecycle = (appWindow: Window) => any;
/** 降级模式下节点事件监听的缓存记录 */
export type EventListenerRecord = {
type: string;
handler: EventListenerOrEventListenerObject;
options: any;
capture?: boolean;
/** once 监听触发后用于清理记录的内部监听 */
onceCleanup?: () => void;
};
type lifecycles = {
beforeLoad: lifecycle;
beforeMount: lifecycle;
Expand Down Expand Up @@ -136,10 +145,7 @@ export default class Wujie {
/** 子应用body元素 */
public body: HTMLBodyElement;
/** 子应用dom监听事件留存,当降级时用于保存元素事件 */
public elementEventCacheMap: WeakMap<
Node,
Array<{ type: string; handler: EventListenerOrEventListenerObject; options: any }>
> = new WeakMap();
public elementEventCacheMap: WeakMap<Node, Array<EventListenerRecord>> = new WeakMap();
/** 子应用window监听事件 */
public iframeAddEventListeners?: Array<string>;
/** 子应用iframe on事件 */
Expand Down
Loading