Skip to content
D
Documentation

Define shapes and styles

how-to
8 min readUpdated

Use geometry extensions when a built-in figure cannot express your node, or when your domain needs its own arrowhead or attachment rule. The example renders a star, a diamond and a custom badge; reusable orange and bold styles; and two links with different attachment strategies.

The model stores intent, not pixels: specs name shapes, styles and connectors, and the renderer resolves those names into geometry. This page goes below the component surface to define that geometry, then mounts the same specs through each binding.

Start in the project left by your quick start: JavaScript, React, Vue, Angular or Qwik. Those projects already install the packages used here. Keep their entry files, configuration and stylesheet imports. Add the module below beside the new component, then render that component from your existing application. For Angular, put the module in src/app/appearance.ts; for the other projects, use src/appearance.ts.

Shapes

  1. Choose a shipped figure before defining geometry. shape.type selects the figure. The catalog includes rect, circle, ellipse, diamond, hexagon, parallelogram, parallelogram-top, trapezoid, trapezoid-bottom, triangle, triangle-down, package, cube, document, cylinder, cloud, predefined-process, component, note, terminal and actor. text supplies a boxless annotation. Inspect the registered names, including aliases, with listShapes(); test a particular name with hasShape().
  2. Register a path with registerPathShape() before mounting nodes that name it. PathGeometry accepts either a static SVG path string or a function of width and height. The star below uses the function form. A static path authored in a design tool needs its reference box in PathShapeOptions. The renderer samples the path to derive boundary attachments and port anchors.
  3. Use registerShape() when you need to supply the whole ShapeDefinition. The badge below supplies an outline, boundary solver, port anchors and an inner label rectangle. outline() handles growth for selection and translation for shadows; boundaryPoint() uses world coordinates, while portAnchor() and innerRect() use local coordinates.

Type the data with NodeSpec and EdgeSpec. The shared module also defines the marker, styles and link extensions used in the following sections. It exports a setup function, not a mounted diagram.

For styles, use defineStyle() or defineStyles() with NamedStyle. For arrowheads, pass a MarkerDefinition to registerMarker() and remove it with unregisterMarker() when finished. The link extensions pair registerAnchor() with AnchorFn, registerConnectionPoint() with ConnectionPointFn, and registerConnector() with ConnectorFn.

ts
import {
  defineStyle, defineStyles, hasShape, listShapes,
  registerAnchor, registerConnectionPoint, registerConnector,
  registerMarker, registerPathShape, registerShape, unregisterMarker,
} from '@grafloria/renderer';
import type {
  AnchorFn, ConnectionPointFn, ConnectorFn, EdgeSpec, MarkerDefinition,
  NamedStyle, NodeSpec, PathGeometry, PathShapeOptions, ShapeDefinition,
} from '@grafloria/renderer';

