attrs, clearAttrs (DOM)
Applies html and body attributes straight to the live document, and removes them again; for browser-only apps without TwilightProvider.
import { attrs, clearAttrs } from '@salla.sa/twilight-theme-engine/dom';In plain words
attrs() from /dom is the plain-JavaScript version: no React, no provider. It puts classes and attributes directly on document.documentElement (the <html> element) and document.body, and remembers what it set, so the next call first removes those. clearAttrs() removes them all.
It is meant for apps that render only in the browser and do not use TwilightProvider. A theme never needs it: inside a theme, call useDocumentClass().
Signature
function attrs(descriptor: DocumentElementDescriptor): void // does nothing without a document function clearAttrs(): void
Example
import { attrs, clearAttrs } from '@salla.sa/twilight-theme-engine/dom';
export function enterProductPage() {
attrs({
html: { lang: 'ar', dir: 'rtl' },
body: { class: 'page-product', 'data-page': 'product' },
});
}
export function leaveProductPage() {
clearAttrs();
}
How it behaves
It records what it applied, as JSON, in a
data-de-managedattribute on each element. The next call removes those classes and attributes, then applies the new ones; anything it did not set is left alone.Without a
document(on the server) both functions return at once, so nothing they set is in server-rendered HTML.There is no live demo on this page: run inside the playground, it would remove the
langanddirof the page itself (see the gotcha).
Gotchas
Never call it in a
TwilightProviderapp. The provider'sDocumentClassProvidersyncs the same two elements through the samedata-de-managedrecord (syncAttrsToElementin src/utils/document-class.ts).attrs()first removes what the provider applied,<html lang dir>and body classes such asrtlandsalla-<theme>included, and the provider removes yours at its next sync. UseuseDocumentClass()from/hooks/useDocumentClass.Calls do not add up: a second call from elsewhere removes what the first one set. Build one descriptor with everything and apply it once.
Related
Adds classes and attributes to the page <html> and <body> while the calling component is mounted, merged with everyone else.
DocumentClassProviderCollects every useDocumentClass() request in its tree and applies the merged classes and attributes to the real body and html elements.
attrsTurns an { html, body } attribute descriptor into React props to spread onto the html and body elements: class becomes className.