Skip to content

Commit

Permalink
feat: export isVNode function
Browse files Browse the repository at this point in the history
  • Loading branch information
aotarola committed Oct 30, 2019
1 parent 26e779f commit 4282d73
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
15 changes: 14 additions & 1 deletion lib/phy.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,26 @@ const preact = require('preact');
// VNode props https://github.com/preactjs/preact/blob/master/src/index.d.ts#L14-L17
const VNODE_ATTRS = ['props', 'type', 'key', 'ref'];

/** @param {object} obj
* @returns {boolean}
*/
function isPreactNode(obj) {
if (!obj) {
return false;
}
return VNODE_ATTRS.every(prop =>
Object.prototype.hasOwnProperty.call(obj, prop)
);
}

const objectToString = Object.toString();

/** @param {VNode | Readonly<Record<string, any>>} obj */
function isAttributes(obj) {
return (
'object' === typeof obj &&
(!obj.constructor || obj.constructor.toString() === objectToString) &&
!VNODE_ATTRS.every(prop => Object.prototype.hasOwnProperty.call(obj, prop))
!isPreactNode(obj)
);
}

Expand Down Expand Up @@ -102,5 +114,6 @@ function h(createElement, selector, attrs, ...kids) {
module.exports = exports = h.bind(null, preact.createElement);

exports.h = exports;
exports.isVNode = isPreactNode;
exports.Component = preact.Component;
exports.render = preact.render;
3 changes: 3 additions & 0 deletions lib/typedefs.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Component, ComponentChildren, ComponentType, VNode } from 'preact';
import p from 'preact';

declare function isPreactNode(obj: object): boolean;

declare function phy(
selectorOrComp: string | ComponentType,
...kids: ComponentChildren[]
Expand All @@ -15,6 +17,7 @@ declare namespace phy {
let h: typeof phy;
let Component: typeof p.Component;
let render: typeof p.render;
let isVNode: typeof isPreactNode;
}

export = phy;
18 changes: 14 additions & 4 deletions test/phy.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const assert = require('assertive');

const h = require('../');
const { h, isVNode } = require('../');
const { Fragment } = require('preact');
const render = require('preact-render-to-string');

Expand Down Expand Up @@ -96,9 +96,19 @@ const tests = [
];

describe('phy', () => {
tests.forEach(test => {
it(test[0], () => {
assert.equal(test[2], render(test[1]));
describe('h', () => {
tests.forEach(test => {
it(test[0], () => {
assert.equal(test[2], render(test[1]));
});
});
});

describe('isVNode', () => {
it('should evaluate to "true" for a VNode', () =>
assert.expect(isVNode(h('div'))));

it('should evaluate to "false" for non VNodes', () =>
[null, undefined, {}, 1].forEach(test => assert.falsey(isVNode(test))));
});
});

0 comments on commit 4282d73

Please sign in to comment.