export function createAppearanceExample() {
  const star: PathGeometry = (w, h) => {
    const cx = w / 2;
    const cy = h / 2;
    const outer = Math.min(w, h) / 2;
    const inner = outer * 0.42;
    let d = '';
    for (let i = 0; i < 10; i++) {
      const radius = i % 2 ? inner : outer;
      const angle = -Math.PI / 2 + i * Math.PI / 5;
      d += `${i ? 'L' : 'M'}${cx + radius * Math.cos(angle)},${cy + radius * Math.sin(angle)} `;
    }
    return d + 'Z';
  };
  const starOptions: PathShapeOptions = {
    innerRect: (w, h) => ({ x: w * 0.3, y: h * 0.3, w: w * 0.4, h: h * 0.4 }),
  };
  registerPathShape('appearance-star', star, starOptions);

  const badge: ShapeDefinition = {
    type: 'appearance-badge',
    outline(w, h, transform = {}) {
      const grow = transform.grow ?? 0;
      return {
        el: 'rect',
        geom: {
          x: (transform.dx ?? 0) - grow,
          y: (transform.dy ?? 0) - grow,
          width: w + 2 * grow, height: h + 2 * grow,
          rx: 16 + grow, ry: 16 + grow,
        },
      };
    },
    boundaryPoint(rect, side, cross) {
      if (side === 'left' || side === 'right') {
        return {
          x: side === 'left' ? rect.x : rect.x + rect.w,
          y: Math.max(rect.y + 16, Math.min(rect.y + rect.h - 16, cross)),
        };
      }
      return {
        x: Math.max(rect.x + 16, Math.min(rect.x + rect.w - 16, cross)),
        y: side === 'top' ? rect.y : rect.y + rect.h,
      };
    },
    portAnchor(w, h, side, rank, count) {
      const fraction = (rank + 1) / (count + 1);
      if (side === 'left' || side === 'right') {
        return { x: side === 'left' ? 0 : w, y: 16 + (h - 32) * fraction };
      }
      return { x: 16 + (w - 32) * fraction, y: side === 'top' ? 0 : h };
    },
    innerRect: (w, h) => ({ x: 18, y: 10, w: w - 36, h: h - 20 }),
  };
  registerShape(badge.type, badge);

  const warn: NamedStyle = { fill: '#f97316', stroke: '#9a3412', strokeWidth: 2 };
  defineStyle('appearance-warn', warn);
  defineStyles({
    'appearance-bold': { strokeWidth: 6 },
    'appearance-wire': { stroke: '#2563eb', strokeWidth: 3 },
  });

  const feather: MarkerDefinition = {
    tipOffset: (style) => style.size,
    render: (ctx) => ({
      type: 'path',
      props: {
        d: `M0,0 L${ctx.size},0 M${ctx.size * 0.4},-4 L${ctx.size},0 L${ctx.size * 0.4},4`,
        stroke: ctx.color, fill: 'none', 'stroke-width': ctx.width,
        transform: ctx.transform, className: 'arrow arrow-appearance-feather',
      },
    }),
  };
  registerMarker('appearance-feather', feather);

  const quarter: AnchorFn = ({ end, other }) => {
    const right = other.rect.x > end.rect.x;
    return {
      point: { x: end.rect.x + (right ? end.rect.w : 0), y: end.rect.y + end.rect.h / 4 },
      side: right ? 'right' : 'left',
    };
  };
  const bottomPair: ConnectionPointFn = ({ source, target }) => ({
    start: { x: source.rect.x + source.rect.w / 2, y: source.rect.y + source.rect.h },
    end: { x: target.rect.x + target.rect.w / 2, y: target.rect.y + target.rect.h },
    sourceDirection: 'bottom', targetDirection: 'bottom',
  });
  const bow: ConnectorFn = ({ points }) => {
    const first = points[0]!;
    let d = `M${first.x},${first.y}`;
    for (let i = 1; i < points.length; i++) {
      const previous = points[i - 1]!;
      const point = points[i]!;
      d += ` Q${(previous.x + point.x) / 2},${(previous.y + point.y) / 2 + 40} ${point.x},${point.y}`;
    }
    return d;
  };
  const removeAnchor = registerAnchor('appearance-quarter', quarter);
  const removeConnectionPoint = registerConnectionPoint('appearance-bottom', bottomPair);
  const removeConnector = registerConnector('appearance-bow', bow);

  const nodes: NodeSpec[] = [
    { id: 'star', label: 'Star', position: { x: 40, y: 40 }, size: { width: 140, height: 120 },
      shape: { type: 'appearance-star' }, style: { fill: '#dbeafe', stroke: '#2563eb' } },
    { id: 'diamond', label: 'Diamond', position: { x: 320, y: 50 }, size: { width: 140, height: 100 },
      shape: { type: 'diamond' } },
    { id: 'badge', label: 'Badge', position: { x: 600, y: 60 }, size: { width: 160, height: 80 },
      shape: { type: 'appearance-badge' } },
    { id: 'warn', label: 'Named orange', position: { x: 40, y: 220 }, size: { width: 160, height: 70 },
      style: { styleClass: 'appearance-warn' } },
    { id: 'inline', label: 'Inline green', position: { x: 240, y: 220 }, size: { width: 160, height: 70 },
      style: { styleClass: 'appearance-warn', fill: '#22c55e' } },
    { id: 'stacked', label: 'Orange + bold', position: { x: 440, y: 220 }, size: { width: 160, height: 70 },
      style: { styleClass: 'appearance-warn appearance-bold' } },
    { id: 'plain', label: 'Theme', position: { x: 640, y: 220 }, size: { width: 160, height: 70 } },
    { id: 'a', label: 'Source', position: { x: 80, y: 380 }, size: { width: 160, height: 70 } },
    { id: 'b', label: 'Target', position: { x: 560, y: 380 }, size: { width: 160, height: 70 } },
  ];
  const edges: EdgeSpec[] = [
    { id: 'feather', source: 'star', target: 'diamond',
      style: { styleClass: 'appearance-wire', arrowHead: { type: 'appearance-feather', size: 14, filled: false } } },
    { id: 'badge-link', source: 'diamond', target: 'badge' },
    { id: 'quarter-link', source: 'a', target: 'b', router: 'straight', connector: 'straight',
      metadata: { connectionPoint: 'port', sourceAnchor: 'appearance-quarter', targetAnchor: 'appearance-quarter' },
      style: { styleClass: 'appearance-wire' } },
    { id: 'bottom-link', source: 'a', target: 'b', router: 'straight', connector: 'appearance-bow',
      metadata: { connectionPoint: 'appearance-bottom' },
      style: { stroke: '#9a3412', strokeWidth: 3, arrowHead: { type: 'none', size: 14, filled: false } } },
  ];

  return {
    nodes, edges,
    registryInfo: `Star registered: ${hasShape('appearance-star')}. Shape names: ${listShapes().length}.`,
    disposeExtensions() {
      removeConnector();
      removeConnectionPoint();
      removeAnchor();
      return unregisterMarker('appearance-feather');
    },
  };
}
  1. Mount the example using your binding. The JavaScript tab runs in the browser; the others add a component to the quick-start project. Use the same appearance.ts in every tab. React and Vue seed uncontrolled defaults. Angular returns edits through its two-way bindings. Qwik registers browser geometry in a visible task before rendering the flow and keeps only serializable arrays and text in signals. Import the Qwik component into your existing route and render it there.

