`@shadestack/interactions`
The website editor's interactions. Framework-free, and not a site package itself:
the renderers mark the nodes, write the page's interactions as JSON and load the runtime on pages that have
any; the website module stores and validates them, and a published page carries them (interactions); the editor's
Motion tab edits them. @shadestack/client/render gives resolvePage the page's nodes
(nodesWithInteractions(page.interactions)); give ShadeTree its interactions (<ShadeTree result={result} interactions={page.interactions} />, in every framework package): the runtime starts after the islands
(bootPageInteractions), and plays what an island's playInteraction asks for. A page has one set of interactions (in Astro one script, PAGE_INTERACTIONS_ID; Next, Nuxt and SvelteKit give them to the runtime as data): with a header or
footer that has interactions of its own (PublishedPart.interactions), give one ShadeTree all of them, each
interaction once (mergeInteractions of @shadestack/client/render). missingStyles(site, styles) lists the breakpoints and colours they use that
new styles lack; pageInteractionNodes(page) the nodes a renderer marks.
Interactions live beside the trees as styles do, keyed by tree id, and name the nodes of their own tree. It depends
on @shadestack/tree and @shadestack/styles for validation; its runtime imports only the styles' property writer
(@shadestack/styles/write), which imports nothing.
import { pageInteractions, serializePageInteractions, validateTreeInteractions, type SiteInteractions } from '@shadestack/interactions'
const interactions: SiteInteractions = {
version: 1,
trees: {
'page-1': [{
id: 'heroIn',
trigger: { on: 'inView', node: 'hero', threshold: 0.4 }, // also load, hover, click, scrollProgress, action, pointer
targets: ['heroTitle', 'heroText'],
animation: {
kind: 'keyframes', // or { kind: 'timeline', steps: [{ targets, at, keyframes, timing }] }
keyframes: [
{ opacity: { kind: 'number', value: 0 }, translateY: { kind: 'length', value: 24, unit: 'px' } },
{ opacity: { kind: 'number', value: 1 }, translateY: { kind: 'length', value: 0, unit: 'px' } }
],
timing: { duration: { kind: 'time', value: 600, unit: 'ms' }, easing: 'ease-out-cubic' }
},
scope: { base: true, breakpoints: ['tablet'] }, // not on phones
reducedMotion: 'opacity' // the default: drop movement, keep opacity and colours; or 'end', 'skip'
}]
}
}
// A tree at a time, when that tree is saved (the value limit holds one tree, not a whole site):
const checked = validateTreeInteractions('page-1', interactions.trees['page-1'], { trees: id => trees.get(id), styles })
if (!checked.ok) console.log(checked.issues) // [{ code, path, message }], at most 200
// At publish, per page: every tree it can render (its own and its components', whatever its Ifs show), never the
// trees one visitor saw, so the JSON and the cached page are the same for everyone. Null: the page loads no runtime.
const page = pageInteractions(interactions /* as stored: each tree's checked copy */, ['page-1', 'card-component'], styles)
const json = page && serializePageInteractions(page) // for <script type="application/json" id="shade-interactions">
// In the page, after the islands have hydrated (bundled only for pages with interactions):
import { startPageInteractions } from '@shadestack/interactions/runtime'
const interactions = startPageInteractions() // reads #shade-interactions
// An island's playInteraction action (an `action` interaction; errors are rejections, never throws):
await interactions.play('openMenu', { tree: 'page-1', from: button }).catch(report)
interactions.stop() // every listener, observer and animation gone
- Rendering. A renderer writes
data-shade-interaction="<tree id>:<node id>"(INTERACTION_ATTRIBUTE,interactionAttribute) on every node ofinteractionNodes(interactions, treeId), as it writes local styles'data-s; the tree refuses everydata-shade-*attribute from the team. A node of a component is marked with the component's tree id, in every instance. - Triggers.
load(when the runtime starts);hover(pointer over the node or focus inside it; leaving plays it back);click(toggle: the next click plays it back);inView(threshold0–1,onceby default; it shows its first keyframe until seen, so an entrance doesn't flash in first; seen atthresholdof the element, or of the screen when the element is taller, so a tall section never stays hidden, looked at again on scroll while partly in view; an element with no height is in view while its top is on the screen);scrollProgress(starttoendof the page's scroll, or of a node's way through the viewport);action(onlyplay(id)). Triggers and targets are elements of the interaction's tree. - Following the pointer.
{ id, trigger: { on: 'pointer', node, leave? }, scope? }plays nothing, so it has no targets, animation orreducedMotion. While a mouse or a pen moves over the node, the runtime writes--shade-pointer-xand--shade-pointer-yon it, the pointer's place as a percentage of the node's box (37.5%), at most once per animation frame. A radial gradient whose centre is'pointer'reads them, on the node or inside it (see Expressions and styles). Touch is ignored, and so is the keyboard: the light stays at the rest the design gives it, and nothing else on the node changes.leave: 'stay'(the default) keeps the last place when the pointer leaves;'rest'takes the properties off, so the gradient is back at its rest at once. Under reduced motion the runtime writes nothing, whatever the interaction says, and when a visitor turns reduced motion on, or the width leaves the interaction'sscope, it takes the properties off. A tree follows the pointer over one node at most, and never over a node inside an Each, so a page follows a handful of boxes, never one per item. Publishing a page whose gradient follows the pointer where no interaction follows it is refused (untrackedPointers), since that light would never move.The writer is{ id: 'light', trigger: { on: 'pointer', node: 'hero', leave: 'rest' } } // with, in a class of the hero or of an element inside it: { 'background-image': { kind: 'radial-gradient', shape: 'circle', position: 'pointer', rest: { x: 72, y: 34 }, stops } } // .lit{background-image:radial-gradient(circle at var(--shade-pointer-x,72%) var(--shade-pointer-y,34%),…)}createPropertyWriterof@shadestack/styles/write: it coalesces what it is given into one write per frame and takes properties off at once. - Islands that render again. When an island removes or adds marked elements,
bootPageInteractionsasks the runtime to bind them, once per frame (rebind()): the island's new trigger elements are bound, its newloadtargets play their entrance, and what it removed is let go. The rest of the page goes on as it is: an entrance that played doesn't play again, one seen once stays where it ended, and the pause control's choice holds. playInteractionnames onlyactioninteractions (interactionLookup), andplay(id)plays only those: it rejects withnot-playablefor any other kind (andunknown,ambiguous), never throwing, so an island'sloadcan't start a hover's twenty seconds, and an action never names a scroll interaction that would fail every time.bootPageInteractionsreports such a rejection throughreportError, like the runtime's other problems.interactionLookupalso gives each one's time ({ duration }), andvalidateTreeholds what oneloadplays to five seconds in all (MAX_LOAD_INTERACTION_MSin@shadestack/tree): its plays run one after the other, so their times add up. Given only true or false, aloadplays one interaction at most.- Clicks and the keyboard. A click trigger must be interactive already: a button, a summary, a link with an
href, or an input of type button, submit, reset, checkbox or radio, which browsers click from Enter and Space too. Validation refuses any other node, and the runtime reports and skips any other element; it never adds atabindex, a role or a key handler, so adivnever becomes clickable. - Targets are found from the element that triggered: the nearest ones (the same card in an Each loop, the same
component instance), else every one on the page.
play(id, { from })does the same from the element whose action ran;treeis needed when two trees on the page have the id. A run built on elements another run animates (two cards whose nearest title is the page's one) takes only those from it, so animations never pile up; seeking never takes them back, so scroll-linked cards don't rebuild a shared target on every frame, while playing again (a hover, a click, coming into view) does. - Keyframes animate
opacity,translateX,translateY(px, rem, em, %, vw, vh),translateZ(the same without %),scale,rotate,rotateXandrotateY(deg, turn; at most one of the three per keyframe, as CSS'srotateturns about one axis),blur(px, rem), andcolorandbackgroundColoras the styles' colour variables ({ kind: 'var', name }) only; values are typed as the styles' values, never CSS text. The runtime animates the individualtranslate,scaleandrotateproperties andfilter, withfill: both, so the end holds until it plays back:rotateX: 55degis writtenrotate: x 55deg, and a depth istranslate's third value. A turn about x or y and a depth show only under a parent with aperspectivestyle; they are experimental. Reduced motion drops them with the rest of the movement underopacity, and shows them at once underend. - Timings: a duration, a delay, an easing from
EASINGS(linear,ease,ease-in,ease-out,ease-in-out, and the-cubicand-backcurves), 1–10 iterations or'infinite', and a direction. A timeline's steps start at theiratand end together, so they reverse as one. A timeline runs at most 20 seconds, and at most five when no visitor starts it (load,inView,action; the runtime checks that again); a repeated step takes at least 350 ms each time. - Repeating forever (
iterations: 'infinite',ENDLESS_TRIGGERS; WCAG 2.2.2): onhover, which the runtime cancels when the pointer and focus leave (an endless run has no end to play back from); and onload,inViewandactiononly when the same tree has a pause control (shade:pause-motion) where it always renders: at the top or inside plain elements, not in an If, an Each, an island, a slot, or adetails,dialogorhiddenelement (hasPauseControl). The tree's own, since interactions are validated a tree at a time and a header, footer or component changes on its own. Never onclickorscrollProgress. An endless timeline's other steps still end within 20 seconds; flashes are counted through the first minute (ENDLESS_COUNTED_MS). An island'sloadcan't play an endlessaction(its five seconds); a click can. The runtime plays endless self-started motion only on a page with ashade-pause-motionelement (else it reportsno-pause-control), never under reduced motion whateverreducedMotionsays, andpause(paused)holds every endless animation (and those that start later) and finishes the others;pause(false)lets them go on.bootPageInteractionsfollows the control'sshade:motionevent (detail: { paused }), and the runtime reads the kept choice (localStorage['shade-motion'] === 'paused',MOTION_STORAGE_KEY) when it starts. - No flashing (WCAG 2.3.1,
flashes.ts): no more than three flashes in any second, so no eight changes of what one node shows start within less than a second. What a node shows is counted together:opacity,color,backgroundColor, and movement that hides it, which counts as opacity 0 (HIDING:scaleof 0.1 or less,blurof 8px or 0.5rem or more, a translate of 100%, 100vw or 100vh, 1000px or 62.5rem or more); within an interaction a node also shows its animated ancestors' changes, and a tree'sloadinteractions, which start together, are counted together. Changes of different parts or nodes starting within 8 ms (FOLD_MS) are one. A change is a stretch where a value only rises or only falls, moves to another colour, or between shown and hidden; keyframes going one way are one change, jumps (two keyframes at one offset, a repeat starting over, the first keyframe replacing the element's own value) count. Times come from the computed offsets, iterations and direction, and the easing curve (EASING_CURVES), which may crowd keyframes or, for the-backcurves, turn back by itself; every step on a node counts. ForscrollProgress, eight changes at all are too many. - Breakpoints (
scope): the base and the styles' breakpoint ids, each for the widths where it is the one that applies.widthBandsdraws them with the styles' own media queries and their opposites (bandConditions): desktop-first 991 and 767 make the base{ above: 991 },tablet{ above: 767, atMost: 991 },mobile{ atMost: 767 }; mobile-first usesatLeastandbelow. So the runtime and the styles agree at every width, a fractional one at a browser zoom too. Out of scope, an interaction doesn't play, and it stops when the window leaves its widths. - Reduced motion is read every time something plays, also for animations built before the visitor changed it
(they are built again), and under it nothing animates over time:
opacity(the default) keeps the opacity and colour changes, drops translate, scale, rotate and blur and goes straight to the end state,endgoes straight to the whole end state,skipplays nothing. There is no setting that ignores it. - The page's JSON has no free text:
serializePageInteractionsescapes<,>,&and the line separators all the same, and the runtime checks it again (readPageInteractions: keyframe offsets in order, whichanimate()would throw on, too) before it binds anything; what it can't read or do it reports throughreportError, whichreportErrorssends to the error log. A start that fails part way removes what it bound and gives a runtime that does nothing (start); an animation the browser refuses is reported (animation), never thrown from a listener. validateInteractionsis the gate before interactions are stored: a plain copy of the input, checked against the trees and the styles (without them, everything that needs them is refused), given back asinteractions. Its value limit (MAX_VALUES) holds one tree at every count limit, so a site's interactions are validated a tree at a time, when that tree is saved:validateTreeInteractions(treeId, interactions, options).interactionLookup(interactions, treeId)isvalidateTree'sinteractionsoption forplayInteraction, andinteractionReferences(interactions, treeId, tree)lists what a saved tree no longer has.
Code, in shade-frontend: packages/interactions/src/. Tests: packages/interactions/test/*.test.ts (the runtime on a fake DOM) and
e2e/tests/interactions.spec.ts (the runtime in Chromium, in shade-frontend's e2e/).