Diagram-as-Code System Design Architecture, visual language, style cascade, layout, and mobile interaction
Version 1.0 · July 23, 2026
Consolidated research guide

Build a diagram compiler, not a template library.

The durable asset is a typed semantic graph. Every diagram is a view over that model, compiled through a visual language, a layout policy, and a renderer adapter. Style consistency comes from a controlled semantic cascade with explicit overrides, automatic legends, and inspectable provenance.

Recommended direction Use a custom TypeScript canonical model, ELK as the primary layout engine, React Flow as the primary interactive renderer, native SVG as the portable static renderer, and Mermaid, D2, LikeC4, Structurizr, PlantUML, and Graphviz as compilation targets.
1Canonical semantic model
12Ordered style layers
4Viewport actions
7Release gates
Orientation

Problem framing

Diagram-as-code systems often collapse modeling, styling, layout, rendering, and interaction into one syntax. That works for small diagrams. It fails for distributed systems, ontology, lineage, trust boundaries, runtime state, mobile navigation, and multi-audience communication.

Knowledge

What entities exist? What relationships are factual, inferred, planned, historical, or runtime-derived?

Communication

What question should the view answer? Which audience must understand, decide, or act?

Presentation

Which layout, visual channels, controls, and renderer best express the selected view?

Core constraint: coordinates, colors, and renderer syntax are derived artifacts. They are not the architecture model.
Research synthesis

Tool landscape

The major tools operate at different layers. They should be composed rather than compared as if they solve the same problem.

Class Representative tools Best use Primary limitation
Model-first architecture LikeC4, Structurizr Reusable architecture models and scoped views Not a universal ontology, lineage, or runtime model
Textual diagram DSL Mermaid, D2, PlantUML, nomnoml, Graphviz DOT Documentation, source control, concise authoring Renderer-specific syntax and limited interaction
Interactive graph UI React Flow, AntV X6, GoJS Editors, custom nodes, selection, controls Automatic layout is external or proprietary
Graph analysis Cytoscape.js, G6, Sigma.js Topology, clustering, ontology, large graphs Less suitable for highly authored card layouts
Layout engines ELK, Dagre, D3, WebCola, Graphviz Positions, routing, constraints, graph aesthetics Cannot infer domain meaning
Rendering gateway Kroki Unified access to many textual engines Compatibility layer, not canonical model
Specialized generation Python Diagrams, WaveDrom, DBML, Penrose Infrastructure, timing, schema, constraint diagrams Narrow domain coverage
Commercial SDK yFiles, GoJS Advanced layout, editing, support Licensing and vendor dependence

Primary portfolio

React FlowELKSVGMermaid

Default combination for curated interactive HTML, deterministic layout, portable static output, and documentation export.

Specialized portfolio

Cytoscape.jsSigma.jsD2LikeC4

Use for compound topology, very large graph exploration, technical diagrams, and architecture-model interchange.

Question-driven selection

Diagram question taxonomy

A diagram should be selected by the question it must answer. One diagram should have one primary communication question.

Question Diagram form Preferred layout
What systems exist and who uses them?Landscape or system contextLayered, radial, or curated
What is inside this system?Container or componentCompound layered
Where does it run?Deployment or topologyLayered with containment
What calls what?Dependency graphLeft-to-right layered
What happens during this use case?Sequence or dynamic viewTime vertical, participants horizontal
What states can an entity enter?State machineLayered or orthogonal cyclic graph
Who performs each process step?Swimlane or BPMNFlow axis plus ownership lanes
Where did this data originate?Data lineageLeft-to-right layered, expandable detail
What concepts exist and relate?Ontology or knowledge graphClustered force, radial, query-focused
Where are security boundaries?Trust-boundary viewContainment plus directional flows
When will work happen?Gantt or timelineTime scale plus lanes
How much flows between stages?SankeyLayered weighted flow
Reference architecture

Canonical model and view compiler

The system should model the system once, then compile only the view needed to answer the current question.

