Skip to content
D
Documentation

Theme a diagram

how-to
8 min readUpdated

Use a theme when the whole canvas needs a different palette; use object styles when a node or edge carries its own meaning. This page switches light, dark and system modes, adopts host design tokens, and keeps semantic paints live across theme changes.

Start in the project from your JavaScript, React, Vue, Angular or Qwik quick start. Keep the starter's entry point, configuration and stylesheet imports. The examples below add a screen to that project; render it from the existing app or route.

The quick starts install the bindings and their peers. If your project lacks the shared packages used here, add them:

bash
npm install -D @grafloria/renderer @grafloria/engine @grafloria/element @grafloria/react @grafloria/vue @grafloria/angular @grafloria/qwik

Theme-bound properties

  1. Add the shared data file below under src/. In Angular, put it under src/app/ so the component's relative imports stay the same.
  2. Bind semantic strokes with themeRef, rather than storing a particular red on the node. category.critical reads the theme's categories palette; numbers.emphasis reads its numeric scale.

The two incident nodes share a meaning, not a fixed paint. Switching themes recolours their borders and their edge; the high-contrast palette also changes the emphasis width. The plain queue node follows the theme's defaults.

Type the arrays with NodeSpec and EdgeSpec. Start with the shipped LIGHT_THEME, DARK_THEME, HIGH_CONTRAST_LIGHT_THEME and HIGH_CONTRAST_DARK_THEME.

ts
import {
  LIGHT_THEME, DARK_THEME, HIGH_CONTRAST_LIGHT_THEME,
  HIGH_CONTRAST_DARK_THEME, themeRef,
} from '@grafloria/renderer';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';

export const themes = [
  { label: 'Light theme', theme: LIGHT_THEME },
  { label: 'Dark theme', theme: DARK_THEME },
  { label: 'High contrast light', theme: HIGH_CONTRAST_LIGHT_THEME },
  { label: 'High contrast dark', theme: HIGH_CONTRAST_DARK_THEME },
];

export const nodes: NodeSpec[] = [
  {
    id: 'critical', label: 'Disk failure',
    position: { x: 40, y: 60 }, size: { width: 180, height: 76 },
    shape: { type: 'rect', cornerRadius: 12 },
    style: {
      stroke: themeRef('category.critical'),
      strokeWidth: themeRef('numbers.emphasis'), selection: 'ring',
    },
  },
  {
    id: 'warning', label: 'Latency spike',
    position: { x: 300, y: 60 }, size: { width: 180, height: 76 },
    shape: { type: 'terminal' },
    style: { stroke: themeRef('category.warning'), strokeWidth: themeRef('numbers.emphasis') },
  },
  {
    id: 'queue', label: 'Incident queue',
    position: { x: 170, y: 210 }, size: { width: 180, height: 76 },
  },
];

export const edges: EdgeSpec[] = [
  { id: 'e1', source: 'critical', target: 'queue',
    style: { stroke: themeRef('category.critical') } },
  { id: 'e2', source: 'warning', target: 'queue',
    style: { stroke: themeRef('category.warning') } },
];

export const hostTokens = {
  '--card': '210 40% 96%', '--card-foreground': '222 47% 11%',
  '--border': '215 20% 45%', '--primary': '221 83% 53%',
  '--mui-palette-background-paper': '#fffbf2',
  '--mui-palette-text-primary': '#1c1b1f',
  '--mui-palette-divider': '#8b6914',
  '--color-white': '#f0fdf4', '--color-slate-900': '#14532d',
  '--color-slate-300': '#15803d', '--color-slate-400': '#166534',
};

Try the Theme-bound properties demo to compare semantic colours and numeric emphasis across palettes.

Theming

One Theme object drives node defaults, links, typography and selection states. Use the component's theme prop/input for a framework-owned palette, or setTheme() on a mounted DiagramInstance. Neither requires remounting the data.

Adopt host design tokens

  1. Add this helper beside theme-data.ts.
  2. Keep the host's CSS variables on an ancestor of the canvas. The shared hostTokens above gives each adapter a visibly different card surface.
  3. Choose a bridge in the screen below. The queue's fill and the canvas's default strokes follow the host; semantic inline strokes retain their own bindings.

shadcnBridge, muiBridge and tailwindBridge return a TokenBridge. setTokenBridge(null) removes it. The browser resolves the bridge's CSS expressions, so changing an ancestor's tokens updates the diagram without a Grafloria repaint call.

ts
import {
  shadcnBridge, muiBridge, tailwindBridge, deriveTheme,
  auditThemeContrast, contrastRatio, WCAG, CASCADE_ORDER,
  getStyle, listStyles, isThemeRef, resolveThemeRef, resolveNodeStyle,
  GRAFLORIA_INSTANCE_ATTR, MEDIA_PREFERS_DARK, MEDIA_PREFERS_CONTRAST,
} from '@grafloria/renderer';
import type { Theme, TokenBridge } from '@grafloria/renderer';
import type { DiagramModel } from '@grafloria/engine';

