ng-diagram

repository·main·Indexed 20 days ago

https://github.com/synergycodes/ng-diagram

A library for building interactive flow diagrams in Angular. It provides components, directives, and a middleware system to manage diagram state and rendering.

Tokens
134.2K
Snippets
425
Records
685
Agent score
68%

What's inside ng-diagram

  1. What is ngDiagram?

    main

    ngDiagram is an Angular-based diagramming library designed for building interactive diagram interfaces. It is built on Angular signals for reactive state management and provides a complete toolkit for creating complex visualizations like flow diagrams, node-based editors, network topologies, and circuit schematics.

    Key architectural features include:

    • Service Layer: Injectable Angular services for managing models, selection, viewport, groups, and clipboard.
    • Command System: Supports atomic operations with built-in undo/redo functionality.
    • Middleware & Plugins: An extensible architecture for injecting custom business logic and behaviors.
    • Theming: A design system driven by CSS variables.
    • Type Safety: Full TypeScript support using generic templates.
  2. Overview of ngDiagram features

    main

    ngDiagram is a powerful Angular library designed for creating interactive diagrams, node-based editors, and visual programming interfaces. Key features include:

    • Built for Angular: Native Angular components with full TypeScript support and reactive state management.
    • Highly Customizable: Support for creating custom nodes, edges, and controls.
    • Performance Focused: Optimized rendering and efficient state updates.
    • Feature Rich: Out-of-the-box support for selection, resizing, rotation, ports, and groups.
  3. Explore the ng-diagram API surface

    main

    The ng-diagram API is organized into several functional categories to help you build and customize diagramming interfaces in Angular:

    • Components: UI building blocks like NgDiagramComponent (the main container), NgDiagramMinimapComponent, and various node/edge decoration components.
    • Directives: Behavior modifiers such as NgDiagramNodeSelectedDirective for handling selection states.
    • Services: Core logic providers including NgDiagramService for general interaction, NgDiagramModelService for data management, and NgDiagramSelectionService for managing selected elements.
    • Types: Comprehensive type definitions covering Configuration (e.g., NgDiagramConfig), Events (e.g., NodeDragEndedEvent), Model (e.g., Node, Edge), Geometry (e.g., Point, Rect), and Middleware.
    • Utilities: Helper functions for setup, such as provideNgDiagram() for dependency injection and initializeModel() for data loading.
  4. View the ng-diagram roadmap and implementation status

    main

    The ng-diagram roadmap tracks the development progress of the library, including completed features, work in progress, and upcoming tasks.

    Completed Features (v1.0):

    • Core Stability: Stable v1.0 release and Angular 18 support.
    • Navigation & UI: Minimap (overview navigation widget), Box Selection (rectangular multi-select tool), and Grid Background (configurable grid pattern).
    • Interaction: Touch & Trackpad input support, Shortcut Manager (centralized keyboard shortcuts), and Direct Node Connections (connecting nodes without explicit ports).
    • Diagram Components: Port Labels, Default Edge Labels, and Lookup Helpers (e.g., getConnectedEdges).
    • Integrations: MCP Server (Model Context Protocol for AI assistants).
    • Events: Additional hooks such as model loaded and object removed.

    In Progress:

    • Templates: Electrical and AV (Audio-Video) demo templates.
    • API Enhancements: Invalidate Measurements API to programmatically invalidate node/edge measurements.
    • Feature Development: Edge Reshaping (interactive editing of edge paths and waypoints).

    Upcoming:

    • Collecting user feedback to shape future development.
  5. Use NgDiagramMinimapComponent for a bird's-eye view

    main

    The NgDiagramMinimapComponent provides a small, interactive overview of your diagram. It renders all nodes as small rectangles and includes a viewport rectangle that indicates the currently visible area of the main diagram.

    Key features:

    • Reactive Updates: The minimap automatically updates when the diagram viewport changes (panning/zooming) or when nodes are added, removed, or updated.
    • Navigation: Users can click and drag directly on the minimap to pan the main diagram viewport to different areas.
  6. Overview of ngDiagram architecture layers

    main

    ngDiagram is organized into several distinct layers that separate concerns:

    • Components Layer: User-facing Angular components that render the diagram and handle interactions (e.g., ng-diagram, ng-diagram-port, ng-diagram-base-node-template).
    • Service Layer: Specialized services providing control over state and functionality (e.g., NgDiagramService for middleware/routing, NgDiagramModelService for data access, NgDiagramSelectionService for selection state).
    • Event Layer: Captures user interactions and translates them into commands via NgDiagramComponent outputs.
    • Command System: Provides structured instructions (e.g., moveNode, addEdge) that act as the bridge between events and model updates.
    • Middleware System: A plugin architecture that intercepts commands for validation, transformation, or side effects.
    • Data Model: The foundation storing the state of Nodes, Edges, and Metadata using Angular signals for reactivity.
  7. Understand the ng-diagram architectural separation

    main

    The ng-diagram project is organized into two distinct layers to ensure that business logic remains decoupled from the UI framework. Developers must respect the boundary between the core and lib modules when contributing or extending the project:

    1. Core Module (src/core/): Contains framework-agnostic business logic and algorithms. It is designed to be pure and independent of any UI framework.
    2. Lib Module (src/lib/): Contains Angular-specific implementations, including components, services, and directives.

    Dependency Rules:

    • Core can only import from other files within the core directory. It is strictly forbidden from importing from lib or any @angular/** modules.
    • Lib can import from core and Angular modules, but must avoid circular dependencies within the lib folder.
  8. Integrate external layout libraries like ELK.js

    main

    You can integrate external layout engines (such as ELK.js) to handle complex node positioning and edge routing.

    When using an external library:

    1. The library calculates and assigns a position to each node.
    2. The library generates edge paths automatically.
    3. To ensure the diagram respects these calculated paths, set the edges to manual mode using RoutingMode.manual. This prevents the built-in engine from overriding the custom layout points provided by the external library.

    If a user manually moves a node, you should reset the edges back to auto mode to allow the built-in routing to recalculate based on the new positions.

    // Conceptual workflow for external layout integration
    
    // 1. Run external layout (e.g., ELK.js)
    const layoutResult = await elk.layout(nodes, edges);
    
    // 2. Update nodes with new positions
    modelAdapter.updateNodes(layoutResult.nodes);
    
    // 3. Set edges to manual mode to preserve external paths
    modelAdapter.updateEdges(edges.map(edge => ({
      ...edge,
      routingMode: RoutingMode.manual
    })));
    
    // 4. Handle manual user movement
    // Listen for selectionMoved to detect when a user drags a node
    // and reset routing to auto
    if (event.type === 'selectionMoved') {
      modelAdapter.updateEdges(edges.map(edge => ({
        ...edge,
        routingMode: RoutingMode.auto
      })));
    }
  9. Customize port content and appearance

    main

    In ng-diagram, ports are not limited to simple circles. You can provide any custom content inside a port, including text, images, SVGs, or full Angular components.

    When you provide custom content, the default port styling is disabled, allowing the port to adapt to the size and shape of your content. This gives you full control over the visual representation of connection points.

    To style ports, you can use:

    • CSS classes
    • Inline styles
    • Overriding CSS variables used for port styling
  10. Manage Edge Z-Index and positioning

    main

    Edges in ngDiagram follow specific rules for layering:

    • Default Behavior: If an edge has no explicit zOrder, its z-index is derived from its connected nodes using max(source, target). This ensures edges automatically follow the nodes they connect.
    • Explicit Z-Order: Setting a zOrder on an edge overrides the default, but the system still adds connected node elevation if those nodes are selected.
    • Edges Above Nodes: To ensure edges are always drawn on top of the nodes they connect, set the edgesAboveConnectedNodes configuration option to true. This adds +1 to every edge's z-index relative to its connected nodes.
  11. Understand RotationActionState

    main

    The RotationActionState object is used to track the state of a node rotation operation currently in progress. It captures the necessary geometric and identity information to calculate how much a node has rotated relative to its starting position and its original orientation.

    This state is typically used internally or by custom interaction handlers to manage the transformation of nodes during a drag or rotation gesture.