# Style guard

Restores style utilities that legacy scripts overwrite.

Source: https://www.zazz.sh/api/primitives/style-guard/

## Installation

```bash
pnpm dlx zazz-ui add style-guard
```

Run `zazz-ui init` first if the project has no `zazz/` folder yet.

## Example

Load the script once. When the page is ready it starts watching, and from then on it puts back an element's utilities whenever another script replaces its whole `style` attribute.

```html
<script type="module" src="/zazz/primitives/style-guard/style-guard.js"></script>

<div id="banner" style="--p: 4; --bg: var(--color-muted)">Promo</div>
<button type="button" id="legacy">Run the legacy script</button>
<script>
  // a legacy script rewrites the attribute; the guard restores --p and --bg
  document.getElementById("legacy").addEventListener("click", () => {
    document.getElementById("banner").style.cssText = "display: block";
  });
</script>
```

A rewrite that runs before the guard starts (an inline script during page load) wins, because there is nothing to restore yet.

`data-ui-guard="off"` on an element opts it out.

## Behavior

`primitives/style-guard/style-guard.js`

Style guard: keeps utilities alive when scripts rewrite the whole `style` attribute.
Optional, production. A `MutationObserver` on `style` snapshots each
element's `--` declarations on first sight and re-applies them only when one
write drops every one of them at once — the `el.style.cssText = …` and
jQuery `.attr('style', …)` signature. A single `removeProperty('--p')` is a
choice and stays removed (with a single utility, "all" and "one" coincide: the guard
tells them apart by whether the other declarations survived the write).
`data-ui-guard="off"` opts an element out. A template
that emits two `style` attributes cannot be repaired (the parser keeps the
first); that is an authoring error.

## Attributes

This primitive is a composition of other primitives and utilities; it has no presets, slots, or hooks of its own.