Diagram compiler architecture Sources feed a canonical semantic graph. A view contract, visual grammar, and layout router compile the model into renderer adapters, interactive HTML, static exports, and an evaluation loop. Sources DSLs · APIs · runtime Canonical semantic graph entities · relations · evidence View contract question · audience · scope Visual grammar tokens · styles · rules Layout router layered · force · timeline Renderer adapters React Flow · SVG Mermaid · LikeC4 · D2 Interactive HTML zoom · pan · inspect Portable export SVG · PNG · DSLs Evaluation and repair loop
The semantic graph is stable. Views, layout, and renderer syntax are derived.
Canonical TypeScript shape
interface DiagramModel {
  id: string;
  version: string;
  generatedAt: string;
  entities: Entity[];
  relationships: Relationship[];
  groups: Group[];
  vocabularies: Vocabulary[];
  evidence: EvidenceRecord[];
  sourceRegistry: SourceRecord[];
}

interface DiagramView {
  id: string;
  title: string;
  question: string;
  audience: string[];
  perspective:
    | "architecture"
    | "runtime"
    | "deployment"
    | "lineage"
    | "ontology"
    | "security"
    | "ownership"
    | "temporal";
  rootIds: string[];
  include: ViewPredicate[];
  exclude: ViewPredicate[];
  depth: number;
  relationshipKinds: string[];
  layoutPolicy: LayoutPolicy;
  visualPolicy: VisualPolicy;
  interactionPolicy: InteractionPolicy;
  responsivePolicies: ResponsiveViewPolicy[];
}
Spatial reasoning

Layout system

Layout selection must be question-driven. Different algorithms express different semantic relationships.

Layered

Directed dependencies, requests, event flow, lineage, pipelines, and decision graphs.

Default: ELK Layered.

Force or stress

Ontology, knowledge graphs, unknown clusters, and ecosystem exploration.

Default: Cytoscape fCoSE.

Constraint

Trust boundaries, lanes, fixed anchors, ownership, ports, and semantic alignment.

Default: ELK constraints or WebCola.

Hierarchy

Taxonomy, decomposition, ownership, package trees, and call trees.

Default: D3 tree or ELK.

Radial

Blast radius, dependency depth, one selected system and its neighborhood.

Rule: radial distance must mean something.

Timeline or lane

Sequence, Gantt, event history, ownership flow, and incident causality.

Rule: time must be an explicit axis.

Layout router

function selectLayout(ctx: LayoutContext): LayoutFamily {
  if (ctx.hasTimeAxis) return "timeline";
  if (ctx.hasGeography) return "geographic";
  if (ctx.hasFixedPositions || ctx.hasSemanticLanes) return "constraint";
  if (ctx.isRootedTree && !ctx.hasContainment) return "tree";
  if (ctx.isDirectedAcyclic || ctx.dominantDirectionRatio >= 0.7) {
    return ctx.hasContainment ? "compound" : "layered";
  }
  if (ctx.highDegreeNodeCount > 0 && ctx.purpose === "explain") {
    return "radial";
  }
  if (ctx.purpose === "explore") return "force";
  return "constraint";
}
Failure mode: a layout algorithm cannot infer that authentication must precede authorization, a gateway must remain between public and private zones, or a queue is a temporal boundary. Those facts must exist in the semantic model or layout constraints.
Meaning before decoration

Visual language

Each visual channel should have one dominant meaning. The same color, border, or line type must not encode unrelated dimensions.

PositionSequence, hierarchy, ownership, time, or geography
ContainmentScope, deployment, ownership, or trust
ShapeEntity kind
Fill hueStable category or domain
BorderLifecycle, confidence, policy, or exception
MotionLive change or directional activity
Line patternRelationship class
ArrowheadDirection and relationship semantics
Line widthQuantitative magnitude only
OpacityDe-emphasis, not primary status
IconRedundant recognition cue
HaloTemporary focus, alert, or selection

Relationship grammar

RelationshipStrokeArrowNotes
Synchronous requestSolidFilledLabel protocol and operation
Asynchronous eventDashedOpenLabel topic or event
Data movementSolid accentFilledLabel schema or data class
DependencyThin solidOpenAvoid implying runtime traffic
FallbackLong dashOpenLabel trigger condition
Inferred relationshipDottedOpenShow confidence and provenance
Administrative controlDash-dotLabeledSeparate from data plane
Connector rule: use actual path geometry and arrowheads. Reserve whitespace between components. Keep shafts and labels clear of borders and content.
Configuration model

Settings architecture

The system should separate environment, reusable design decisions, semantic recipes, matching rules, and deliberate exceptions.

