Skip to content

Commit

Permalink
feat: enhance DOM judgment
Browse files Browse the repository at this point in the history
fix: #2702
  • Loading branch information
Wxh16144 committed Jan 18, 2025
1 parent c7bb04c commit cff2bf0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
25 changes: 25 additions & 0 deletions packages/hooks/src/utils/dom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Thx rc-util
* copied from https://github.com/react-component/util/blob/v5.44.3/src/Dom/findDOMNode.ts#L4-L23
*/

export function isDOM(node: any): node is HTMLElement | SVGElement {
// https://developer.mozilla.org/en-US/docs/Web/API/Element
// Since XULElement is also subclass of Element, we only need HTMLElement and SVGElement
return node instanceof HTMLElement || node instanceof SVGElement;
}

/**
* Retrieves a DOM node via a ref, and does not invoke `findDOMNode`.
*/
export function getDOM(node: any): HTMLElement | SVGElement | null {
if (node && typeof node === 'object' && isDOM(node.nativeElement)) {
return node.nativeElement;
}

if (isDOM(node)) {
return node as any;
}

return null;
}
3 changes: 2 additions & 1 deletion packages/hooks/src/utils/domTarget.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MutableRefObject } from 'react';
import { isFunction } from './index';
import isBrowser from './isBrowser';
import { getDOM } from './dom';

type TargetValue<T> = T | undefined | null;

Expand Down Expand Up @@ -30,5 +31,5 @@ export function getTargetElement<T extends TargetType>(target: BasicTarget<T>, d
targetElement = target;
}

return targetElement;
return getDOM(targetElement) ?? defaultElement;
}

0 comments on commit cff2bf0

Please sign in to comment.