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
- Choose a shipped figure before defining geometry.
shape.typeselects the figure. The catalog includesrect,circle,ellipse,diamond,hexagon,parallelogram,parallelogram-top,trapezoid,trapezoid-bottom,triangle,triangle-down,package,cube,document,cylinder,cloud,predefined-process,component,note,terminalandactor.textsupplies a boxless annotation. Inspect the registered names, including aliases, withlistShapes(); test a particular name withhasShape(). - Register a path with
registerPathShape()before mounting nodes that name it.PathGeometryaccepts 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 inPathShapeOptions. The renderer samples the path to derive boundary attachments and port anchors. - Use
registerShape()when you need to supply the wholeShapeDefinition. 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, whileportAnchor()andinnerRect()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.
tsimport {
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');
},
};
}
- 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.tsin 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 });
tsx// src/AppearanceExample.tsx
import { useLayoutEffect, useState } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import { createAppearanceExample } from './appearance';
export function AppearanceExample() {
const [example, setExample] = useState<ReturnType<typeof createAppearanceExample> | null>(null);
useLayoutEffect(() => {
const next = createAppearanceExample();
setExample(next);
return () => { next.disposeExtensions(); };
}, []);
if (!example) return <p>Preparing shapes</p>;
return (
<section>
<p>{example.registryInfo}</p>
<div style={{ height: '560px' }}>
<GrafloriaFlow defaultNodes={example.nodes} defaultEdges={example.edges} />
</div>
</section>
);
}
vue<!-- src/AppearanceExample.vue --> <script setup lang="ts"> import { onUnmounted } from 'vue'; import { GrafloriaFlow } from '@grafloria/vue'; import { createAppearanceExample } from './appearance'; const example = createAppearanceExample(); onUnmounted(() => { example.disposeExtensions(); }); </script> <template> <section> <p>{{ example.registryInfo }}</p> <div style="height: 560px"> <GrafloriaFlow :default-nodes="example.nodes" :default-edges="example.edges" /> </div> </section> </template>
ts// src/app/appearance-example.component.ts
import { Component } from '@angular/core';
import type { OnDestroy } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
import { createAppearanceExample } from './appearance';
@Component({
selector: 'app-appearance-example',
imports: [DiagramCanvasComponent],
template: `
<p>{{ example.registryInfo }}</p>
<grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
style="display: block; height: 560px" />
`,
})
export class AppearanceExampleComponent implements OnDestroy {
readonly example = createAppearanceExample();
nodes: NodeSpec[] = this.example.nodes;
edges: EdgeSpec[] = this.example.edges;
ngOnDestroy(): void { this.example.disposeExtensions(); }
}
tsx// src/AppearanceExample.tsx
import { component$, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
import { createAppearanceExample } from './appearance';
export default component$(() => {
const nodes = useSignal<NodeSpec[]>([]);
const edges = useSignal<EdgeSpec[]>([]);
const status = useSignal('Preparing shapes');
const ready = useSignal(false);
useVisibleTask$(({ cleanup }) => {
const example = createAppearanceExample();
nodes.value = example.nodes;
edges.value = example.edges;
status.value = example.registryInfo;
ready.value = true;
cleanup(() => { example.disposeExtensions(); });
});
return (
<section>
<p>{status.value}</p>
<div style={{ height: '560px' }}>
{ready.value && <GrafloriaFlow defaultNodes={nodes.value} defaultEdges={edges.value} />}
</div>
</section>
);
});
The JavaScript sample includes a Close diagram button above the shapes and style comparisons.
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
filltakes 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.
- 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.
tsimport { 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 };
}
- 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 atsrc/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.type | What it draws |
|---|---|
arrow | Triangle arrowhead |
open-arrow | Open arrowhead |
circle | Circular head |
square | Square head |
diamond | Diamond head |
crow-foot | Crow-foot cardinality head |
hollow-diamond | Hollow diamond head |
one-or-many | One-or-many cardinality head |
one | One cardinality head |
zero-or-one | Zero-or-one cardinality head |
zero-or-many | Zero-or-many cardinality head |
filled-diamond | Filled diamond head |
generalization | UML generalization head |
double-arrow | Double arrowhead |
half-arrow-left | Left half-arrowhead |
half-arrow-right | Right half-arrowhead |
cross | Cross head |
bar | Bar head |
dot | Dot head |
oval | Oval head |
custom | A raw path from ArrowStyle.path, or a registered marker named by ArrowStyle.marker |
none | No arrowhead |
| A registered name | Your 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:
registerAnchor()takes anAnchorFnthat chooses one endpoint. The blue lower link namesappearance-quarterinmetadata.sourceAnchorandmetadata.targetAnchor; it leaves and enters at one-quarter of each box's height.registerConnectionPoint()takes aConnectionPointFnthat chooses both endpoints together. The brown link namesappearance-bottominmetadata.connectionPoint; both ends attach to bottom midpoints. Returnnullto decline and let the per-end anchor/port pipeline run.registerConnector()takes aConnectorFnthat turns the routed world-space points into a complete SVG pathd. The brown link selectsappearance-bowthroughconnectorand 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
| Option | Type | Default | What it does |
|---|---|---|---|
PathShapeOptions.viewBox | { x: number; y: number; w: number; h: number } | Unit box 0 0 1 1 | Reference coordinates for a static path |
PathShapeOptions.sampleSteps | number | 24 | Curve subdivision for outline sampling |
PathShapeOptions.portAnchor | ShapeDefinition['portAnchor'] | Sampled outline | Supplies exact local port anchors |
PathShapeOptions.boundaryPoint | ShapeDefinition['boundaryPoint'] | Sampled outline | Supplies exact world-space attachment points |
PathShapeOptions.innerRect | ShapeDefinition['innerRect'] | Padded bounding box | Constrains 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.tipOffset | number | ((style: ArrowStyle) => number) | 0 | Pulls 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.
Related
- Theme a diagram changes theme and type-default layers.
- Route and edit edges covers routing and saved bends.
- Customize rendering contracts fills node interiors with framework content instead of replacing silhouette geometry.
Was this page helpful?