Settings

Layout engine, direction, routing, zoom, density, legend position, mobile projection, print behavior.

Tokens

Reusable design decisions such as colors, typography, spacing, node dimensions, motion, and line strength.

Styles

Named visual recipes such as node.service, relationship.async, or confidence.inferred.

Rules

Selector-based application of styles using kind, tags, metadata, hierarchy, relationship endpoints, state, or zoom.

Overrides

Explicit exceptions with reason, author, issue, creation date, and optional expiry.

Legend

A compiled representation of the semantic language currently used in the view.

Design principle: a frontmatter block is an authoring surface. It should serialize into the canonical settings model rather than become the canonical model itself.
Consistency with controlled exceptions

Semantic cascade

The system should use an ordered, property-by-property cascade. It should not reproduce CSS specificity.

Twelve-level semantic style cascade The style resolver progresses from renderer fallback through diagram profile, semantic styles, view rules, overrides, interaction state, and accessibility normalization. 1 · Renderer fallback 2 · Diagram profile 3 · Object category 4 · Semantic kind 5 · Semantic facet 6 · Group or scope 7 · Shared view 8 · Inherited / local view 9 · Persistent override 10 · Session preview 11 · Interaction overlay 12 · Accessibility normalization safe rendering defaults topology, lineage, ontology, state node, edge, group, boundary service, queue, database, actor status, lifecycle, confidence, trust environment, domain, lane, container reusable audience and view patterns parent first, child later exact element exception temporary control-panel changes hover, focus, selected, related contrast, reduced motion, forced colors Higher layer wins · within a layer, later matching declaration wins
No numerical specificity. No !important. Exact IDs exist only in the override layer.

Channel ownership

Semantic dimensionPrimary channelsSecondary channels
Entity kindShape, icon, base fillBase border
Relationship kindLine pattern, arrowheadLine color
Domain or categoryFill hue or accent railGroup header
OwnershipContainer, label, corner markerAccent
LifecycleBorder pattern, badgeMuted opacity
Runtime healthStatus marker, haloBorder color
ConfidenceLine pattern, markerOpacity
TrustBoundary and boundary labelEdge crossing marker
SelectionOuter ring, handlesElevation
Quantitative magnitudeWidth or sizeSequential color
Portable style language

Tokens, named styles, rules, and expressions

Token layers

  1. Primitive tokens
    Literal colors, dimensions, timing values, and font families.
  2. Semantic tokens
    Meaning-bearing aliases such as color.node.service.fill.
  3. Context modifiers
    Light, dark, high contrast, screen, print, mobile, desktop, compact, reduced motion.
  4. Resolved map
    Concrete values for the active context before element rules are applied.

Named style example

styles:
  node.service:
    appliesTo: node
    facet: kind
    properties:
      shape: rounded-rectangle
      fill: "{color.node.service.fill}"
      borderColor: "{color.node.service.border}"
      icon: "{icon.node.service}"
      paddingInline: "{space.node.padding.inline}"
      paddingBlock: "{space.node.padding.block}"
    legend:
      group: Elements
      label: Service
      description: Independently deployable software service

Rule example

rules:
  - id: services
    layer: kind
    select:
      kind: service
    use:
      - node.service

  - id: deprecated-elements
    layer: facet
    select:
      tags:
        contains: deprecated
    use:
      - lifecycle.deprecated

Restricted expression example

{
  "$expr": [
    "step",
    ["zoom"],
    "hidden",
    0.65,
    "title-only",
    1.0,
    "title-and-technology",
    1.4,
    "full"
  ]
}
Expressions must be pure, deterministic, serializable, type-checked, bounded, and free from arbitrary JavaScript.
Language made visible

Legend system

The legend must be generated from the same semantic style definitions that render the diagram.

  1. Resolve the current view.
  2. Resolve computed styles for visible elements.
  3. Record semantic styles that contributed visible meaning.
  4. Deduplicate and order legend entries.
  5. Render swatches using the same resolved tokens.
  6. Add continuous scales for quantitative mappings.
  7. Exclude interaction-only states unless an interaction guide is requested.

Legend modes

UsedFull languageCustomCompactExplanatory

Override rule

A semantic override must reuse an existing legend-backed style, add a legend definition, or fail validation.

