Skip to content

Commit

Permalink
refactor(stage,editor): stage销毁后释放内部变量
Browse files Browse the repository at this point in the history
  • Loading branch information
roymondchen committed Aug 22, 2024
1 parent 2d285d2 commit 62b2da7
Show file tree
Hide file tree
Showing 19 changed files with 171 additions and 135 deletions.
8 changes: 6 additions & 2 deletions packages/editor/src/hooks/use-stage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { computed, watch } from 'vue';
import { computed, onBeforeUnmount, watch } from 'vue';

import type { MNode } from '@tmagic/schema';
import StageCore, { GuidesType, RemoveEventData, SortEventData, UpdateEventData } from '@tmagic/stage';
Expand Down Expand Up @@ -62,7 +62,7 @@ export const useStage = (stageOptions: StageOptions) => {
},
);

stage.mask.setGuides([
stage.mask?.setGuides([
getGuideLineFromCache(getGuideLineKey(H_GUIDE_LINE_STORAGE_KEY)),
getGuideLineFromCache(getGuideLineKey(V_GUIDE_LINE_STORAGE_KEY)),
]);
Expand Down Expand Up @@ -131,5 +131,9 @@ export const useStage = (stageOptions: StageOptions) => {
}
});

onBeforeUnmount(() => {
stage.destroy();
});

