# Edit UML class diagrams

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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions#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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start), [React](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/react-quick-start), [Vue](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start), [Angular](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/angular-quick-start) or [Qwik](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-quick-start). 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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-interfaces#umldiagramoptions). Each [`UmlClassSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-interfaces#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 title="uml-spec.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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-interfaces#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-types#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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/edit-database-diagrams) for choosing relationship attachment sides. For a larger, centre-aligned example of the same notation, open the [UML relationships demo](https://grafloria.com/demos/diagrams/uml-relationships.html).

## 2. Mount the diagram and edit members

[`umlClass`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions#umlclass) returns a [`UmlClass`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-classes#umlclass) handle for a mounted kit class. Create this shared editing module beside `uml-spec.ts`:

```ts title="uml-edits.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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-react#grafloriadiagram); for Vue use [`GrafloriaDiagram`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriadiagram); for Qwik use [`GrafloriaDiagram`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-qwik#grafloriadiagram). Angular's [`GrafloriaDiagramComponent`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-overview) hosts the same kit through `<grafloria-diagram>`. In JavaScript, [`render`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core#render) mounts the spec into the supplied element and returns the instance.

:::code-group
```ts title="JavaScript"
// 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 title="React"
// 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 title="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 title="Angular"
// 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 title="Qwik"
// 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>
  );
});
```
:::

![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.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/a95d9380cda26129af09ffb8cf38c454.png)

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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-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](https://grafloria.com/demos/diagrams/class-uml.html).

### 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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-classes#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions) creates the ER card; the two kit outputs share one canvas. Use [`RenderSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core#renderspec) for the composed spec.

```ts title="scroll-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](https://grafloria.com/demos/diagrams/scrollable-cards.html).

## 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. 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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/nest-containers). For shared-history controls and transactions, see [Commands and history](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/commands-and-history).

## Related

- [Edit database diagrams](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/edit-database-diagrams) covers ER fields and column-level connections.
- [Save and restore documents](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/save-and-restore) preserves the full kit document rather than a projection of its node specs.
- [Export images and vector PDF](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/export-diagram) exports the mounted diagram.
