Expressions and styles
@shadestack/expressions
The website editor's expressions: a typed tree, never code. Framework-free and without
dependencies. The tree stores them in its bindings; the rendering core evaluates them on the server
and interprets client islands' live ones in the browser with the same evaluate; the editor's fx bar parses and
checks them as they are typed, with the types the website module checks them with when a page is saved.
import { checkExpression, compileTemplate, createRuntime, evaluate, parseFormula, printFormula, t } from '@shadestack/expressions'
const parsed = parseFormula('formatMoney(product.price) + \' · \' + upper(product.name)')
if (!parsed.ok) console.log(parsed.problem) // { message, start, end }
const scope = { names: { product: t.object({ name: t.text, price: t.money }) } }
const checked = checkExpression(parsed.expression, scope, { kinds: ['text'] })
// { ok: true, type: { kind: 'text' } }, or { ok: false, issues: [{ code, path, message }] }
const runtime = createRuntime({ locale: 'nl-NL', timeZone: 'Europe/Amsterdam', translations: site.texts })
evaluate(parsed.expression, { product: { name: 'Lamp', price: { amount: 1250, currency: 'EUR' } } }, runtime)
// '€ 12,50 · LAMP'
compileTemplate(parsed.expression, 'vue', { kind: 'text' }) // '{{ fx_.add(…) }}', with `fx_` the runtime
printFormula(parsed.expression) // 'formatMoney(product.price) + \' · \' + upper(product.name)'
- The AST:
literal,path(entry.title),member(fields of what a call gives),unary(!,-),binary(==!=<<=>>=&&||??+-*/%),conditionalandcall.readExpressionchecks untrusted input: strict shapes, canonical forms, no name that reaches a prototype (__proto__,constructor,toString…) andLIMITS(256 parts, 32 levels, 1,000 characters per text). Everything below runs it first. - Types: text, number, on/off, date (ISO 8601), money (
{ amount, currency }, SHADE's money type: whole minor units, such as cents, and the currency), URL, rich text, link, image, nothing, optional values, lists, records and data sources (t.text,t.list(…),t.object({ … }),t.optional(…)).checkExpression(expression, { names, unavailable, translations }, expected)refuses a text where on/off is expected, a text joined with a number, truthiness in&&,||,!and conditions, and something that may be nothing where a decision is made; each issue has thepathof the part (args.0) and a hint. - Functions (
FUNCTIONS, with signatures and descriptions for autocomplete):formatDate,formatNumber,formatMoney,translate;lower,upper,trim,slice,includes,startsWith,replace;length,first,last,join,isEmpty;min,max,round,floor,ceil,abs. All pure; no patterns. Their number of arguments (arity) and their values are checked again when they run, whatever the checker said. - One interpreter, one runtime:
evaluateand compiled code call the same runtime, so they agree. Fields are read from plain records' own properties only; anything else in the data (a function, a class instance, a Date) is refused. Errors areExpressionErrors (code,path), never a fallback value: report them and show nothing in their place. Dates with a time are compared by moment (==too, soa == bisa <= b && a >= b), a day next to one being its midnight UTC, and one that isn't a real moment (a month 13, a 30 February) is an error. - URLs: escaping doesn't make a URL safe, so the runtime's
url(value, schemes)checks what an expression gives for a URL place against the scheme allow-list (LINK_SCHEMESby default;javascript:,data:and the otherNEVER_SCHEMESnever pass): the URL, trimmed, null for nothing, or anExpressionError(url). Call it on what the interpreter gives for anhref, asrcor anavigatetarget;compileTemplatewrites it into compiled code itself.knownUrlProblem(expression, schemes)checks the texts known when the expression is saved; pastMAX_KNOWN_URLS(64) of them it refuses withTOO_MANY_URLSinstead of checking only some. - Compiled code (
compileExpression,compileTemplate(expression, 'jsx' | 'vue' | 'svelte', place, { runtime, names })) is one JavaScript expression with text literals escaped to\uXXXX, placed where the framework escapes it, never as HTML;on*attributes and roots that are JavaScript keywords are refused, and so arestyle,srcdoc,formaction,srcset,imagesrcset,http-equiv,id,name,target,relandrole(UNBINDABLE_ATTRIBUTES). A URL attribute (URL_ATTRIBUTES:hrefwith the links' schemes,citethe web's,src,action,posterand the others https only) is wrapped infx_.url(…, [schemes]), so a client island can't show ajavascript:link from state or an entry's text;{ kind: 'attribute', name, schemes }sets other schemes. Bind the runtime in the template's scope asfx_(orruntime), and the roots under their names (ornames). - The formula bar:
parseFormula(with the span of every part, and errors with where and why),printFormulaandformatFormula(with spans). They round-trip.
Code, in shade-frontend: packages/expressions/src/. Tests: packages/expressions/test/*.test.ts.
@shadestack/styles
The website editor's styles. Framework-free, with no dependencies, and not a site
package itself: the renderers write what it says on elements, the website module stores the styles and compiles
them at publish, the style panel edits them, and the accessibility checker
(@shadestack/a11y) reads their contrast. Styles live beside the trees, keyed by class id, and local
styles by tree id and node id (node ids are unique within one tree only); the tree only names classes.
import { compileStyles, originOf, contrastInModes, themeStyleSheet, type StyleSheet } from '@shadestack/styles'
const styles: StyleSheet = {
...themeStyleSheet(theme), // the theme's tokens as the default variables; mobile-first, tablet from 768px and desktop from 992px
classes: [{
id: 'button',
name: 'Button',
rules: [
{ declarations: { 'background-color': { kind: 'var', name: 'color-primary' }, 'padding-top': { kind: 'var', name: 'space-3' } } },
{ breakpoint: 'mobile', declarations: { 'padding-top': { kind: 'length', value: 0.5, unit: 'rem' } } },
{ state: 'hover', declarations: { 'background-color': { kind: 'color', hex: '#1d4ed8' } } }
]
}],
// Local styles by tree id (the page's record), then node id.
local: { 'page-1': { hero01: { rules: [{ declarations: { 'font-size': { kind: 'fluid', min: { kind: 'length', value: 2, unit: 'rem' }, max: { kind: 'length', value: 3.5, unit: 'rem' } } } }] } } }
}
const result = compileStyles(styles, { resolveMedia: id => media.url(id) })
if (result.ok) writeFile('styles.css', result.css) // one minified file, the same bytes for the same styles
else console.log(result.issues) // [{ code, path, message }], at most 200; nothing written
omitCollections leaves out the variables of collections a frontend writes itself: the website module leaves out the
theme's, which the site writes once from the current theme (themeToCss).
- Rendering. An element's
classattribute holds its class ids as they are (the stylesheet escapes them where CSS needs it:2colas.\32 col,-as.\2d); a node with local styles getsdata-s="<tree hook>:<node id>"(localStyleKey(treeId, nodeId),LOCAL_STYLE_ATTRIBUTE): the hook is a short hash of the tree id (treeHook), the same every publish, andvalidateStylesrefuses two trees of one sheet with one hook. The tree refusesdata-sfrom the team like everydata-shade-*attribute. A page picks a variable mode withdata-shade-mode="dark"on<html>(MODE_ATTRIBUTE), or on any element for the part inside it (a light section in a dark page); without it, the visitor'sprefers-color-schemedecides. - SHADE's own names. A renderer's, widget's or the editor's classes and custom properties start with
shade-(RESERVED_CLASS_PREFIXES,RESERVED_VARIABLE_PREFIXES), and classes undersite-are SHADE's site's own. Styles refuse class ids and variable names under them, so no style can hide the consent banner. - Rules hold the declarations for one context: the base or one condition (a breakpoint, a container query, a
visitor's setting, a feature test or an island's state); no state or
hover,focus,focus-visible,active,checked,disabled; the element or::before,::after,::placeholder,::marker. These are the only selectors: each state is written asSTATE_SELECTORSsays, inside:where();checkedis:where(:checked,:has(:checked)), a checked input and what holds one (the label around a radio). - Values are typed, never text (
values.ts):length(with a unit),number,angle,time,color(hex),keyword,var(a defined variable of a type the property takes),fluid(clamp()from a minimum to a maximum over the sheet's viewport range, 375–1440 by default),font,shadow,image(a media library id, resolved byresolveMediaand checked again, or a path on the site),gradient(linear: an angle) andradial-gradient(acircleorellipse, a size keyword, a centre in percentages or'pointer', below), both withrepeatingand stops at a percentage or a length inSTOP_UNITS,calc(two lengths added or subtracted, in any units the property takes, where its entry hascalc:calc(100% - 96px)),tracks,placement,ratio,string(onlycontenton::before/::after, hex-escaped),areas(grid-template-areas: rows of cells, each a name inAREA_NAMEornullfor., every row as long, each name's cells a rectangle, never a name inRESERVED_AREA_NAMES),area(grid-area: one such name),filter(filter,backdrop-filter: 1–8 functions,blurwith a length inBLUR_UNITS, anamountfor theFILTER_AMOUNTS(1 is 100%; up to 1 orMAX_FILTER_AMOUNT),hue-rotatewith an angle,drop-shadowwith lengths and a colour),clip(clip-path:insetwith four sides andround,circleandellipsewith radii (a length orCLIP_RADII) and a centreat,polygonwith 3–24 points; lengths or percentages), andlistwhere a property takes several.text-shadowtakesshadowwithout spread or inset (textShadowin its entry), a shadow variable's value held to that too. Values CSS would drop are refused:repeat(auto-fit, 1fr),fras aminmax()minimum,noneinside a list,top 10px, and avar()whose variable comes to a value the property doesn't take in some mode. - Properties come from the allow-list in
properties.ts(PROPERTIES,propertySpec), longhands only, each with its kinds, units, keywords, ranges and variable types. Adding one is adding its entry; never a free value. Two pairs overlap as CSS has them,overflowwithoverflow-x/overflow-yandgrid-areawithgrid-column/grid-row: the narrower is later in the order, so it wins within a rule. There is notransform:rotate,scale,translateandtransform-origincover it. - 3D transforms (experimental, as the text outline below).
perspective(none, a length from 0 to 10000 without a percentage, or a size variable) andperspective-origin(a position) go on a parent;transform-style(flat,preserve-3d) andbackface-visibility(visible,hidden) are keywords.rotatetakes an angle, a turn in the plane, or a list of an axis and an angle (the entry'saxis:x,yorz), one axis as CSS'srotatehas it.translatetakes a third value, a depth (the entry'sdepth): a length without a percentage orcalc(), from -10000 to 10000.{ 'perspective': px(1200), 'transform-style': kw('preserve-3d') } // the stage { 'rotate': { kind: 'list', items: [kw('x'), { kind: 'angle', value: 55, unit: 'deg' }] }, 'translate': { kind: 'list', items: [px(0), px(0), px(120)] } } // a layer // .layer{rotate:x 55deg;translate:0px 0px 120px} - Text outline (experimental: it may change in a minor version until a second, different use adopts it, which
PROPERTIES[name].experimentalsays):text-stroke-widthtakes 0 to 8 pixels, or a size variable that comes to that in every mode, andtext-stroke-colora colour or colour variable, so the outline follows the modes. CSS has no unprefixed property for it, so the compiler writes them as-webkit-text-stroke-widthand-webkit-text-stroke-color(the entry'scss;cssNamegives it), the form every current browser supports. Both are inherited, as CSS has them. Outlined words usually have a transparentcolor:{ 'color': kw('transparent'), 'text-stroke-width': px(2), 'text-stroke-color': v('color-text') } // .hollow{color:transparent;-webkit-text-stroke-width:2px;-webkit-text-stroke-color:var(--color-text)} - Mask (experimental, as the text outline), a group of its own,
mask:mask-imagetakesnoneor a gradient, linear or radial, asbackground-imagedoes, but no image, so a mask never loads a file. Where the gradient is transparent the element doesn't show; where it is opaque it shows as it is.mask-size,mask-positionandmask-repeattake what theirbackground-*twins take. The compiler writes the standard properties with no-webkit-copies: every current browser takes them. A stop's colour can be a theme variable, so the mask follows the modes:{ 'mask-image': { kind: 'radial-gradient', shape: 'circle', size: 'closest-side', position: { x: 30, y: 40 }, stops: [{ color: v('color-text') }, { color: { kind: 'color', hex: '#0000' }, at: 100 }] }, 'mask-repeat': kw('no-repeat') } // .lit{mask-image:radial-gradient(circle closest-side at 30% 40%,var(--color-text),#0000 100%);mask-repeat:no-repeat} - A centre that follows the pointer (experimental): a radial gradient's
positionmay be'pointer', with arestof{ x, y }in percentages (the middle when left out), inbackground-imageandmask-image. The compiler writes the centre as the two properties the interactions runtime writes, each with the rest as its fallback, so with no script, on touch and under reduced motion the gradient sits at its rest. It moves only on a node an interaction follows the pointer over, or inside one (see Interactions); publishing refuses it anywhere else. Arestwithout'pointer'is refused.{ 'background-image': { kind: 'radial-gradient', shape: 'circle', position: 'pointer', rest: { x: 72, y: 34 }, stops: [{ color: v('color-accent') }, { color: { kind: 'color', hex: '#0000' }, at: 60 }] } } // .glow{background-image:radial-gradient(circle at var(--shade-pointer-x,72%) var(--shade-pointer-y,34%),var(--color-accent),#0000 60%)} - An island's state and number: inside a client island, a rule may be for its text state with fixed
optionsbeing one of them,island: { state, is }, written:where([data-shade-state~="picked:site"])before the selector, so its specificity stays the others'. A value may follow a number state with arange:{ kind: 'state-number', state, min, max, rest, unit? }, writtenclamp(<min>,var(--shade-value-<state>,<rest>),<max>)(times oneunit: a length unit ordeg, none for a number such asopacity);min,maxandrestare in the property's range,restbetween them, and it is what shows before the island runs and outside one. A whole-number property (z-index) and a feature test take none. The checker reads such a number at its lowest end and checks the contrast of each island's state a rule is for.{ island: { state: 'picked', is: 'all-plugins' }, declarations: { 'border-top-style': kw('dashed') } } // :where([data-shade-state~="picked:all-modules"]) .chip{border-top-style:dashed} { 'width': { kind: 'state-number', state: 'level', min: 0, max: 96, rest: 40, unit: 'px' } } // .bar{width:clamp(0px,var(--shade-value-level,40)*1px,96px)} - The cascade (
cascadeOrder): every selector has the same specificity (a class or the attribute, a state in:where()), so order decides: states outermost, then the base, the breakpoints (widest first desktop-first, narrowest first mobile-first), the container queries, the visitor's settings (forced colours, then reduced motion) and the feature tests (all at one rank, so the later in the source wins), then the island's states (one rank too), then the classes in their listed order and local styles last. The order of the classes on an element doesn't matter. So a node's own styles win over its classes in the same state and condition only: a class's tablet value wins over the node's own base value on a tablet. - States that hold together (
activeStates,IMPLIED_STATES): as in the browser,focus-visiblecomes withfocusandactive(a pointer press) withhover; passstatesfor another combination (['focus', 'active']for a keyboard press). The later state in the cascade wins: hover, focus, focus-visible, active, checked, disabled. - Variables compile to custom properties: each collection's default mode on
:root, the other modes under@media (prefers-color-scheme: …)when the page picks none, and under[data-shade-mode=…]every value that differs between a collection's modes (the default mode's too, so modes nest), with every variable that refers to one of those, directly or through others: a custom property holdingvar()is resolved where it is declared, so an aliasaccent: var(--brand)declared only on:rootwould keep the root's brand in a dark section. - Colour variables are typed: every colour variable is registered first, as
@property --brand{syntax:"\3c color\3e ";inherits:true;initial-value:#2563eb}(its default mode's colour; the syntax's<and>as hex escapes, so the file still holds no<), andthemeToCssregisters the theme's colours the same way. So a transition on a variable fades the variable itself, and what is drawn from it inside a gradient, a mask or a filter fades with the page when the mode switches.transition-propertytakes colour variables by name, up to 16 items:{ 'transition-property': { kind: 'list', items: [v('color-background'), v('glow')] }, 'transition-duration': { kind: 'time', value: 500, unit: 'ms' } } // .page{transition-property:--color-background,--glow;transition-duration:500ms} - Container queries: a class with
container: 'inline-size'makes its elements query containers (container: c-<id>/inline-size); a container query incontainersis a width range of it. - Visitors' settings and feature tests:
media: 'forced-colors'is written@media (forced-colors:active)(high contrast and other forced colours) andmedia: 'reduced-motion'@media (prefers-reduced-motion:reduce).supports: { property, value, not? }is a feature test: an allow-listed property that takes no text, with a typed value it takes (never a variable or an image), written through the same serialiser as a declaration,@supports (display:grid)or withnot@supports not (display:grid). A rule has at most one condition: they don't combine with each other or with a breakpoint.compileStyles(styles, { holding: ['reduced-motion'] })writes the named settings' rules without their query, as if they held: for an editor's canvas, never for a site.{ supports: { property: 'display', value: kw('grid'), not: true }, declarations: { display: kw('flex') } } // @supports not (display:grid){.cards{display:flex}} - Origins (
originOf(styles, { treeId, nodeId, classes }, editing, property)): the winning value,kind(here,breakpoint,container,conditionfor a setting, a feature test or an island's state,state,class,local,none), whether the edited rule isoverridden, every contribution in order,inherits, and a variable followed to its value in every mode.originsOfgives them for every property set. - Contrast (
contrastInModes(styles, foreground, background)): the WCAG 2.2 ratio in each mode, resolving variables;meetsContrast(ratio, { level, large, nonText }). validateStylesis the gate before styles are stored: it checks a plain JSON copy of its input and gives that copy back (styles), so store the copy;compileStylesruns it again, writes from the copy only, and checks its own output (cssProblem: no<, no at-rule but its@mediaand@containerqueries, a colour variable's@propertyand its@supportstests (one allow-listed property each), nourl()but a quoted safe address, no!important, balanced braces, and every block in the compiler's grammar: its selectors, its queries, allow-listed properties, and nothing under SHADE's prefixes: no classshade-…orsite-…, no custom property--shade-…declared or read, but forvar(--shade-pointer-x,<n>%)andvar(--shade-pointer-y,<n>%), a pointer centre's two reads with their rest, andvar(--shade-value-<name>,<n>), an island's number with its rest).styleReferences(styles, { classes, trees: [{ treeId, nodeIds }] })lists classes missing or unused and local styles whose node is gone from its tree ({ treeId, nodeId }), for saving to remove.themeWarnings(theme)says what the default variables leave out: font families they can't name, and the web fonts, whose@font-facerules stay the theme's.- It carries no theme of its own:
themeStyleSheet,themeVariables,themeToCssandfontFacesCsstake a theme's tokens, and the theme itself (its schema,ThemeTokens, and its default,DEFAULT_THEME) is the website module's.themeToCssandfontFacesCsscheck what they write again, whoever gave the theme: a colour that isn't a hex colour or a font stack with more than names, quotes and commas is left out, and so is a web font whose address isn't a safe one (isSafeImageUrl) or whose weight or style is off its list.
Code, in shade-frontend: packages/styles/src/. Tests: packages/styles/test/*.test.ts, the sample site's output in
packages/styles/test/__snapshots__/site.css.