return stage;
};
2 changes: 1 addition & 1 deletion packages/editor/src/initService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ export const initServiceEvents = (

const getApp = () => {
const stage = editorService.get('stage');
return stage?.renderer.runtime?.getApp?.();
return stage?.renderer?.runtime?.getApp?.();
};

const updateDataSourceSchema = () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/editor/src/layouts/sidebar/ComponentListPanel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ const dragendHandler = () => {
globalThis.clearTimeout(timeout);
timeout = undefined;
}
const doc = stage.value?.renderer.getDocument();
const doc = stage.value?.renderer?.getDocument();
if (doc && stageOptions?.containerHighlightClassName) {
removeClassNameByClassName(doc, stageOptions.containerHighlightClassName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ const unWatch = watch(
nextTick(() => unWatch());
stage.on('select', (el: HTMLElement, event: MouseEvent) => {
const els = stage.renderer.getElementsFromPoint(event) || [];
const els = stage.renderer?.getElementsFromPoint(event) || [];
const ids = els.map((el) => getIdFromEl()(el)).filter((id) => Boolean(id)) as string[];
buttonVisible.value = ids.length > 3;
Expand Down
4 changes: 2 additions & 2 deletions packages/editor/src/layouts/workspace/viewer/Stage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ const dropHandler = async (e: DragEvent) => {
e.preventDefault();
const doc = stage?.renderer.contentWindow?.document;
const doc = stage?.renderer?.contentWindow?.document;
const parentEl: HTMLElement | null | undefined = doc?.querySelector(`.${stageOptions?.containerHighlightClassName}`);
let parent: MContainer | undefined | null = page.value;
Expand All @@ -209,7 +209,7 @@ const dropHandler = async (e: DragEvent) => {
const layout = await services?.editorService.getLayout(parent);
const containerRect = stageContainer.value.getBoundingClientRect();
const { scrollTop, scrollLeft } = stage.mask;
const { scrollTop, scrollLeft } = stage.mask!;
const { style = {} } = config.data;
let top = 0;
Expand Down
6 changes: 3 additions & 3 deletions packages/editor/src/layouts/workspace/viewer/StageOverlay.vue
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const style = computed(() => ({
watch(stage, (stage) => {
if (stage) {
stage.on('dblclick', async (event: MouseEvent) => {
const el = await stage.actionManager.getElementFromPoint(event);
const el = (await stage.actionManager?.getElementFromPoint(event)) || null;
services?.stageOverlayService.openOverlay(el);
});
} else {
Expand All @@ -53,8 +53,8 @@ watch(stageOverlay, (stageOverlay) => {
const { mask, renderer } = subStage;
const { contentWindow } = renderer;
mask.showRule(false);
const { contentWindow } = renderer!;
mask?.showRule(false);
services?.stageOverlayService.updateOverlay();
Expand Down
6 changes: 3 additions & 3 deletions packages/editor/src/services/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ class Editor extends BaseService {

if (node?.id) {
this.get('stage')
?.renderer.runtime?.getApp?.()
?.renderer?.runtime?.getApp?.()
?.page?.emit(
'editor:select',
{
Expand Down Expand Up @@ -737,7 +737,7 @@ class Editor extends BaseService {

public async doPaste(config: MNode[], position: PastePosition = {}): Promise<MNode[]> {
propsService.clearRelateId();
const doc = this.get('stage')?.renderer.contentWindow?.document;
const doc = this.get('stage')?.renderer?.contentWindow?.document;
const pasteConfigs = beforePaste(position, cloneDeep(config), doc);
return pasteConfigs;
}
Expand All @@ -756,7 +756,7 @@ class Editor extends BaseService {
if (!node.style) return config;

const stage = this.get('stage');
const doc = stage?.renderer.contentWindow?.document;
const doc = stage?.renderer?.contentWindow?.document;

if (doc) {
const el = getElById()(doc, node.id);
Expand Down
22 changes: 15 additions & 7 deletions packages/editor/src/services/stageOverlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ class StageOverlay extends BaseService {
const subStage = this.get('stage');
const wrapDiv = this.get('wrapDiv');
subStage?.destroy();

for (let i = 0, l = wrapDiv.children.length; i < l; i++) {
const child = wrapDiv.children[i];
child.remove();
}

wrapDiv.remove();

this.set('stage', null);
Expand Down Expand Up @@ -97,7 +103,7 @@ class StageOverlay extends BaseService {
render: async (stage: StageCore) => {
this.copyDocumentElement();

const rootEls = stage.renderer.getDocument()?.body.children;
const rootEls = stage.renderer?.getDocument()?.body.children;
if (rootEls) {
Array.from(rootEls).forEach((element) => {
if (['SCRIPT', 'STYLE'].includes(element.tagName)) {
Expand Down Expand Up @@ -135,8 +141,8 @@ class StageOverlay extends BaseService {
const subStage = this.get('stage');
const stage = editorService.get('stage');

const doc = subStage?.renderer.getDocument();
const documentElement = stage?.renderer.getDocument()?.documentElement;
const doc = subStage?.renderer?.getDocument();
const documentElement = stage?.renderer?.getDocument()?.documentElement;

if (doc && documentElement) {
doc.replaceChild(documentElement.cloneNode(true), doc.documentElement);
Expand All @@ -160,13 +166,15 @@ class StageOverlay extends BaseService {
background-color: #fff;
`;

Array.from(wrapDiv.children).forEach((element) => {
element.remove();
});
for (let i = 0, l = wrapDiv.children.length; i < l; i++) {
const child = wrapDiv.children[i];
child.remove();
}

wrapDiv.appendChild(contentEl);

setTimeout(() => {
subStage?.renderer.contentWindow?.magic.onPageElUpdate(wrapDiv);
subStage?.renderer?.contentWindow?.magic.onPageElUpdate(wrapDiv);
});

if (await stageOptions?.canSelect?.(contentEl)) {
Expand Down
4 changes: 2 additions & 2 deletions packages/editor/src/utils/content-menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ export const usePasteMenu = (menu?: Ref<InstanceType<typeof ContentMenu> | undef
const rect = menu.value.$el.getBoundingClientRect();
const parentRect = stage?.container?.getBoundingClientRect();
const initialLeft =
calcValueByFontsize(stage?.renderer.getDocument(), (rect.left || 0) - (parentRect?.left || 0)) /
calcValueByFontsize(stage?.renderer?.getDocument(), (rect.left || 0) - (parentRect?.left || 0)) /
services.uiService.get('zoom');
const initialTop =
calcValueByFontsize(stage?.renderer.getDocument(), (rect.top || 0) - (parentRect?.top || 0)) /
calcValueByFontsize(stage?.renderer?.getDocument(), (rect.top || 0) - (parentRect?.top || 0)) /
services.uiService.get('zoom');
services?.editorService?.paste({ left: initialLeft, top: initialTop });
} else {
Expand Down
18 changes: 11 additions & 7 deletions packages/editor/src/utils/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,16 @@ const getMiddleTop = (node: MNode, parentNode: MNode, stage: StageCore | null) =
}

const { height: parentHeight } = parentNode.style;
// wrapperHeight 是未 calcValue的高度, 所以要将其calcValueByFontsize一下, 否则在pad or pc端计算的结果有误
const { scrollTop = 0, wrapperHeight } = stage.mask;
const wrapperHeightDeal = calcValueByFontsize(stage.renderer.getDocument()!, wrapperHeight);
const scrollTopDeal = calcValueByFontsize(stage.renderer.getDocument()!, scrollTop);
if (isPage(parentNode)) {
return (wrapperHeightDeal - height) / 2 + scrollTopDeal;

let wrapperHeightDeal = parentHeight;
if (stage.mask && stage.renderer) {
// wrapperHeight 是未 calcValue的高度, 所以要将其calcValueByFontsize一下, 否则在pad or pc端计算的结果有误
const { scrollTop = 0, wrapperHeight } = stage.mask;
wrapperHeightDeal = calcValueByFontsize(stage.renderer.getDocument()!, wrapperHeight);
const scrollTopDeal = calcValueByFontsize(stage.renderer.getDocument()!, scrollTop);
if (isPage(parentNode)) {
return (wrapperHeightDeal - height) / 2 + scrollTopDeal;
}
}

// 如果容器的元素高度大于当前视口高度的2倍, 添加的元素居中位置也会看不见, 所以要取最小值计算
Expand Down Expand Up @@ -263,7 +267,7 @@ export const fixNodePosition = (config: MNode, parent: MContainer, stage: StageC
return {
...(config.style || {}),
top: getMiddleTop(config, parent, stage),
left: fixNodeLeft(config, parent, stage?.renderer.contentWindow?.document),
left: fixNodeLeft(config, parent, stage?.renderer?.contentWindow?.document),
};
};

Expand Down
39 changes: 23 additions & 16 deletions packages/stage/src/ActionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ const defaultContainerHighlightDuration = 800;
* @extends EventEmitter
*/
export default class ActionManager extends EventEmitter {
private dr: StageDragResize;
private multiDr?: StageMultiDragResize;
private highlightLayer: StageHighlight;
private dr: StageDragResize | null = null;
private multiDr: StageMultiDragResize | null = null;
private highlightLayer: StageHighlight | null = null;
/** 单选、多选、高亮的容器(蒙层的content) */
private container: HTMLElement;
/** 当前选中的节点 */
Expand Down Expand Up @@ -143,7 +143,7 @@ export default class ActionManager extends EventEmitter {
this.disabledMultiSelect = true;
if (this.multiDr) {
this.multiDr.destroy();
this.multiDr = undefined;
this.multiDr = null;
}
}

Expand All @@ -161,15 +161,15 @@ export default class ActionManager extends EventEmitter {
* @param guidelines 参考线坐标数组
*/
public setGuidelines(type: GuidesType, guidelines: number[]): void {
this.dr.setGuidelines(type, guidelines);
this.dr?.setGuidelines(type, guidelines);
this.multiDr?.setGuidelines(type, guidelines);
}

/**
* 清空所有参考线
*/
public clearGuides(): void {
this.dr.clearGuides();
this.dr?.clearGuides();
this.multiDr?.clearGuides();
}

Expand All @@ -178,7 +178,7 @@ export default class ActionManager extends EventEmitter {
* @param el 变更的元素
*/
public updateMoveable(el?: HTMLElement): void {
this.dr.updateMoveable(el);
this.dr?.updateMoveable(el);
// 多选时不可配置元素,因此不存在多选元素变更,不需要传el
this.multiDr?.updateMoveable();
}
Expand All @@ -204,7 +204,7 @@ export default class ActionManager extends EventEmitter {
}

public getMoveableOption<K extends keyof MoveableOptions>(key: K): MoveableOptions[K] | undefined {
if (this.dr.getTarget()) {
if (this.dr?.getTarget()) {
return this.dr.getOption(key);
}
if (this.multiDr?.targetList.length) {
Expand Down Expand Up @@ -271,7 +271,7 @@ export default class ActionManager extends EventEmitter {
public select(el: HTMLElement | null, event?: MouseEvent): void {
this.setSelectedEl(el);
this.clearSelectStatus(SelectStatus.MULTI_SELECT);
this.dr.select(el, event);
this.dr?.select(el, event);
}

public multiSelect(ids: Id[]): void {
Expand Down Expand Up @@ -310,14 +310,14 @@ export default class ActionManager extends EventEmitter {
}
if (el === this.highlightedEl || !el) return;

this.highlightLayer.highlight(el);
this.highlightLayer?.highlight(el);
this.highlightedEl = el;
this.emit('highlight', el);
}

public clearHighlight(): void {
this.setHighlightEl(undefined);
this.highlightLayer.clearHighlight();
this.highlightLayer?.clearHighlight();
}

/**
Expand All @@ -329,7 +329,7 @@ export default class ActionManager extends EventEmitter {
this.multiDr?.clearSelectStatus();
this.selectedElList = [];
} else {
this.dr.clearSelectStatus();
this.dr?.clearSelectStatus();
}
}

Expand Down Expand Up @@ -373,7 +373,7 @@ export default class ActionManager extends EventEmitter {
}

public getDragStatus() {
return this.dr.getDragStatus();
return this.dr?.getDragStatus();
}

public destroy(): void {
Expand All @@ -382,9 +382,16 @@ export default class ActionManager extends EventEmitter {
this.container.removeEventListener('mouseleave', this.mouseLeaveHandler);
this.container.removeEventListener('wheel', this.mouseWheelHandler);
this.container.removeEventListener('dblclick', this.dblclickHandler);
this.dr.destroy();
this.selectedEl = null;
this.selectedElList = [];

this.dr?.destroy();
this.multiDr?.destroy();
this.highlightLayer.destroy();
this.highlightLayer?.destroy();

this.dr = null;
this.multiDr = null;
this.highlightLayer = null;
}

public on<Name extends keyof ActionManagerEvents, Param extends ActionManagerEvents[Name]>(
Expand Down Expand Up @@ -431,7 +438,7 @@ export default class ActionManager extends EventEmitter {
this.emit('select-parent');
})
.on(AbleActionEventType.REMOVE, () => {
const drTarget = this.dr.getTarget();
const drTarget = this.dr?.getTarget();
if (!drTarget) return;
const data: RemoveEventData = {
data: [{ el: drTarget }],
Expand Down
Loading

0 comments on commit 62b2da7

Please sign in to comment.