export const bridgeChoices = ['Own theme', 'shadcn', 'MUI', 'Tailwind'] as const;

export function bridgeFor(choice: string): TokenBridge | undefined {
  if (choice === 'shadcn') return shadcnBridge();
  if (choice === 'MUI') return muiBridge();
  if (choice === 'Tailwind') return tailwindBridge();
  return undefined;
}

export function styleIncidents(model: DiagramModel): void {
  const critical = model.getNode('critical');
  const warning = model.getNode('warning');
  critical?.setClasses(['incident', 'review']);
  critical?.setStyle({ opacity: 0.9 });
  warning?.setClasses(['incident']);
}

export function describeTheme(model: DiagramModel, theme: Theme, host: HTMLElement): string {
  const node = model.getNode('critical');
  const report = auditThemeContrast(theme);
  const derivedDark = deriveTheme({ from: theme, mode: 'dark' });
  const derivedContrast = deriveTheme({ from: theme, mode: 'high-contrast', textLevel: WCAG.AAA_TEXT });
  const ratio = contrastRatio(theme.colors.text.primary, theme.colors.node.default.fill);
  return JSON.stringify({
    theme: theme.name,
    failures: report.failures.map((check) => check.id),
    unmeasured: report.checks.filter((check) => check.ratio === undefined).map((check) => check.id),
    textRatio: ratio,
    derivedDarkPasses: auditThemeContrast(derivedDark).passes,
    derivedContrastPasses: auditThemeContrast(derivedContrast, WCAG.AAA_TEXT).passes,
    cascade: CASCADE_ORDER,
    styles: listStyles(),
    criticalStyleDefinition: getStyle('critical'),
    boundStroke: node ? isThemeRef(node.style.stroke) : false,
    criticalToken: resolveThemeRef('category.critical', theme),
    resolvedNode: node ? resolveNodeStyle(node, theme) : undefined,
    instanceId: host.querySelector(`[${GRAFLORIA_INSTANCE_ATTR}]`)?.getAttribute(GRAFLORIA_INSTANCE_ATTR),
    osDark: window.matchMedia(MEDIA_PREFERS_DARK).matches,
    osContrast: window.matchMedia(MEDIA_PREFERS_CONTRAST).matches,
  }, null, 2);
}

The diagnostics are an explicit inspection snapshot, not a reactive status indicator. auditThemeContrast returns checks, non-exempt failures and a boolean passes. contrastRatio returns undefined for unparseable paints; an unmeasured pair is not evidence of adequate contrast. Audit the colours your app actually paints: auditing the theme object does not measure a host CSS token override or an arbitrary gradient.

The helper queries the mounted DiagramModel; it does not build a separate document for inspection.

deriveTheme accepts dark (the dark counterpart) or high-contrast (the same colour scheme with repaired contrast). It repairs enforceable failures and throws if the resulting theme cannot meet the requested level.

Bridge optionTypeDefaultWhat it does
shadcn space'hsl' | 'oklch' | 'raw''hsl'Wrap bare components in hsl() or oklch(), or use complete colour values unchanged.
MUI prefixstring'--mui'Select the prefix of the host's CSS-variable palette.
Tailwind scalestring'slate'Select the neutral --color-* ramp.
Tailwind accentstring'blue'Select the accent ramp.

Choose raw for complete shadcn colours such as oklch(0.98 0.01 250). Choose oklch only when the variables contain bare OKLCH components; this mode requires the host to supply those variables. The Tailwind adapter reads v4 CSS variables, not v3 utility class names. See Themes & design tokens for host palette switching.

Dark mode

  1. Add the screen for your framework below. The canvas starts in system mode.
  2. Choose dark, light or system to change the colour-mode source.
  3. Choose a named theme to inspect an explicit palette. In the component examples, this clears the colorMode input and supplies a fresh theme object, so choosing the previously stored palette also applies it. The existing OS subscription remains as described below.

ColorMode controls the light/dark axis; it does not disable accessibility preferences.

ModeResult
lightPin the light axis.
darkPin the dark axis.
systemFollow prefers-color-scheme, including subsequent OS changes.

Contrast or forced-colour preferences upgrade the selected axis to its high-contrast counterpart when that theme exists. DEFAULT_THEME_SET supplies both counterparts. A custom ThemeSet requires light and dark; highContrastLight and highContrastDark are optional.

Mount the screen

The screens below add palette, colour-mode and token-bridge controls to the mounting pattern in Edit nodes from your UI.