Pass the example's registered shape, marker and style names through the node and edge specs; Edit nodes covers the mounting APIs.

ts
// src/main.ts — keep any stylesheet imports from your existing entry.
import { render } from '@grafloria/element';
import { createAppearanceExample } from './appearance';

const host = document.createElement('div');
host.style.height = '560px';
host.style.width = '100%';
const status = document.createElement('p');
const close = document.createElement('button');
close.textContent = 'Close diagram';
document.body.append(status, close, host);
const example = createAppearanceExample();
status.textContent = example.registryInfo;
const instance = render({ nodes: example.nodes, edges: example.edges }, host);
close.addEventListener('click', () => {
  instance.dispose();
  const removed = example.disposeExtensions();
  status.textContent = `Diagram closed. Feather removed: ${removed}.`;
  host.remove();
  close.remove();
}, { once: true });

The JavaScript sample includes a Close diagram button above the shapes and style comparisons.

JavaScript renders the star, diamond and badge, four style comparisons, two lower links and a Close diagram button.

The React component renders the same geometry and named styles.

The Vue component shows the lower blue link and brown curved link beneath the style comparisons.

The Angular canvas renders the same data through its two-way bindings.

The bindings own their canvas teardown; the samples release their link extensions on unmount.

The top row shows the custom star beside a built-in diamond and the rounded badge. Inspect the full catalog in the live Shapes demo.

Define reusable style sets

The setup calls defineStyle() for the warning style, then defineStyles() for the bold border and blue wire. A NamedStyle carries node properties, link properties or shared properties. Nodes and edges select it through style.styleClass.

Compare the four middle-row nodes:

  • Named orange takes the warning class's orange fill and 2px border.
  • Inline green names the same class, but its own fill takes precedence.
  • Orange + bold combines two space-separated names. The later class wins the border-width conflict, producing a 6px border.
  • Theme names no class and retains the theme's styling.

The cascade runs from lowest to highest: theme → type-default → named-class → element-inline → state. State styling retains precedence over named and inline styles; which selection paints change depends on the node's selection look. Definitions are copied on registration. To change a definition, call defineStyle() again rather than mutating the original object.

Try the same comparisons in the live Named style classes demo.

Style Parser

Use DSL when your style definitions arrive as text. Its parse() method reads a flowchart with comma-separated style properties and returns a diagram whose nodes carry the parsed styles. Property names accept camelCase and kebab-case. Register those styles with defineStyle() to use them on the mounted diagram.

  1. Add this module beside appearance.ts. It builds on the same shapes and links, reads the orange, bold and blue styles from text, and parses the green node's fill override. Copy only the green fill into the existing node style so its warning class remains selected.
ts
import { DSL } from '@grafloria/engine';
import { defineStyle } from '@grafloria/renderer';
import { createAppearanceExample } from './appearance';

export function createParsedAppearanceExample() {
  const example = createAppearanceExample();
  const parser = new DSL();
  const definitions = parser.parse(`
    flowchart LR
      warn[Warning]
      bold[Bold]
      wire[Wire]
      green[Green]
      style warn fill:#f97316,stroke:#9a3412,stroke-width:2
      style bold strokeWidth:6
      style wire stroke:#2563eb,strokeWidth:3
      style green fill:#22c55e
  `);
  for (const node of definitions.getNodes()) {
    defineStyle(`appearance-${node.id}`, node.style);
  }
  const green = definitions.getNode('green');
  if (!green) throw new Error('The style document must define green.');
  const nodes = example.nodes.map((node) => node.id === 'inline'
    ? { ...node, style: { ...node.style, fill: green.style.fill } }
    : node);
  return { ...example, nodes };
}
  1. In the mounting sample for your framework above, replace the factory import with import { createParsedAppearanceExample as createAppearanceExample } from './parsed-appearance';. Keep the remaining mounting and cleanup code unchanged. For Angular, save the new module at src/app/parsed-appearance.ts; the relative import stays the same. Qwik calls the parser inside the existing visible task, before passing serializable specs to the flow.

