forked from WebReflection/linkedom
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4 from luwes/slot
Improve <slot> element support
- Loading branch information
Showing
2 changed files
with
56 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,61 @@ | ||
import {HTMLElement} from './element.js'; | ||
import {registerHTMLClass} from '../shared/register-html-class.js'; | ||
|
||
const tagName = 'slot'; | ||
|
||
/** | ||
* @implements globalThis.HTMLSlotElement | ||
*/ | ||
export class HTMLSlotElement extends HTMLElement { | ||
constructor(ownerDocument, localName = 'slot') { | ||
class HTMLSlotElement extends HTMLElement { | ||
constructor(ownerDocument, localName = tagName) { | ||
super(ownerDocument, localName); | ||
} | ||
|
||
/* c8 ignore start */ | ||
get name() { return this.getAttribute('name'); } | ||
set name(value) { this.setAttribute('name', value); } | ||
|
||
assign() {} | ||
|
||
assignedNodes(options) { | ||
const isNamedSlot = !!this.name; | ||
const hostChildNodes = this.getRootNode().host?.childNodes ?? []; | ||
let slottables; | ||
|
||
if (isNamedSlot) { | ||
slottables = [...hostChildNodes].filter(node => node.slot === this.name); | ||
} else { | ||
slottables = [...hostChildNodes].filter(node => !node.slot); | ||
} | ||
|
||
if (options?.flatten) { | ||
const result = []; | ||
|
||
// Element and Text nodes are slottables. A slot can be a slottable. | ||
for (let slottable of slottables) { | ||
if (slottable.localName === 'slot') { | ||
result.push(...slottable.assignedNodes({ flatten: true })); | ||
} else { | ||
result.push(slottable); | ||
} | ||
} | ||
|
||
slottables = result; | ||
} | ||
|
||
// If no assigned nodes are found, it returns the slot's fallback content. | ||
return slottables.length ? slottables : [...this.childNodes]; | ||
} | ||
|
||
assignedElements(options) { | ||
const slottables = this.assignedNodes(options).filter(n => n.nodeType === 1); | ||
|
||
// If no assigned elements are found, it returns the slot's fallback content. | ||
return slottables.length ? slottables : [...this.children]; | ||
} | ||
/* c8 ignore stop */ | ||
} | ||
|
||
registerHTMLClass(tagName, HTMLSlotElement); | ||
|
||
export {HTMLSlotElement}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters