From 23d9ff90961e3a1443b76ec1824e219740dacae3 Mon Sep 17 00:00:00 2001 From: Cory LaViska Date: Tue, 22 Dec 2020 17:09:01 -0500 Subject: [PATCH] Add default slot detection to hasSlot --- src/utilities/slot.ts | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/utilities/slot.ts b/src/utilities/slot.ts index bc84b79e..e1041281 100644 --- a/src/utilities/slot.ts +++ b/src/utilities/slot.ts @@ -37,8 +37,28 @@ export function getTextContent(slot: HTMLSlotElement): string { } // -// Determines whether a slot with the given name exists in an element. +// Determines whether an element has a slot. If name is specified, the function will look for a corresponding named +// slot, otherwise it will look for a "default" slot (e.g. a non-empty text node or an element with no slot attribute). // -export function hasSlot(el: HTMLElement, name: string) { - return el.querySelector(`[slot="${name}"]`) !== null; +export function hasSlot(el: HTMLElement, name?: string) { + // Look for a named slot + if (name) { + return el.querySelector(`[slot="${name}"]`) !== null; + } + + // Look for a default slot + return [...el.childNodes].some(node => { + if (node.nodeType === node.TEXT_NODE && node.textContent.trim() !== '') { + return true; + } + + if (node.nodeType === node.ELEMENT_NODE) { + const el = node as HTMLElement; + if (!el.hasAttribute('slot')) { + return true; + } + } + + return false; + }); }