@tempots/dom
HeadlessAdapter class
Represents an adapter for headless rendering environments. This class provides methods to interact with elements in a headless context.
This class is used to adapt the HeadlesContext to whatever you want to use to render your final HTML. You can use libraries like cheerio to render your HTML.
For cheerio an adapter could look like this:
const renderWithCheerio = (html: string, root: HeadlessPortal) => {
const $ = cheerio.load(html)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const adapter = new HeadlessAdapter<cheerio.Cheerio<any>>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
select: (selector: string): cheerio.Cheerio<any>[] => [$(selector)],
getAttribute: (el, name: string) => el.attr(name) ?? null,
setAttribute: (el, name: string, value: string | null) => {
if (value === null) {
el.removeAttr(name)
} else {
el.attr(name, value)
}
},
getClass: el => el.attr('class') ?? '',
setClass: (el, value: string | null) => {
if (value === null) {
el.removeAttr('class')
} else {
el.attr('class', value)
}
},
getStyles: el => el.attr('style') ?? {},
setStyles: (el, value: Record<string, string>) => {
if (Object.keys(value).length === 0) {
el.removeAttr('style')
} else {
el.css(value)
}
},
appendHTML: (el, html) => el.append(html),
getInnerHTML: el => el.html() ?? '',
setInnerHTML: (el, html) => el.html(html),
getInnerText: el => el.text() ?? '',
setInnerText: (el, text) => el.text(text),
})
adapter.setFromRoot(root, true)
return $.html()
}
This function will return the rendered HTML as a string.
Signature:
declare class HeadlessAdapter<EL>
Constructors
Constructor |
Modifiers |
Description |
---|---|---|
Constructs a new instance of the |
Properties
Property |
Modifiers |
Type |
Description |
---|---|---|---|
|
(el: EL, html: string) => void |
Appends HTML to an element. | |
|
(el: EL, attr: string) => string | null |
Gets the value of an attribute from an element. | |
|
(el: EL) => string | null |
Gets the class of an element. | |
|
(el: EL) => string | null |
Gets the inner HTML of an element. | |
|
(el: EL) => string | null |
Gets the inner text of an element. | |
|
(el: EL) => Record<string, string> |
Gets the styles of an element. | |
|
(selector: string) => EL[] |
Selects elements from the headless environment. | |
|
(el: EL, attr: string, value: string | null) => void |
Sets the value of an attribute on an element. | |
|
(el: EL, cls: string | null) => void |
Sets the class of an element. | |
|
(root: HeadlessPortal, setPlaceholders: boolean) => void |
Sets the content of the root element from a HeadlessPortal. Generally this will be the same instance that is returned by | |
|
(el: EL, html: string) => void |
Sets the inner HTML of an element. | |
|
(el: EL, text: string) => void |
Sets the inner text of an element. | |
|
(el: EL, styles: Record<string, string>) => void |
Sets the styles of an element. |