ts
import { render } from '@grafloria/element';
import { DARK_THEME, LIGHT_THEME, DEFAULT_THEME_SET } from '@grafloria/renderer';
import { nodes, edges, themes, hostTokens } from './theme-data';
import { bridgeChoices, bridgeFor, describeTheme, styleIncidents } from './theme-tools';

const screen = document.createElement('section');
const controls = document.createElement('nav');
const host = document.createElement('div');
const neighbour = document.createElement('div');
const output = document.createElement('pre');
for (const [key, value] of Object.entries(hostTokens)) screen.style.setProperty(key, value);
host.style.height = '400px';
neighbour.style.height = '400px';
screen.append(controls, host, neighbour, output);
document.getElementById('app')!.append(screen);
const api = render({ nodes, edges }, host, { colorMode: 'system' });
styleIncidents(api.getModel());
const other = render({ nodes, edges }, neighbour, { theme: DARK_THEME });
function button(label: string, action: () => void) {
  const element = document.createElement('button');
  element.textContent = label;
  element.onclick = action;
  controls.append(element);
}
for (const mode of ['light', 'dark', 'system'] as const) {
  button(mode, () => {
    api.setColorMode(mode, DEFAULT_THEME_SET);
    output.textContent = `Requested mode: ${api.getColorMode()}`;
  });
}
for (const choice of themes) button(choice.label, () => api.setTheme(choice.theme));
for (const choice of bridgeChoices) button(choice, () => api.setTokenBridge(bridgeFor(choice)));
button('Inspect light theme', () => { output.textContent = describeTheme(api.getModel(), LIGHT_THEME, host); });
button('Close screen', () => { api.dispose(); other.dispose(); screen.remove(); });

The JavaScript screen shows the incident flow in light and dark palettes on the same page.

The React screen starts with two coloured incident borders feeding the queue.

The Vue screen presents the same flow and inspection controls.

The Angular screen exposes its mode, theme and bridge inputs through buttons.

The Qwik screen shows the incident flow after the canvas mounts.

In Qwik, only serializable data crosses the server/resume boundary. The ready callback stores the live instance with noSerialize(); bridge objects are created in browser event handlers, not captured in resumable state.

Angular's ready callback receives a GrafloriaCanvasInstance; keep theme, mode and bridge changes in the canvas inputs. Removing colorMode does not remove an instance's existing mode subscription. An explicit palette can paint now, and a later OS preference change can still resolve that subscription. For an exclusively app-owned palette, omit colorMode from the outset and use only the named-theme controls.

The JavaScript screen also mounts an independent dark neighbour. Changing the first canvas leaves that neighbour's variables alone. GRAFLORIA_INSTANCE_ATTR identifies the root carrying each instance's variable scope. See Instance-scoped CSS variables and the Dark mode demo.

getColorMode() reports the requested mode, not the resolved theme. MEDIA_PREFERS_DARK and MEDIA_PREFERS_CONTRAST are the query strings used in the inspection snapshot. You do not need your own listeners to make system mode follow the OS.

The React, Vue and Qwik mode buttons call setColorMode() on the mounted instance before updating the prop. This applies the requested mode even when it matches the controller's last request after an explicit theme selection.

Styling & theming

Use shape configuration for geometry and style for the object's paint. Shape fill, stroke, strokeWidth, cornerRadius and opacity accept CSS colours, pixel widths/radii and opacity from 0 to 1. A node's explicit style paints override its shape paints; state styling comes afterward.

Style individual objects

For initial data preparation, apply styles and CSS classes to live NodeModel objects. The styleIncidents() helper in theme-tools.ts assigns incident classes and gives the critical node 0.9 opacity. Each mounting example above calls it with api.getModel() from its init/ready callback, so it acts on the mounted incident nodes.

setStyle() merges properties. replaceStyle() replaces the whole style object, including removal of omitted keys. setClasses() replaces the CSS-class collection; addClass() and removeClass() change one class. These CSS classes are distinct from named style definitions referenced through style.styleClass. For inspector edits that the reader can undo, use the command path in Edit nodes from your UI, rather than treating direct model preparation as a history command.

CASCADE_ORDER lists the precedence, lowest to highest:

LayerWhat wins here
themeThe theme's general defaults.
type-defaulttheme.nodes[type] or the link-type default.
named-classNamed styles, applied left to right in style.styleClass.
element-inlineThe object's own declared paints.
stateSelection, then highlight, hover, disabled and error.

The inspection helper uses listStyles and getStyle to inspect registered named definitions; an unregistered name returns undefined. resolveNodeStyle resolves cascade layers, while isThemeRef detects a binding and resolveThemeRef reads its token. A missing token returns undefined: treat it as an unset property, not a paint value. These are inspection tools; let the mounted renderer apply the cascade.

