@magnet-js/style
v0.1.1
Published
Reactive scoped styles for Magnet.
Readme
@magnet/style
Reactive scoped styles for Magnet, built on the CSS
@scope at-rule.
Install
JSR
deno add jsr:@magnet/stylenpm via JSR
npx jsr add @magnet/stylenpm
npm install @magnet-js/styleUsage
styleScoping(context, head)
Creates a style tagged template literal bound to a Magnet context and a head
element. The context is any Magnet context (from @magnet/ui or a compatible
implementation), and head is the element where style elements are mounted.
import { styleScoping } from "@magnet/style";
import { magnet } from "@magnet/ui";
import { tc39 } from "@magnet/signal";
const m = magnet({ window, ...tc39 });
const style = styleScoping(m, document.head);style tagged template
Interpolate plain values or signals into a CSS sheet. The full CSS content is
hashed into a scope identifier (S<hash>), a single <style> element per
unique hash is mounted into head, and the sheet is wrapped in
@scope (.<hash>) { ... }.
Static styles return a [scope, cleanup] pair. Reactive styles (any
interpolation that is a signal) return a [computedScope, cleanup] pair.
// Static style
const [scope, dispose] = style`
:scope { display: grid; }
button { color: red; }
`;
// <div class="S1b47q3"> ... </div>
dispose(); // clears the element when done// Reactive style
const { state } = tc39;
const color = state("red");
const [scope, dispose] = style`:scope { color: ${color}; }`;
scope.get(); // current scope identifier
color.set("blue"); // scope updates, element content updatesIdentical stylesheets share one scope and one <style> element. Elements are
reference-counted and pooled: when the count reaches zero, the element is
cleared and reused.
SSR
Use ssrWindow from @magnet/ssr to render scoped styles on the server:
import { ssrWindow } from "@magnet/ssr";
import { magnet } from "@magnet/ui";
import { tc39 } from "@magnet/signal";
const m = magnet({ window: ssrWindow, ...tc39 });
const head = ssrWindow.document.createElement("head");
const style = styleScoping(m, head);
const [scope] = style`:scope { color: red; }`;
head.toString();
// <head><style>@scope (.S1ufux28) {
// :scope { color: red; }
// }</style></head>Public API
styleScoping— creates astyletagged template literal.Style— tagged template literal type.StyleScope— scope identifier type (S${string}).StyleValue— interpolable value type.
License
MIT © 2026 Fernando G. Vilar.