Computed-style inspector example
Payment API
──────────────────────────────────
fill
  Result: #315DA8
  Token: color.node.service.fill
  Context: dark / standard contrast
  Applied by: style node.service
  Rule: kind = service

borderStyle
  Result: dotted
  Applied by: style lifecycle.deprecated
  Rule: tag contains deprecated

size
  Result: large
  Applied by: element override
  Reason: Primary subject of decision view
Measured geometry

Text, node sizing, and alignment

Layout must use measured node dimensions after the final font and content are available.

  1. Load the actual font.
  2. Normalize title and metadata content.
  3. Measure text runs and semantic wrap points.
  4. Calculate width, height, icon rail, badges, and ports.
  5. Run layout and route edges.
  6. Measure edge labels and detect collisions.
  7. Repair spacing, scope, or orientation.

Alignment rules

  • Use a fixed icon or number rail.
  • Top-align leading icons, badges, or numbers with the title stack.
  • Do not vertically center them against title-plus-description height.
  • Reset heading margins inside nodes.
  • Use a shared spacing scale for padding, labels, ports, and lane gutters.
  • Validate optical centering of SVG glyphs inside wrappers.
  • Never shrink text below the readability floor simply to fit the full graph.
Invalidation matters: paint-only changes should repaint. Typography, padding, label visibility, ports, or shape changes must trigger measurement and layout.
Responsive projection

Mobile and viewport behavior

A mobile diagram is a different projection of the same model, not a desktop screenshot scaled down.

Viewport controls

  • Fit all
  • Fit selection
  • 100% semantic scale
  • Reset view

Responsive recompilation

  • Left-to-right becomes top-to-bottom.
  • Lower-level groups collapse.
  • Secondary labels move into a detail panel.
  • Full topology becomes selected-node neighborhood.

Semantic zoom

LevelVisible information
LandscapeDomains, systems, trust zones, aggregate relationships
SystemContainers, important relationships, ownership
ComponentComponents, protocols, state, key metadata
DetailAttributes, evidence, fields, provenance, runtime metrics

Input and accessibility

Provide pinch zoom, wheel and trackpad zoom, pan, keyboard traversal, search, breadcrumbs, a synchronized node list, non-drag alternatives, focus visibility, screen-reader summaries, and reduced-motion behavior.

Failure prevention

Quality gates

1 · Model validity

IDs, endpoints, containment, temporal consistency, provenance, and lifecycle state.

2 · View validity

Primary question, audience, scope, legend, acronyms, and complexity budget.

3 · Geometry

No overlap, clipping, hidden arrowheads, edge-label collisions, or connector intrusion.

4 · Visual language

One meaning per channel, legend parity, theme consistency, and redundant cues.

5 · Accessibility

Contrast, keyboard, focus, target size, reduced motion, text alternative, and forced colors.

6 · Responsive behavior

320, 390, 768, 1024, and 1440 pixels, plus orientation and text zoom.

7 · Communication

Scope, main relationship, boundaries, risk, and intended action are evident.

Complexity repair order

  1. Remove unrelated relationships.
  2. Aggregate repeated nodes.
  3. Collapse lower-level groups.
  4. Replace repeated edges with aggregate edges.
  5. Move metadata into details.
  6. Split temporal and structural concerns.
  7. Generate coordinated views.
  8. Introduce semantic zoom and neighborhood isolation.
Durable reuse

Skill and memory design

The future diagram-architect skill should retain durable decision logic, renderer limitations, battle scars, validation rules, and accepted fixtures.

diagram-architect/
├── SKILL.md
├── CHANGELOG.md
├── references/
│   ├── diagram-question-taxonomy.md
│   ├── visual-language.md
│   ├── layout-router.md
│   ├── style-system.md
│   ├── token-resolution.md
│   ├── legend-generation.md
│   ├── responsive-diagrams.md
│   └── evaluation-framework.md
├── profiles/
│   ├── c4-architecture.md
│   ├── topology.md
│   ├── ontology.md
│   ├── lineage.md
│   ├── state-machine.md
│   ├── process-swimlane.md
│   └── timeline-gantt.md
├── battle-scars/
│   ├── connector-border-collision.md
│   ├── layout-before-measurement.md
│   ├── unreadable-fit-view.md
│   ├── mobile-desktop-shrink.md
│   ├── css-specificity-war.md
│   ├── legend-drift.md
│   ├── one-off-color-language.md
│   └── raw-literal-proliferation.md
└── evals/
    ├── routing.json
    ├── geometry.json
    ├── responsive.json
    ├── accessibility.json
    └── comprehension.json

