The Stateful (DOM) Elements Library is a small, early-stage JavaScript library that keeps state on a DOM element. It defines a StatefulElement custom element (a customized built-in div) that stores a private state object, exposes methods to set, merge, group and read that state, and notifies listeners registered with watchState when setState runs. State changes do not update the DOM: nothing re-renders, and the internal ElementManager.updateUI only records values in an internal Map. The library is three source files with no build step.
The library is not published to npm. Clone the repository and copy the files in src/ into your project:
git clone https://github.com/zachshallbetter/Stateful-Elements.git
cp Stateful-Elements/src/*.js path/to/your/project/The files are ES modules, so load the entry file with a module script tag. Importing StatefulElement.js registers the element as stateful-element:
<script type="module" src="StatefulElement.js"></script>
<div is="stateful-element"></div>StatefulElement extends HTMLDivElement, so it needs a browser that supports customized built-in elements (the is attribute). Safari does not.
The methods below are called on a StatefulElement instance. The element also has mergeState, groupState, updateGroupState, removeState and resetState. Clicking a child with a data-action attribute dispatches an internal event named after the action, but there is no public method to listen for it yet.
The setState method merges new values into the element's state object and notifies watchState listeners.
element.setState(newState);newState: An object of state keys and values to merge into the current state.
newState: (Required) An object of state keys and values to merge into the current state.
- None.
const element = document.querySelector('div[is="stateful-element"]');
// Set the state 'active' to true
element.setState({ active: true });// Set the state 'error' to false
element.setState({ error: false });// Update multiple states at once
element.setState({
'loading': true,
'visible': false
});The getState method returns a copy of the element's whole state object.
element.getState();- None.
- Returns a shallow copy of the current state object.
// Read the current value of 'active'
const isActive = element.getState().active;
console.log(isActive); // Output: true// Read the current value of 'error'
const isError = element.getState().error;
console.log(isError); // Output: falseThe watchState method registers a callback that runs every time setState is called. It does not filter by state name, and it is not called by mergeState, groupState or the other methods.
element.watchState(callback);callback: A function to be executed whensetStateruns.
callback: (Required) A function to be executed whensetStateruns. It receives an object whosedetail.stateholds the full state after the update. This is a plain callback, not a DOM event.
// Log the state after each setState call
element.watchState((event) => {
console.log('State changed:', event.detail.state);
});These are methods on StatefulElement that work on its own state object. They are not polyfills: the library does not use ElementInternals or CustomStateSet, and the states do not match the :state() CSS selector.
addState:Adds a key to the element's state.hasState:Checks if a key exists in the element's state.removeState:Removes a key from the element's state.
The addState method adds a key to the element's state, with a value of true unless another value is given.
element.addState(stateName, value);stateName: A string representing the name of the state to be added.value: The value to store. Defaults totrue.
stateName: (Required) A string representing the name of the state to be added.value: (Optional) The value to store. Defaults totrue.
- None.
// Add the state 'active'
element.addState('active');The hasState method checks if a key exists in the element's state.
element.hasState(stateName);stateName: A string representing the name of the state to check.
stateName: (Required) A string representing the name of the state to check.
- Returns a boolean indicating whether the specified key exists.
// Check if the state 'active' exists
const isActive = element.hasState('active');
console.log(isActive); // Output: trueThe removeState method removes a key from the element's state.
element.removeState(stateName);stateName: A string representing the name of the state to be removed.
stateName: (Required) A string representing the name of the state to be removed.
- None.
// Remove the state 'active'
element.removeState('active');| Path | Contents |
|---|---|
src/ |
StatefulElement.js (the custom element), ElementManager.js and EventManager.js |
test/ |
Jest test file (index.test.js) |
docs/ |
Design documentation; some of it describes behavior that is not implemented |
package.json |
Package metadata and the npm test script |
npm install then npm test runs jest against test/index.test.js. As of this writing the test run does not work: jest is not declared in package.json, and with Jest installed the suite fails with HTMLDivElement is not defined because no browser-like test environment is configured. The tests have not been confirmed to pass.
Early-stage; the v1.0.0 tag and package.json carry version 1.0.0. The library is not published to npm and has no CI workflow. Behavior and non-goals are listed in the introduction and the Usage section above. Notable changes go in CHANGELOG.md.
For detailed documentation and examples, see the docs folder in the repository. The docs describe the design ideas, including ElementInternals, and some of what they describe is not implemented yet.
Contributions to the Stateful DOM Elements Library are welcome! Please refer to the contribution guidelines for more information.
MIT. See LICENSE.