You build a Violet-style UML designer in JavaScript by splitting the job into a model layer, a rendering layer, and an interaction layer. The model holds classes, attributes, operations, and relationships as plain data. The renderer draws those nodes and edges to SVG or canvas. The interaction layer turns mouse gestures into model changes through a command history. Violet itself is a Java desktop application built around diagram editors and graph nodes, so "recreating" it mainly means reproducing that structure—editable class boxes, relationship routing, undo—in a browser rather than porting its source line by line. The condition that matters most: decide early whether you need a full modeling tool or a draw-and-export editor, because the two diverge in scope and effort well before the UI is finished.
This guide walks through a viable build order, the data structures that keep the code sane, the rendering trade-offs, gesture handling, undo, persistence, and the limits you'll hit. I'll flag the points where the honest answer is "this gets hard fast" rather than pretending a weekend project covers it.
What "Violet-style" actually requires you to reproduce
Violet is a lightweight UML editor: you drop class boxes on a canvas, type attributes and methods, draw generalization, association, aggregation, and similar relationships, and the tool keeps the diagram consistent. Its defining traits are modest: a class diagram is a set of nodes with editable compartments plus a set of edges that connect them. Your JavaScript version should target the same core.
Before writing code, write down the feature set. A realistic first version includes:
Class nodes with a name, an attribute list, and an operation list. Four relationship types at minimum: association, generalization (inheritance), aggregation, and composition. Dragging nodes, resizing, and reconnecting edges when a node moves. Selecting, deleting, and editing elements. Undo and redo. Save and load as JSON, plus SVG or PNG export.
Out of scope for version one: sequence diagrams, state machines, use-case diagrams, code generation, and layout algorithms. Violet supports multiple diagram types; if you try to build the whole family before one diagram works, you'll stall. Ship the class diagram first.
The "designer" part deserves a note too. If you mean a tool where a user visually edits UML, the plan below applies. If you mean a library that takes a data model and auto-lays-out a diagram, you're building a renderer, and interaction code drops away. Most people asking this question want the former.
The model layer: plain objects that survive serialization
Keep the model free of DOM references and framework state. A class node looks like this:
An edge:
Three decisions in that schema matter more than they look.
First, every element carries a stable string id. Edges reference nodes by id, never by array index, because indices break the moment something is deleted or reordered. Second, geometry (x, y, width, height) lives on the node rather than being computed at render time, so saving and loading restores exactly what the user saw. Third, the visibility field stores the UML markers (+, -, #, ~) as data, not as part of the displayed name, so you can render or parse them however you like later.
Keep the whole diagram in one object:
That shape is your save format. A version number costs nothing now and saves you when the schema changes.
Avoid storing computed layout in the model. If you calculate edge waypoints, keep them in a separate rendering cache. The moment derived values live next to source data, they drift out of sync and undo snapshots bloat.
Rendering: SVG versus canvas
SVG is the default recommendation for a UML editor. Each node is a element containing a rect and text elements; each edge is a . The browser handles hit-testing through pointer events on individual elements, text stays crisp at any zoom, and you can style everything with CSS. For diagrams with a few hundred elements, SVG performance is fine.
Canvas wins when you have thousands of elements, animated rendering at high frame rates, or need pixel-level control. The cost is that you implement hit-testing yourself: you maintain a mapping from coordinates to elements and test pointer positions against bounding boxes or paths. That's real work, and for typical UML diagrams—dozens to low hundreds of classes—it's usually unnecessary.
If you use a framework like React, render nodes as keyed components and let reconciliation handle updates. The trap is putting interaction state (drag offsets, selection rectangles) into the same store as the model, causing re-renders on every mouse move. Keep transient gesture state in refs or local variables and commit to the model only when the gesture ends.
Text layout is the part newcomers underestimate. A class box needs the name centered in its top compartment, attributes left-aligned below, operations below that, with dividers. You can either measure text and set compartment heights, or fix the height and clip overflow. Measuring is more correct; a rough character-width estimate (average glyph width times character count) is faster and often good enough. Just be consistent, because inconsistent compartment sizing makes the diagram look amateurish even when the logic is right.
Edge routing starts simple. A straight line from source center to target center works for a prototype but looks wrong immediately: arrows land on box interiors. Do the minimum proper version—clip the line to the node boundaries and place the arrowhead at the boundary intersection. For self-relationships (a class pointing at itself), route a small loop out and back. Orthogonal routing with obstacle avoidance is a much bigger project; defer it.
Interaction: turning gestures into model changes
The interaction layer is where most of the bugs live. Structure it as four distinct gesture types, each with a start, move, and end phase.
Prerequisites: the model, renderer, and a coordinate conversion function (screen pixel to diagram coordinate, accounting for pan and zoom) must exist before gestures are meaningful. Get the conversion function right first; nearly every dragging bug traces back to forgetting the pan/zoom offset.
1: Node dragging. On pointerdown over a node, record the pointer position and the node's starting x/y. On pointermove, set the node position to start plus the delta divided by zoom. On pointerup, push a command onto the history stack that captures the before and after positions. Use pointer events (pointerdown, pointermove, pointerup) rather than mouse events so touch and stylus work, and call setPointerCapture so a fast drag that leaves the element still tracks. 2: Selection. Plain click selects one element; shift-click toggles. Draw a selection rectangle on empty-canvas drag and select everything intersecting it on release. Keep a selectedIds set separate from the model. 3: Edge creation. On pointerdown over a node's connection handle, enter edge-drawing mode and draw a temporary line to the pointer. On pointerup over another node, create the edge in the model. Validate first: reject self-associations where they make no sense, reject duplicate edges of the same type between the same pair, and reject connections to the canvas. 4: Editing text. Double-click a name or compartment to swap in an input or contenteditable element positioned over the text. On blur or Enter, commit the change as one undoable command. Commit only once—committing on every keystroke fills your history with garbage.
Checking success: after each gesture, the model should reflect the change and a fresh render should match what's on screen. A quick test is to drag a node, save to JSON, reload the page, and confirm the node returns to the dragged position. If it snaps back, your gesture committed to a copy or your save path reads stale state.
The most common failure is event ordering. If a handle sits inside a draggable node, a pointerdown on the handle can trigger both edge-drawing and node-dragging. Stop propagation on the handle's listener and check event.target before deciding which gesture begins. Test this deliberately, because it's easy to miss until a user complains.
Relationship semantics and how they affect the code
Each relationship type carries different meaning and a different rendering.
| Type | Meaning | Line style | End marker |
|---|---|---|---|
| Association | Structural link | Solid | Open arrow or none |
| Generalization | "Is a" (inheritance) | Solid | Hollow triangle at parent |
| Realization | Implements an interface | Dashed | Hollow triangle |
| Aggregation | "Has a" (weak ownership) | Solid | Hollow diamond at owner |
| Composition | "Owns" (strong, lifecycle) | Solid | Filled diamond at owner |
Store the type in the edge and let the renderer pick markers from a lookup. Don't bake marker geometry into the model.
The semantic layer matters if you ever validate diagrams. A generalization cycle—A inherits from B, B inherits from A—is invalid UML, and catching it is a graph traversal from the parent following generalization edges. Similarly, detecting duplicate class names within one diagram is a simple map check. Build these as pure functions over the model so they're testable without rendering. Do this after the editor works, not before; validation is a nice addition that never blocks the core loop.
One subtlety: composition and aggregation were historically distinct with strong opinions attached—composition implies the part dies with the whole. Most casual users of UML editors don't care and will pick whichever diamond looks right. Don't enforce philosophy; render what they choose and validate only clear structural errors.
Undo, redo, and why command history beats snapshots
Once dragging is possible, users expect undo. Two approaches exist.
Snapshot history: serialize the whole diagram before and after each change and push onto a stack. Dead simple, a dozen lines of code, and works for small diagrams. At a few hundred nodes, each snapshot is maybe tens of kilobytes; a deep history stack consumes memory but is rarely the bottleneck for a desktop-class editor.
Command history: each user action is an object with do() and undo() methods. Node moves, text edits, edge creation, and deletions each become commands.
Commands are the better long-term design because they scale, compose, and name the action for a menu ("Undo Move Order"). Start with snapshots if you want to ship fast, but leave a seam—an applyCommand function the UI calls—so you can swap the mechanism later without touching gesture code.
Two rules prevent most undo bugs. First, one user action equals one history entry: dragging a node fifty pixels during a hundred mouse moves is one command, not a hundred. Push on gesture end, not on move. Second, coalesce text editing so a typed word is one entry per commit, not per keystroke. Clear the redo stack whenever a new command arrives after an undo—that's standard behavior and skipping it produces confusing results.
Test undo by doing a sequence—move, create edge, edit text, delete—then undoing four times and confirming each step reverses exactly. Then redo four times and confirm the final state matches. If anything is off, your commands are capturing mutable object references instead of values; clone what you need at push time.
Saving, loading, and exporting
JSON save and load is nearly free if the model is plain data. Serialize the diagram object with JSON.stringify, download it as a blob, and load with JSON.parse plus a schema check (verify version, that node ids are unique, and that every edge's endpoints exist).
Export to SVG is straightforward: if you render nodes and edges as SVG already, serialize the element with XMLSerializer and inline the styles. Export to PNG requires drawing the SVG onto a canvas via an image and toDataURL—it works but hits the "tainted canvas" rule if any external images or fonts are referenced. Keep the diagram self-contained (no external resources) and you avoid it.
The export path is also where you find out if your coordinate system is clean. A diagram that exports with everything shifted up and left means your root viewBox doesn't match the diagram's bounding box. Compute the bounding box from node geometry and edge waypoints, pad it, and set the viewBox accordingly. Test with a small three-class diagram first, then one with edges leaving the canvas.
If you want interoperability with other tools, XMI is the UML exchange format, but it's heavyweight XML and mapping it faithfully is a project of its own. Provide your own JSON format and skip XMI unless a specific integration demands it.
Testing the core loop without a framework trap
Keep the model functions pure and test them directly: addNode, removeNode (which must cascade-delete connected edges), addEdge with its validation, and the undo/redo stack. These run in plain Node with no DOM. If you write them against a canvas or SVG, you can't test them, and you'll be debugging through the UI forever.
For the interaction layer, one browser test is worth more than many unit tests: drag three nodes into a chain, draw two edges, undo twice, redo twice, save, reload, and load. Automating it with Playwright or a similar driver is reasonable, but even a manual checklist caught early bugs in every editor I've seen built.
A specific stop condition: if you find yourself writing obstacle-avoiding orthogonal edge routing with crossing minimization or replacing the renderer with WebGL, you've crossed from "UML editor" into "graph visualization engine." At that point, evaluate an existing library rather than continuing hand-rolled; further work without that decision tends to produce an unfinished tool.
Realistic effort and what to expect
A minimal but honest class-diagram editor—nodes, four edge types, drag, edit, undo, JSON save—is a few thousand lines of JavaScript and a few focused weeks for one developer, less if you use a framework and skip polish. The long tail is real: keyboard nudging, copy and paste, zoom controls, multi-select drag, alignment guides, and accessibility each feel small and together double the timeline.
The failure modes worth budgeting for: text measurement inconsistencies across browsers, gesture conflicts between handles and nodes, undo commands holding stale references, and edge routing that looks fine on three nodes and chaotic on thirty. Every one of those is solvable, and every one is cheaper to solve by testing early with a deliberate messy diagram than by reading code later.
The tool you're aiming at—a browser-native, lightweight, Violet-class editor—is genuinely achievable in JavaScript. The scope discipline is the hard part, not the code. Pick the class diagram, ship it end to end including save and reload, and let the second diagram type, if any, wait until the first one doesn't embarrass you.