Use the UML kit when your data describes classes and relationships rather than generic boxes and arrows. Declare the class cards, edit their members through typed handles, and cap tall UML or ER cards so their bodies scroll.
Build with data; edit with handles. umlDiagram returns ordinary nodes and edges plus a wiring step. The mounted diagram owns the live models; the kit supplies the compartments, relationship markers and editing controls.
These examples start in the project left by your quick start: JavaScript, React, Vue, Angular or Qwik. Those projects already install the packages used here; no additional install is needed. Keep their entry files, framework configuration and stylesheet imports.
1. Declare classes and every relationship kind
Create this shared module next to the component you add in step 2. For Angular, put it in src/app; for React, Vue and JavaScript, use src; for Qwik, put it next to your route's index.tsx.
Type the input with UmlDiagramOptions. Each UmlClassSpec supplies an ID, optional display name, attributes and methods. Members are strings: include the visibility prefix and signature you want painted, such as # name: String or + speak(): void.
tsimport { umlDiagram } from '@grafloria/element';
import type { UmlDiagramOptions } from '@grafloria/element';
export function buildSpec() {
const options: UmlDiagramOptions = {
editable: true,
classes: [
{ id: 'Animal', position: { x: 60, y: 40 },
attributes: ['# name: String'], methods: ['+ speak(): void'] },
{ id: 'Dog', position: { x: 60, y: 320 },
attributes: ['+ breed: String'], methods: ['+ fetch(): void'] },
{ id: 'Drawable', stereotype: 'interface', position: { x: 400, y: 40 },
methods: ['+ draw(): void'] },
{ id: 'Owner', position: { x: 400, y: 320 },
attributes: ['+ name: String'], methods: ['+ adopt(): void'] },
{ id: 'Collar', position: { x: 60, y: 600 },
attributes: ['+ size: int'], methods: ['+ fasten(): void'] },
{ id: 'Logger', position: { x: 400, y: 600 },
attributes: ['- level: int'], methods: ['+ log(): void'] },
{ id: 'Toy', position: { x: 740, y: 320 },
attributes: ['+ name: String'], methods: ['+ play(): void'] },
{ id: 'Park', position: { x: 740, y: 600 },
attributes: ['+ name: String'], methods: ['+ open(): void'] },
],
relationships: [
{ from: 'Dog', to: 'Animal', kind: 'inheritance',
fromSide: 'top', toSide: 'bottom' },
{ from: 'Dog', to: 'Drawable', kind: 'realization' },
{ from: 'Owner', to: 'Dog', kind: 'aggregation', label: 'owns',
multiplicity: ['1', '0..*'], fromSide: 'left', toSide: 'right' },
{ from: 'Dog', to: 'Collar', kind: 'composition',
fromSide: 'bottom', toSide: 'top' },
{ from: 'Owner', to: 'Logger', kind: 'dependency', label: '«uses»',
fromSide: 'bottom', toSide: 'top' },
{ from: 'Owner', to: 'Toy', kind: 'directed-association',
fromSide: 'right', toSide: 'left' },
{ from: 'Toy', to: 'Park', kind: 'association', label: 'available at',
fromSide: 'bottom', toSide: 'top' },
],
};
return umlDiagram(options);
}
The mounted sample renders eight class cards and seven relationships. The name sits above the attribute and method compartments; «interface» appears above Drawable's italic name.
Each UmlRelationshipSpec names its from and to class IDs. Put the whole at from for aggregation and composition, and the parent or interface at to for inheritance and realization. multiplicity holds the chips at the [from, to] ends.
These are all values of UmlRelationKind:
kind | Rendered notation |
|---|---|
inheritance | Solid line, hollow triangle at to. |
realization | Dashed line, hollow triangle at to. |
association | Solid line without arrowheads; the default kind. |
directed-association | Solid line, open arrow at to. |
aggregation | Solid line, hollow diamond at from. |
composition | Solid line, filled diamond at from. |
dependency | Dashed line, open arrow at to. |
For UML inheritance, the sample attaches Dog's top to Animal's bottom; see Edit database diagrams for choosing relationship attachment sides. For a larger, centre-aligned example of the same notation, open the UML relationships demo.
2. Mount the diagram and edit members
umlClass returns a UmlClass handle for a mounted kit class. Create this shared editing module beside uml-spec.ts:
tsimport { umlClass } from '@grafloria/element';
import type { UmlClass } from '@grafloria/element';
import type { DiagramInstance } from '@grafloria/renderer';
export async function addMovement(api: DiagramInstance): Promise<void> {
const animal: UmlClass = umlClass(api, 'Animal');
await animal.methods.add('+ move(): void');
await animal.setAbstract(true);
}
Capture the mounted DiagramInstance through the binding's ready callback. The button adds + move(): void to Animal and italicises its name. Each handle mutation enters the diagram's history as one edit; there is no extra repaint call.
For React use GrafloriaDiagram; for Vue use GrafloriaDiagram; for Qwik use GrafloriaDiagram. Angular's GrafloriaDiagramComponent hosts the same kit through <grafloria-diagram>. In JavaScript, render mounts the spec into the supplied element and returns the instance.
ts// src/main.ts: retain the quick start's stylesheet imports.
import { render } from '@grafloria/element';
import { buildSpec } from './uml-spec';
import { addMovement } from './uml-edits';
const root = document.getElementById('app');
if (!root) throw new Error('Missing #app');
const button = document.createElement('button');
button.textContent = 'Add movement to Animal';
const host = document.createElement('div');
host.style.height = '700px';
root.append(button, host);
const api = render(buildSpec(), host, { fitView: true });
button.addEventListener('click', () => { void addMovement(api); });
// Call this when your app removes this view, not immediately after mounting.
function unmount() {
api.dispose();
button.remove();
host.remove();
}
const close = document.createElement('button');
close.textContent = 'Close diagram';
close.addEventListener('click', () => { unmount(); close.remove(); });
root.append(close);
tsx// src/UmlEditor.tsx
import { useRef, useState } from 'react';
import { GrafloriaDiagram } from '@grafloria/react';
import type { DiagramInstance } from '@grafloria/renderer';
import { buildSpec } from './uml-spec';
import { addMovement } from './uml-edits';
export function UmlEditor() {
const [spec] = useState(buildSpec);
const api = useRef<DiagramInstance | null>(null);
const [ready, setReady] = useState(false);
return (
<section>
<button disabled={!ready} onClick={() => {
if (api.current) void addMovement(api.current);
}}>Add movement to Animal</button>
<div style={{ height: '700px' }}>
<GrafloriaDiagram spec={spec} options={{ fitView: true }}
onReady={(instance) => { api.current = instance; setReady(true); }} />
</div>
</section>
);
}
vue<!-- src/UmlEditor.vue --> <script setup lang="ts"> import { shallowRef } from 'vue'; import { GrafloriaDiagram } from '@grafloria/vue'; import type { DiagramInstance } from '@grafloria/renderer'; import { buildSpec } from './uml-spec'; import { addMovement } from './uml-edits'; const spec = buildSpec(); const options = { fitView: true }; const api = shallowRef<DiagramInstance | null>(null); function onReady(instance: DiagramInstance) { api.value = instance; } function edit() { if (api.value) void addMovement(api.value); } </script> <template> <section> <button :disabled="!api" @click="edit">Add movement to Animal</button> <div style="height: 700px"> <GrafloriaDiagram :spec="spec" :options="options" @ready="onReady" /> </div> </section> </template>
ts// src/app/uml-editor.component.ts
import { Component, signal } from '@angular/core';
import { GrafloriaDiagramComponent } from '@grafloria/angular';
import type { DiagramInstance } from '@grafloria/renderer';
import { buildSpec } from './uml-spec';
import { addMovement } from './uml-edits';
@Component({
selector: 'app-uml-editor',
imports: [GrafloriaDiagramComponent],
template: `
<button [disabled]="!api()" (click)="edit()">Add movement to Animal</button>
<grafloria-diagram [spec]="spec" [options]="options"
(ready)="api.set($event)" style="display: block; height: 700px" />
`,
})
export class UmlEditorComponent {
readonly spec = buildSpec();
readonly options = { fitView: true };
readonly api = signal<DiagramInstance | null>(null);
edit() {
const instance = this.api();
if (instance) void addMovement(instance);
}
}
tsx// src/routes/index.tsx
import { component$, noSerialize, useSignal } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaDiagram } from '@grafloria/qwik';
import type { DiagramInstance } from '@grafloria/renderer';
import { buildSpec } from './uml-spec';
import { addMovement } from './uml-edits';
export default component$(() => {
const api = useSignal<NoSerialize<DiagramInstance>>();
return (
<section>
<button disabled={!api.value} onClick$={async () => {
if (api.value) await addMovement(api.value);
}}>Add movement to Animal</button>
<div style={{ height: '700px' }}>
<GrafloriaDiagram spec$={() => buildSpec()} options={{ fitView: true }}
onReady$={(instance) => { api.value = noSerialize(instance); }} />
</div>
</section>
);
});
In React or Vue, render the new editor from your existing App component, retaining its stylesheet import. In Angular, add UmlEditorComponent to the root component's imports and put <app-uml-editor /> in its template; retain the root's existing imports and configuration. The JavaScript and Qwik tabs are entry files. Run the quick start's development command and open its local URL.
The framework bindings run the kit's wiring and dispose the instance on unmount. render() also runs finalize for you: do not repeat it to add multiplicity chips. Qwik builds the function-bearing kit spec in the browser through spec$ and keeps only the live instance under noSerialize(); see resumable integration.
With editable: true, double-click a class name or member to rename it. Use the kit's attribute/method add controls and each member's delete control to edit the compartments. Click a member to select its row. Compare the initial class-card structure with the Class diagram demo.
Other handle edits
The handle reads live state on every access. spec is a deep copy, not an object you mutate to update the canvas. Use rename(name), resize({ width, height }), setAbstract(boolean) and setStereotype(string) for the corresponding changes. update(delta) combines changes to name, stereotype, abstract flag, dimensions and full member lists into one edit.
Both attributes and methods provide list(), length, at(index), add(member, { at }), renameAt(index, member) and removeAt(index). Omit at when appending. Read the current members before choosing an index.
CardHandle, the base of UmlClass, supplies exists, width, height, select(), undo() and redo(). Undo and redo operate on the diagram's shared history, not a separate history for that card. onRowSelect(callback) reports this card's row selection and returns an unsubscribe function; unsubscribe when your panel unmounts. For UML, use the callback's selected row rather than its ER-specific field value.
3. Make large ER and UML cards scroll
Give the entity or class a fixed height. The header stays above a scrollable body instead of the card growing to fit every row. The same option works for both kits.
Create this module alongside uml-spec.ts. erDiagram creates the ER card; the two kit outputs share one canvas. Use RenderSpec for the composed spec.
tsimport { erDiagram, umlDiagram } from '@grafloria/element';
import type { RenderSpec } from '@grafloria/element';
export function buildSpec(): RenderSpec {
const er = erDiagram({
entities: [{
id: 'ITEM', name: 'Warehouse Item', position: { x: 60, y: 60 },
height: 260,
columns: Array.from({ length: 21 }, (_, index) => ({
name: `field_${index + 1}`, type: 'varchar',
})),
}],
});
const uml = umlDiagram({
classes: [{
id: 'Animal', name: 'Repository', position: { x: 400, y: 60 },
height: 240,
attributes: Array.from({ length: 16 }, (_, index) => `- field${index + 1}: string`),
methods: Array.from({ length: 10 }, (_, index) => `+ op${index + 1}(): void`),
}],
});
return {
nodes: [...er.nodes, ...uml.nodes],
edges: [...er.edges, ...uml.edges],
finalize: (api) => { er.finalize(api); uml.finalize(api); },
};
}
In your step 2 tab, change the buildSpec import from ./uml-spec to ./scroll-spec. Keep the mount, ready callback and sized host unchanged. The edit button now adds a method to the Repository card, whose ID remains Animal.
You see Warehouse Item capped at 260 diagram units and Repository capped at 240. Put the cursor over either card's rows or members and use the wheel: its body scrolls. The card absorbs the wheel even at the end of its range, so the canvas does not pan. Move off the card to pan; hold Ctrl or ⌘ while wheeling to zoom the canvas, including over a card. Explore both behaviours in the Scrollable cards demo.
Options that matter
| Option | Type | Default | What it does |
|---|---|---|---|
classes | UmlClassSpec[] | Required | Declares the class cards. |
relationships | UmlRelationshipSpec[] | No relationships | Declares links and their UML notation. |
rowSelection | boolean | Enabled unless false | Enables member selection and row events; set false to opt out. |
editable | boolean | false | Adds in-canvas rename, add and delete controls. |
Class height | number | Derived from members | Caps the card and makes its body scroll. |
Class width | number | Derived from content | Sets an explicit card width. |
Relationship kind | UmlRelationKind | association | Chooses the line and marker notation. |
Relationship multiplicity | [string, string] | No chips | Labels the from and to ends. |
Pitfalls
- Look up handles only after the instance is ready.
umlClass()throws for unknown IDs and nodes that are not UML kit cards. Checkexistsbefore using a handle after a deletion. editablecontrols the in-canvas editing chrome, not whether your application can call handle methods. Programmatic handle edits also work without that chrome.- Keep the initial spec stable while editing through handles. A changed spec or options value replaces the diagram in the framework hosts; it is not a command on the current history stack.
- For composed kit specs, retain a
finalizethat invokes each kit's wiring, as the scroll sample does. Copying only nodes and edges omits that wiring step. - For nested host sizing, see Nest containers and lanes. For shared-history controls and transactions, see Commands and history.
Related
- Edit database diagrams covers ER fields and column-level connections.
- Save and restore documents preserves the full kit document rather than a projection of its node specs.
- Export images and vector PDF exports the mounted diagram.
Was this page helpful?