Documents v0.9.0 · previews run the real runtime · experimental features are marked exp

Persistent preference

A UI setting that survives a page reload.

persist()set()experimental
Live previewreal runtime

Choose Compact, then reload. Previews on this site run in a sandboxed frame without storage, so they cannot keep the setting: open the standalone page to try the reload.

How it works

  • persist()line 3Keeps a state across reloads, in localStorage or, for the tab’s session, in sessionStorage, under a key you choose.
  • set()lines 5, 6Sets a state to a value. In an :on() rule it is a mutation of the state on the left, --x: set(5), with typed expressions.

A setting that is still selected after a reload. persist("examples.density") stores the state in localStorage and restores it when the page loads again.

Native CSS alternative

None: CSS cannot store anything. Without Reactive CSS this needs a script that reads and writes localStorage.

Limitations

  • Storage is per browser and per origin: the setting does not follow you to another device or browser.
  • Private browsing modes and sandboxed frames may block storage; the state then works without being kept.

Implementation

2 files · 12 lines
style.cssreactive
/* ---- Reactive CSS -------------------------------------------------------------------------- *//* Stored in localStorage under rcss:examples.density. */.prefs { --density: state(comfortable, persist("examples.density")); }.prefs .comfortable:on(click) { --density: set(comfortable); }.prefs .compact:on(click) { --density: set(compact); }.prefs .comfortable { --attr-aria-pressed: when(--density == comfortable); }.prefs .compact { --attr-aria-pressed: when(--density == compact); }.prefs:when(--density == compact) .list li { padding: 6px 14px; font-size: 14px; }.prefs .current { content: var(--density); }
state()Function · hover any red tokenMakes each matching element the owner of an independent state with an initial value.Reference →

Source: site/src/catalog/api/persistent-preference/. style.css from its Reactive CSS divider; the layout above it and the shared api.css run but are not shown.

Related

Draggable card

Move an element using declarative drag events.

experimental:on(drag)event()

Attribute sync

Keep real DOM attributes synchronized with CSS state.

experimental--attr-*toggle()

Focus & blur

Request focus and react when an element loses it.

experimentalfocus::blur