Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions src/DOMElementFilter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,24 +158,30 @@ const FRAGMENT_NODE = 11

const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/

const isCustomElement = (val: any) => {
const {tagName} = val
return Boolean(
(typeof tagName === 'string' && tagName.includes('-')) ||
(typeof val.hasAttribute === 'function' && val.hasAttribute('is')),
)
}

const testNode = (val: any) => {
const constructorName = val.constructor.name
const {nodeType, tagName} = val
const isCustomElement =
(typeof tagName === 'string' && tagName.includes('-')) ||
(typeof val.hasAttribute === 'function' && val.hasAttribute('is'))

const {nodeType} = val

return (
(nodeType === ELEMENT_NODE &&
(ELEMENT_REGEXP.test(constructorName) || isCustomElement)) ||
(ELEMENT_REGEXP.test(constructorName) || isCustomElement(val))) ||
(nodeType === TEXT_NODE && constructorName === 'Text') ||
(nodeType === COMMENT_NODE && constructorName === 'Comment') ||
(nodeType === FRAGMENT_NODE && constructorName === 'DocumentFragment')
)
}

export const test: NewPlugin['test'] = (val: any) =>
val?.constructor?.name && testNode(val)
(val?.constructor?.name || isCustomElement(val)) && testNode(val)

type HandledType = Element | Text | Comment | DocumentFragment

Expand All @@ -195,7 +201,8 @@ export default function createDOMElementFilter(
filterNode: (node: Node) => boolean,
): NewPlugin {
return {
test: (val: any) => val?.constructor?.name && testNode(val),
test: (val: any) =>
(val?.constructor?.name || isCustomElement(val)) && testNode(val),
serialize: (
node: HandledType,
config: Config,
Expand Down
31 changes: 31 additions & 0 deletions src/__tests__/pretty-dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,34 @@ test('prettyDOM supports a COLORS environment variable', () => {
process.env.COLORS = 'true'
expect(prettyDOM(container)).toEqual(withColors)
})

test('prettyDOM supports named custom elements', () => {
window.customElements.define(
'my-element-1',
class MyElement extends HTMLElement {},
)

const {container} = render('<my-element-1>Hello World!</my-element-1>')

expect(prettyDOM(container)).toMatchInlineSnapshot(`
<div>
<my-element-1>
Hello World!
</my-element-1>
</div>
`)
})

test('prettyDOM supports anonymous custom elements', () => {
window.customElements.define('my-element-2', class extends HTMLElement {})

const {container} = render('<my-element-2>Hello World!</my-element-2>')

expect(prettyDOM(container)).toMatchInlineSnapshot(`
<div>
<my-element-2>
Hello World!
</my-element-2>
</div>
`)
})