Skip to content

Commit

Permalink
feat: extract DOM node check and retrieval to separate function (#539)
Browse files Browse the repository at this point in the history
* feat: extract DOM node check and retrieval to separate function

* chore: rename

* typo

* chore: rename
  • Loading branch information
Wxh16144 authored May 20, 2024
1 parent 70da09e commit f9b468e
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 8 deletions.
26 changes: 19 additions & 7 deletions src/Dom/findDOMNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,34 @@ export function isDOM(node: any): node is HTMLElement | 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): node is HTMLElement | SVGElement {
if (node && typeof node === 'object' && isDOM(node.nativeElement)) {
return node.nativeElement;
}

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

return null;
}

/**
* Return if a node is a DOM node. Else will return by `findDOMNode`
*/
export default function findDOMNode<T = Element | Text>(
node: React.ReactInstance | HTMLElement | SVGElement | { nativeElement: T },
): T {
if (node && typeof node === 'object' && isDOM((node as any).nativeElement)) {
return ((node as any).nativeElement as unknown) as T;
}

if (isDOM(node)) {
return (node as unknown) as T;
const domNode = getDOM(node);
if (domNode) {
return domNode as T;
}

if (node instanceof React.Component) {
return (ReactDOM.findDOMNode(node) as unknown) as T;
return ReactDOM.findDOMNode(node) as unknown as T;
}

return null;
Expand Down
29 changes: 28 additions & 1 deletion tests/findDOMNode.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { render } from '@testing-library/react';
import * as React from 'react';
import findDOMNode, { isDOM } from '../src/Dom/findDOMNode';
import findDOMNode, { getDOM, isDOM } from '../src/Dom/findDOMNode';
import proxyObject from '../src/proxyObject';

describe('findDOMNode', () => {
Expand Down Expand Up @@ -129,4 +129,31 @@ describe('findDOMNode', () => {
container.querySelector('span'),
);
});

describe('getDOM', () => {
it('should return the DOM node when input is a DOM node', () => {
const node = document.createElement('div');
const result = getDOM(node);

expect(result).toBe(node);
});

it('should return the nativeElement when input is an object with a DOM node as nativeElement', () => {
const nativeElement = document.createElement('div');
const node = { nativeElement };

const result = getDOM(node);

expect(result).toBe(nativeElement);
});

it.each([null, void 0, { foo: 'bar' }, 'string'])(
'should return null when input is not a DOM node',
node => {
const result = getDOM(node);

expect(result).toBeNull();
},
);
});
});

0 comments on commit f9b468e

Please sign in to comment.