The mounted result retains the orange node, green inline override, thick orange border and blue links shown above, now with their styles read from text. parse() returns a diagram model; it does not mount a diagram or register renderer style classes on its own.

Register a custom arrowhead

The star-to-diamond link uses registerMarker() with a typed MarkerDefinition. Select the registered name with style.arrowHead.type.

Draw in the marker's local frame with the direction of travel along positive x. Put the supplied transform on the root VNode. tipOffset tells the renderer how far the visual tip lies from the local origin, so it can place that tip at the endpoint. The feather reaches size along x and therefore returns style.size as its offset.

The sample's close/unmount path calls unregisterMarker(); it returns false if the name was not registered. Remove a marker only when no mounted diagram still needs that registration.

arrowHead.typeWhat it draws
arrowTriangle arrowhead
open-arrowOpen arrowhead
circleCircular head
squareSquare head
diamondDiamond head
crow-footCrow-foot cardinality head
hollow-diamondHollow diamond head
one-or-manyOne-or-many cardinality head
oneOne cardinality head
zero-or-oneZero-or-one cardinality head
zero-or-manyZero-or-many cardinality head
filled-diamondFilled diamond head
generalizationUML generalization head
double-arrowDouble arrowhead
half-arrow-leftLeft half-arrowhead
half-arrow-rightRight half-arrowhead
crossCross head
barBar head
dotDot head
ovalOval head
customA raw path from ArrowStyle.path, or a registered marker named by ArrowStyle.marker
noneNo arrowhead
A registered nameYour marker's VNode

The brown bottom link explicitly uses none. Compare the shipped heads with a custom feather in the live Edge markers demo.

Extend attachments and connectors

Use these three seams for different jobs:

  1. registerAnchor() takes an AnchorFn that chooses one endpoint. The blue lower link names appearance-quarter in metadata.sourceAnchor and metadata.targetAnchor; it leaves and enters at one-quarter of each box's height.
  2. registerConnectionPoint() takes a ConnectionPointFn that chooses both endpoints together. The brown link names appearance-bottom in metadata.connectionPoint; both ends attach to bottom midpoints. Return null to decline and let the per-end anchor/port pipeline run.
  3. registerConnector() takes a ConnectorFn that turns the routed world-space points into a complete SVG path d. The brown link selects appearance-bow through connector and curves below its endpoints. The router chooses where the polyline goes; the connector chooses how to draw it.

A connection-point strategy that returns a result owns both ends and takes precedence over per-end anchors. The blue link sets connectionPoint: 'port' to select the declining strategy and reach its explicit anchors. Use a distinct connector name to preserve the built-in behavior of straight, rounded, smooth and bezier: a registered connector with one of those names takes precedence over the renderer's internal branch.

Each of these registration calls returns a disposer that restores the previous registration under that name. The shared module keeps those disposers until the component unmounts or the JavaScript diagram closes.

Options that matter

OptionTypeDefaultWhat it does
PathShapeOptions.viewBox{ x: number; y: number; w: number; h: number }Unit box 0 0 1 1Reference coordinates for a static path
PathShapeOptions.sampleStepsnumber24Curve subdivision for outline sampling
PathShapeOptions.portAnchorShapeDefinition['portAnchor']Sampled outlineSupplies exact local port anchors
PathShapeOptions.boundaryPointShapeDefinition['boundaryPoint']Sampled outlineSupplies exact world-space attachment points
PathShapeOptions.innerRectShapeDefinition['innerRect']Padded bounding boxConstrains the label to the silhouette's interior
ShapeDefinition.styleMode'inline' | 'spread''inline'Chooses body style composition; spread spreads styles as props and merges geometry last
MarkerDefinition.tipOffsetnumber | ((style: ArrowStyle) => number)0Pulls the marker origin back so its tip lands on the endpoint

ArrowStyle supplies the marker size and other arrow styling to an offset function.

Pitfalls

  • Namespace global registration names. These module-level registrations are shared across diagrams in the same process; another registration under the same name replaces yours.
  • Unknown shape names render the rectangle fallback. Use hasShape() to catch spelling errors rather than interpreting a rectangle as successful custom registration.
  • Reserve an inner label box for concave or slanted silhouettes. The default padded bounding box does not describe the star's interior; the sample overrides it.
  • Keep the badge at least 36px wide and 32px high: its fixed-radius anchor and label calculations assume room for their insets.
  • For host sizing beyond the fixed-height samples, use Nest containers and lanes.

Was this page helpful?