Paint servers

Replace the shared node array with the following data to draw a linear gradient and its twin, a radial gradient, a dot pattern and a shadow. The mounting code in each framework stays the same. Two identical gradient specs share a definition; paints remain SVG resources rather than flattened colours.

ts
import type { NodeSpec } from '@grafloria/renderer';

export const paintNodes: NodeSpec[] = [
  { id: 'linear', label: 'Linear', position: { x: 40, y: 60 },
    size: { width: 180, height: 76 }, style: { fill: {
      type: 'linear', x1: 0, y1: 0, x2: 1, y2: 1,
      stops: [{ offset: 0, color: '#c4b5fd' }, { offset: 1, color: '#fbcfe8' }],
    } } },
  { id: 'twin', label: 'Linear twin', position: { x: 280, y: 60 },
    size: { width: 180, height: 76 }, style: { fill: {
      type: 'linear', x1: 0, y1: 0, x2: 1, y2: 1,
      stops: [{ offset: 0, color: '#c4b5fd' }, { offset: 1, color: '#fbcfe8' }],
    } } },
  { id: 'radial', label: 'Radial', position: { x: 40, y: 190 },
    size: { width: 180, height: 76 }, style: { fill: {
      type: 'radial', cx: 0.5, cy: 0.4, r: 0.6,
      stops: [{ offset: 0, color: '#fef08a' }, { offset: 1, color: '#fdba74' }],
    } } },
  { id: 'dots', label: 'Dots', position: { x: 280, y: 190 },
    size: { width: 180, height: 76 }, style: { fill: {
      type: 'dots', color: '#0369a1', backgroundColor: '#e0f2fe', size: 2, spacing: 10,
    } } },
  { id: 'shadow', label: 'Shadow', position: { x: 160, y: 320 },
    size: { width: 180, height: 76 }, style: {
      fill: '#f8fafc', shadow: { offsetX: 4, offsetY: 6, blur: 8, color: 'rgba(0,0,0,0.4)' },
    } },
];

For example, mount that data in a separate browser panel, without changing the incident screen:

ts
import { render } from '@grafloria/element';
import { paintNodes } from './paint-data';

const panel = document.createElement('section');
const host = document.createElement('div');
const close = document.createElement('button');
host.style.height = '480px';
close.textContent = 'Close paints';
panel.append(close, host);
document.getElementById('app')!.append(panel);
const api = render({ nodes: paintNodes, edges: [{ source: 'linear', target: 'twin' }] }, host);
close.onclick = () => { api.dispose(); panel.remove(); };
Matching linear-gradient nodes, a radial gradient, a dot-pattern node and a shadowed node, with a Close paints button.

Inspect the shapes' url(#…) fills and the corresponding <linearGradient>, <radialGradient>, <pattern> and <filter> entries in <defs>. See the Paint servers demo.

Selection and outline options

OptionTypeDefaultWhat it does
themeThemeLIGHT_THEMESupplies the canvas palette when colour mode does not choose it.
colorMode'light' | 'dark' | 'system'UnsetSelects a palette from the theme set and follows accessibility preferences.
tokenBridgeTokenBridgeUnsetRe-points instance variables to host tokens.
highlighterConfigboolean | Partial<HighlighterConfig>falseEnables/configures overlay decorations independently of body paint.
style.selection'both' | 'border' | 'ring''both'Selects the body's selection treatment.

both changes the fill and border and draws the ring; border changes only the border; ring keeps the body's paint and shows the ring. The incident sample uses ring to preserve its semantic critical stroke.

HighlighterConfig controls hover, selection, validation and connect-target decorations with showHover, showSelection, showValidation and showConnectTargets; its padding fields are hoverPadding, selectionPadding and validationPadding. Use setHighlighterConfig(true) to enable the layer, an object to configure it, or false to disable it. Angular exposes this through [highlighterConfig] rather than its ready instance.

WCAG exports AA_TEXT (4.5), AA_LARGE (3), AA_NON_TEXT (3), AAA_TEXT (7) and AAA_LARGE (4.5). toHex converts numeric RGB channels to a hex string; it is not a theme switch or token resolver.

Pitfalls

  • Do not expect a literal fill or stroke to change with the theme. Bind the meaning with themeRef() when it must move with the palette.
  • Do not use a theme audit as a measurement of the final browser cascade. Inspect your host-token colours and explicit object paints separately.
  • Do not combine a palette binding with an active colour-mode source and expect the palette binding to choose the mode's theme. Give custom mode palettes through themes instead.
  • Do not style unrelated page elements with Grafloria's internal node selectors. Scope host styles to your own screen; Grafloria scopes its own variables to the instance.

Was this page helpful?