fix: don't blur the iframe when selecting it

This commit is contained in:
MrWindlike 2022-07-01 17:03:31 +08:00
parent 391213d541
commit a1c320f741

View File

@ -1,4 +1,4 @@
import React, { useMemo, useRef, useState, useEffect, useCallback } from 'react';
import React, { useMemo, useRef, useState } from 'react';
import { EditorServices } from '../../types';
import { observer } from 'mobx-react-lite';
import { Box } from '@chakra-ui/react';
@ -14,7 +14,7 @@ type Props = {
export const EditorMaskWrapper: React.FC<Props> = observer(props => {
const { children, services } = props;
const { editorStore, eventBus, registry } = services;
const { setSelectedComponentId, setExplorerMenuTab } = editorStore;
const { setSelectedComponentId, setExplorerMenuTab, selectedComponentId } = editorStore;
const [mousePosition, setMousePosition] = useState<[number, number]>([0, 0]);
const [scrollOffset, setScrollOffset] = useState<[number, number]>([0, 0]);
const wrapperRef = useRef<HTMLDivElement | null>(null);
@ -66,25 +66,18 @@ export const EditorMaskWrapper: React.FC<Props> = observer(props => {
);
};
const onClickIframe = useCallback(() => {
if (document.activeElement?.tagName === 'IFRAME') {
setSelectedComponentId(document.activeElement?.getAttribute('title') || '');
setTimeout(() => {
window.focus();
});
}
}, [setSelectedComponentId]);
// can't capture the iframe click event
// use window's blur event to detect whether clicking the iframes
useEffect(() => {
window.focus();
window.addEventListener('blur', onClickIframe);
// use `setInterval` to check whether the iframe is selected
setInterval(function () {
if (document.activeElement?.tagName === 'IFRAME') {
const currentSelectedComponentId =
document.activeElement?.getAttribute('title') || '';
return () => {
window.removeEventListener('blur', onClickIframe);
};
}, [onClickIframe]);
if (selectedComponentId !== currentSelectedComponentId) {
setSelectedComponentId(currentSelectedComponentId);
}
}
}, 1000);
const mousePositionWithOffset: [number, number] = [
mousePosition[0] + scrollOffset[0],