- ClayJS
- Advanced
- API
- Advanced regions
Advanced regions
Querying and writing ClayJS region policy from custom attributes, plugins, and document transforms.
For plugin authors and custom attributes that run inside the save cycle; for the clay attribute keywords and everyday recipes, see Regions.
Respecting regions from your own code#
Writing a custom attribute that touches the save? Ask clayjs what a region means instead of matching [no-save] yourself. That’s what clay.internals.region is for: it’s the same policy the library uses, so your attribute can’t stop agreeing with it two releases from now. It needs one extra script tag, the internals satellite.
<script src="https://clayjs.com/v1/clay-internals.js"></script>
A count-of attribute that writes how many elements match a selector into a badge, and leaves alone the regions that aren’t being persisted as they stand:
await clay.loaded.internals;
const { resolveRegionPolicy, addRegionToken, PERSIST } = clay.internals.region;
clay.internals.addDocumentTransform(clone => {
for (const el of clone.querySelectorAll("[count-of]")) {
// Inside no-save or freeze? This element isn't going to disk as it stands,
// so counting into it is either wasted or wrong.
if (resolveRegionPolicy(el).persist !== PERSIST.FULL) continue;
el.textContent = clone.querySelectorAll(el.getAttribute("count-of")).length;
}
});
Keep the callback pure and repeatable. It runs on the save clone, and it runs again every time clayjs checks whether the page has changed. Write something new on each run, a timestamp being the tempting one, and every check differs from the last, so the page never reads clean and autosave never stops.
When your attribute generates chrome of its own, mark it rather than hoping nobody saves it. addRegionToken merges into whatever clay attribute is already on the element:
addRegionToken(toolbar, "no-save"); // clay="existing-token no-save"
The rest of the surface (isInert, isSnapshotRemoved, REGION_ATTRS, and the raw selectors clayjs strips with) is in the reference.