SHADE is young: 0.1.0-next.2 is a pre-release, and 0.1.0 isn't out yet.

SHADE
Sites in other frameworks

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 (== != < <= > >= && || ?? + - * / %), conditional and call. readExpression checks untrusted input: strict shapes, canonical forms, no name that reaches a prototype (__proto__, constructor, toString…) and LIMITS (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 the path of 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: evaluate and 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 are ExpressionErrors (code, path), never a fallback value: report them and show nothing in their place. Dates with a time are compared by moment (== too, so a == b is a <= 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_SCHEMES by default; javascript:, data: and the other NEVER_SCHEMES never pass): the URL, trimmed, null for nothing, or an ExpressionError (url). Call it on what the interpreter gives for an href, a src or a navigate target; compileTemplate writes it into compiled code itself. knownUrlProblem(expression, schemes) checks the texts known when the expression is saved; past MAX_KNOWN_URLS (64) of them it refuses with TOO_MANY_URLS instead 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 are style, srcdoc, formaction, srcset, imagesrcset, http-equiv, id, name, target, rel and role (UNBINDABLE_ATTRIBUTES). A URL attribute (URL_ATTRIBUTES: href with the links' schemes, cite the web's, src, action, poster and the others https only) is wrapped in fx_.url(…, [schemes]), so a client island can't show a javascript: link from state or an entry's text; { kind: 'attribute', name, schemes } sets other schemes. Bind the runtime in the template's scope as fx_ (or runtime), and the roots under their names (or names).
  • The formula bar: parseFormula (with the span of every part, and errors with where and why), printFormula and formatFormula (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 class attribute holds its class ids as they are (the stylesheet escapes them where CSS needs it: 2col as .\32 col, - as .\2d ); a node with local styles gets data-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, and validateStyles refuses two trees of one sheet with one hook. The tree refuses data-s from the team like every data-shade-* attribute. A page picks a variable mode with data-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's prefers-color-scheme decides.
  • 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 under site- 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 as STATE_SELECTORS says, inside :where(); checked is :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 by resolveMedia and checked again, or a path on the site), gradient (linear: an angle) and radial-gradient (a circle or ellipse, a size keyword, a centre in percentages or 'pointer', below), both with repeating and stops at a percentage or a length in STOP_UNITS, calc (two lengths added or subtracted, in any units the property takes, where its entry has calc: calc(100% - 96px)), tracks, placement, ratio, string (only content on ::before/::after, hex-escaped), areas (grid-template-areas: rows of cells, each a name in AREA_NAME or null for ., every row as long, each name's cells a rectangle, never a name in RESERVED_AREA_NAMES), area (grid-area: one such name), filter (filter, backdrop-filter: 1–8 functions, blur with a length in BLUR_UNITS, an amount for the FILTER_AMOUNTS (1 is 100%; up to 1 or MAX_FILTER_AMOUNT), hue-rotate with an angle, drop-shadow with lengths and a colour), clip (clip-path: inset with four sides and round, circle and ellipse with radii (a length or CLIP_RADII) and a centre at, polygon with 3–24 points; lengths or percentages), and list where a property takes several. text-shadow takes shadow without spread or inset (textShadow in its entry), a shadow variable's value held to that too. Values CSS would drop are refused: repeat(auto-fit, 1fr), fr as a minmax() minimum, none inside a list, top 10px, and a var() 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, overflow with overflow-x/overflow-y and grid-area with grid-column/grid-row: the narrower is later in the order, so it wins within a rule. There is no transform: rotate, scale, translate and transform-origin cover it.
  • 3D transforms (experimental, as the text outline below). perspective (none, a length from 0 to 10000 without a percentage, or a size variable) and perspective-origin (a position) go on a parent; transform-style (flat, preserve-3d) and backface-visibility (visible, hidden) are keywords. rotate takes an angle, a turn in the plane, or a list of an axis and an angle (the entry's axis: x, y or z), one axis as CSS's rotate has it. translate takes a third value, a depth (the entry's depth): a length without a percentage or calc(), 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].experimental says): text-stroke-width takes 0 to 8 pixels, or a size variable that comes to that in every mode, and text-stroke-color a 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-width and -webkit-text-stroke-color (the entry's css; cssName gives it), the form every current browser supports. Both are inherited, as CSS has them. Outlined words usually have a transparent color:
    { '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-image takes none or a gradient, linear or radial, as background-image does, 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-position and mask-repeat take what their background-* 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 position may be 'pointer', with a rest of { x, y } in percentages (the middle when left out), in background-image and mask-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. A rest without '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 options being 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 a range: { kind: 'state-number', state, min, max, rest, unit? }, written clamp(<min>,var(--shade-value-<state>,<rest>),<max>) (times one unit: a length unit or deg, none for a number such as opacity); min, max and rest are in the property's range, rest between 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-visible comes with focus and active (a pointer press) with hover; pass states for 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 holding var() is resolved where it is declared, so an alias accent: var(--brand) declared only on :root would 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 <), and themeToCss registers 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-property takes 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 in containers is 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) and media: '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 with not @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, condition for a setting, a feature test or an island's state, state, class, local, none), whether the edited rule is overridden, every contribution in order, inherits, and a variable followed to its value in every mode. originsOf gives 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 }).
  • validateStyles is 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; compileStyles runs it again, writes from the copy only, and checks its own output (cssProblem: no <, no at-rule but its @media and @container queries, a colour variable's @property and its @supports tests (one allow-listed property each), no url() 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 class shade-… or site-…, no custom property --shade-… declared or read, but for var(--shade-pointer-x,<n>%) and var(--shade-pointer-y,<n>%), a pointer centre's two reads with their rest, and var(--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-face rules stay the theme's.
  • It carries no theme of its own: themeStyleSheet, themeVariables, themeToCss and fontFacesCss take a theme's tokens, and the theme itself (its schema, ThemeTokens, and its default, DEFAULT_THEME) is the website module's. themeToCss and fontFacesCss check 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.