Skip to content
D
Documentation

Edit UML class diagrams

how-to
6 min readUpdated

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.

ts
import { 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:

kindRendered notation
inheritanceSolid line, hollow triangle at to.
realizationDashed line, hollow triangle at to.
associationSolid line without arrowheads; the default kind.
directed-associationSolid line, open arrow at to.
aggregationSolid line, hollow diamond at from.
compositionSolid line, filled diamond at from.
dependencyDashed 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:

ts
import { 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);
Look at the class compartments, the italic Drawable interface name, and the hollow triangle and diamond relationship markers. The Add movement to Animal button sits above the initial diagram.

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.

ts
import { 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

OptionTypeDefaultWhat it does
classesUmlClassSpec[]RequiredDeclares the class cards.
relationshipsUmlRelationshipSpec[]No relationshipsDeclares links and their UML notation.
rowSelectionbooleanEnabled unless falseEnables member selection and row events; set false to opt out.
editablebooleanfalseAdds in-canvas rename, add and delete controls.
Class heightnumberDerived from membersCaps the card and makes its body scroll.
Class widthnumberDerived from contentSets an explicit card width.
Relationship kindUmlRelationKindassociationChooses the line and marker notation.
Relationship multiplicity[string, string]No chipsLabels 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. Check exists before using a handle after a deletion.
  • editable controls 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 finalize that 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.

Was this page helpful?