Kumbatio

DOM

applyEnergyLevel, readEnergyLevel, and observeEnergyLevel from @kumbatio/energy-system/dom

import { applyEnergyLevel, readEnergyLevel, observeEnergyLevel } from '@kumbatio/energy-system/dom'

Framework-free DOM projection of the energy level. All three functions take an optional root element; when omitted they use document.body and throw Error('Energy DOM APIs require a browser document or an explicit root element') outside a browser document.

applyEnergyLevel

function applyEnergyLevel(level: EnergyLevel, root?: HTMLElement): void

Apply an energy level to a root element. Sets the data-energy-level attribute and four CSS custom properties derived from uiVisibilityStrategy:

Custom propertySource field
--energy-chrome-opacitychromeOpacity
--energy-chrome-opacity-hoverchromeOpacityHover
--energy-content-max-widthcontentMaxWidth
--energy-content-font-scalecontentFontScale

Throws for an invalid level. Pairs with the reference stylesheet, whose per-level custom property values mirror the same strategy - the JS and CSS-only paths always agree.

applyEnergyLevel(25)
// <body data-energy-level="25" style="--energy-chrome-opacity: 0.1; ...">

readEnergyLevel

function readEnergyLevel(root?: HTMLElement): EnergyLevel

Read the current energy level from a root element's data-energy-level attribute. Returns 100 if no valid level is set.

observeEnergyLevel

function observeEnergyLevel(callback: EnergyChangeListener, root?: HTMLElement): () => void

Observe energy level changes on a root element via MutationObserver (watching the data-energy-level attribute). Calls back with EnergyState values whose timestamp is the observation time and whose source is 'inferred'. Only fires when the level actually changed. Returns a cleanup function that disconnects the observer.

const stop = observeEnergyLevel((state, prev) => {
  console.log(`DOM level ${prev.level} -> ${state.level}`)
})

// later
stop()

When using the React entry with applyToDOM (the default), EnergyProvider calls applyEnergyLevel for you on document.body. Use observeEnergyLevel to react to that projection from non-React code.