fix(system): safe check all event target

This commit is contained in:
CRIMX
2024-12-10 12:56:30 +08:00
parent 0f21ec21eb
commit b7b5032c02
9 changed files with 20 additions and 18 deletions

View File

@@ -32,18 +32,20 @@ export const getDimensions = (node: HTMLDivElement): Dimensions => ({
height: node.offsetHeight,
});
export const getHostForElement = (element: HTMLElement): Document | ShadowRoot =>
(element.getRootNode?.() as Document | ShadowRoot) || window?.document;
export const getHostForElement = (element: HTMLElement | EventTarget | null): Document | ShadowRoot =>
((element as Partial<HTMLElement> | null)?.getRootNode?.() as Document | ShadowRoot) || window?.document;
const inputTags = ['INPUT', 'SELECT', 'TEXTAREA'];
export function isInputDOMNode(event: KeyboardEvent): boolean {
// using composed path for handling shadow dom
const target = (event.composedPath?.()?.[0] || event.target) as HTMLElement;
const isInput = inputTags.includes(target?.nodeName) || target?.hasAttribute?.('contenteditable');
const target = (event.composedPath?.()?.[0] || event.target) as Element | null;
if (target?.nodeType !== 1 /* Node.ELEMENT_NODE */) return false;
const isInput = inputTags.includes(target.nodeName) || target.hasAttribute('contenteditable');
// when an input field is focused we don't want to trigger deletion or movement of nodes
return isInput || !!target?.closest('.nokey');
return isInput || !!target.closest('.nokey');
}
export const isMouseEvent = (event: MouseEvent | TouchEvent): event is MouseEvent => 'clientX' in event;

View File

@@ -364,7 +364,7 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
}
})
.filter((event: MouseEvent) => {
const target = event.target as HTMLDivElement;
const target = event.target;
const isDraggable =
!event.button &&
(!noDragClassName || !hasSelector(target, `.${noDragClassName}`, domNode)) &&

View File

@@ -18,13 +18,13 @@ export function isParentSelected<NodeType extends NodeBase>(node: NodeType, node
return isParentSelected(parentNode, nodeLookup);
}
export function hasSelector(target: Element, selector: string, domNode: Element): boolean {
let current = target;
export function hasSelector(target: Element | EventTarget | null, selector: string, domNode: Element): boolean {
let current = target as Partial<Element> | null | undefined;
do {
if (current?.matches(selector)) return true;
if (current?.matches?.(selector)) return true;
if (current === domNode) return false;
current = current.parentElement as Element;
current = current?.parentElement;
} while (current);
return false;

View File

@@ -48,7 +48,7 @@ function onPointerDown(
}: OnPointerDownParams
) {
// when xyflow is used inside a shadow root we can't use document
const doc = getHostForElement(event.target as HTMLElement);
const doc = getHostForElement(event.target);
let autoPanId = 0;
let closestHandle: Handle | null;