Retrieval workflow

  1. Classify the diagram question.
  2. Retrieve one primary diagram profile.
  3. Retrieve one renderer profile.
  4. Retrieve five to nine relevant battle scars.
  5. Select one primary layout technique.
  6. Compile, audit, repair, and record reusable findings.
Store semantic and operational knowledge. Do not store one-off coordinates, arbitrary manual nudges, or unversioned renderer bugs as universal guidance.
Execution

Implementation roadmap

Phase 1 · Contracts

Canonical TypeScript model, view specification, visual-token schema, layout router, evaluation schema, and initial fixtures.

Phase 2 · Static compiler

ELK adapter, SVG renderer, Mermaid and LikeC4 export, text measurement, geometry audits, legend, and provenance.

Phase 3 · Interactive HTML

React Flow renderer, semantic zoom, selection, isolation, search, breadcrumbs, fit controls, and accessible list.

Phase 4 · Specialized graphs

Cytoscape.js, Sigma.js, OpenLineage ingestion, cloud inventory, runtime overlays, and stable diff layouts.

Phase 5 · Diagram intelligence

Question-to-view generation, automatic scope reduction, geometry repair, language linting, and comprehension testing.

Repository shape

diagram-system/
├── packages/
│   ├── model/
│   ├── ingestion/
│   ├── view-compiler/
│   ├── visual-language/
│   ├── layout/
│   ├── renderers/
│   ├── exporters/
│   └── evaluation/
├── skills/
│   └── diagram-architect/
├── fixtures/
│   ├── topology/
│   ├── ontology/
│   ├── lineage/
│   ├── sequence/
│   ├── state/
│   └── mobile/
└── apps/
    ├── diagram-studio/
    └── static-artifact-builder/
Red-team review

Material risks and controls

No universal renderer

React Flow, Mermaid, LikeC4, Cytoscape.js, Sigma.js, and SVG solve different problems.

Control: renderer portfolio behind one compiler.

Automatic layout lacks domain knowledge

Algorithms optimize geometry, not architecture meaning.

Control: semantic constraints and view contracts.

Large graphs still become hairballs

Rendering capacity does not equal comprehension.

Control: scoped subgraphs, aggregation, semantic zoom, and coordinated views.

Style systems can become opaque

CSS-like specificity and inline overrides make behavior hard to explain.

Control: fixed cascade layers and computed-style provenance.

Mobile fit is not mobile communication

Labels may technically fit while becoming unreadable.

Control: responsive recompilation and semantic zoom.

Metrics are incomplete proxies

Few crossings do not prove understanding.

Control: task-based comprehension evaluation.

Release rule: every visible difference must be traceable to a semantic style, a documented state, or an explicit exception.
Provenance

Primary sources

This guide consolidates the prior research and design synthesis. The following primary references informed the conclusions.

  1. LikeC4 documentation
  2. Structurizr documentation
  3. Mermaid diagram syntax and examples
  4. Mermaid theming and configuration
  5. React Flow API reference
  6. React Flow layout guidance
  7. React Flow accessibility guidance
  8. Cytoscape.js documentation
  9. Cytoscape.js layout guidance
  10. Sigma.js documentation
  11. AntV G6 layout overview
  12. AntV X6 overview
  13. ELK Layered reference
  14. Graphviz layout engines
  15. Kroki diagram rendering gateway
  16. yFiles for HTML
  17. GoJS documentation
  18. D2 classes
  19. Vega-Lite configuration
  20. Mapbox style expressions
  21. Design Tokens Community Group format
  22. Material Color Utilities
  23. D3 chromatic scales
  24. WCAG 2.2
  25. WCAG animation guidance
  26. OpenLineage object model
  27. Physics of Notations

Methodology

The research was organized by problem layer: modeling, view selection, visual language, style resolution, layout, rendering, interaction, accessibility, and validation. Tool capabilities were treated as complementary. Recommendations were then red-teamed against portability, mobile use, semantic clarity, renderer limitations, and long-term maintainability.