oxdraw

repository·master·Indexed 25 days ago

https://github.com/rohanadwankar/oxdraw

A library, CLI, and web view for declarative diagramming that bridges code-generated diagrams (Mermaid syntax) and manual tools. It allows users to render Mermaid files to SVG/PNG, visually fine-tune diagrams in a web editor with changes persisted back to source code, and generate AI-powered codemaps and 'Codedowns' (Markdown with clickable code mappings) from a codebase.

Tokens
15.9K
Snippets
29
Records
93
Agent score
80%

What's inside oxdraw

  1. Manage UI Theming and Panel Resizing

    master

    The Oxdraw Editor provides interactive controls for visual customization:

    Theme Toggling

    Use the toggleTheme function to switch between light and dark modes. This updates the theme state and sets the data-theme attribute on document.body, triggering corresponding CSS rules.

    Panel Resizing

    Users can resize the CodePanel and adjacent panels by dragging. This is handled by:

    1. Initiating a resize via startLeftPanelResizing or startRightPanelResizing.
    2. Activating global mouse listeners (handleMouseMove, handleMouseUp).
    3. Updating leftPanelWidth or rightPanelWidth states to dynamically adjust layout widths.
  2. Understand the Oxdraw Editor Frontend Data Flow

    master

    The Oxdraw Editor frontend follows a structured data flow between the UI components and the backend API to manage diagrams, source code, and images.

    1. Initialization

    • The Home component initializes state variables.
    • An initial API call (e.g., fetchDiagram) retrieves diagram data and source code.
    • This data is passed to DiagramCanvas (for visual rendering) and CodePanel (for source editing).

    2. Diagram Editing (Visual)

    • Interactions in DiagramCanvas (moving nodes, resizing, styling) trigger callbacks in the Home component.
    • Home updates its internal diagram state.
    • Changes are persisted to the backend using API functions like updateLayout, updateStyle, deleteNode, or deleteEdge.

    3. Source Code Editing

    • Users edit code in the CodePanel, which updates a sourceDraft state.
    • An auto-save mechanism (using saveTimer and lastSubmittedSource) or manual save triggers the updateSource API call.
    • Successful updates trigger a re-render of the DiagramCanvas via updated DiagramData from the backend.

    4. Image Handling

    • Selected images are processed client-side using utilities like ensureImageWithinLimit, resizeImageToLimit, loadImageFromBlob, and blobToBase64 to ensure size compliance and Base64 encoding.
    • The resulting Base64 string is sent to the backend via updateNodeImage.

    5. Code Mapping & Markdown

    • The codeMapMode and codedownMode states control feature visibility.
    • API calls like fetchCodeMapMapping or fetchCodeMapFile retrieve code locations or markdown content.
    • The openInEditor API allows opening referenced files in an external local editor.
  3. Understand the Oxdraw Editor Frontend Architecture

    master

    The Oxdraw Editor frontend is a client-intensive Next.js and React application. It uses a component-based architecture where a central Home component manages global state and orchestrates interactions between specialized sub-components and a backend API.

    Key Architectural Traits:

    • Client-Side Rich Application: Relies heavily on React hooks for state management and UI interactions.
    • API-Driven: All data persistence and complex diagram processing (parsing source, generating diagram data) are handled via a backend API.
    • Modular Components: Separation of concerns into dedicated components like DiagramCanvas, CodePanel, and MarkdownViewer.
    • Responsive UI: Supports resizable panels and theme switching.
  4. Use a local OpenAI-compatible inference server

    master
    If you are running a local inference server (e.g., via cgpu), ensure it is serving responses at http://localhost:8080/v1/responses. The response format must be compatible with the OpenAI responses API.
  5. Core Application Components and State Management

    master

    The Home component (found in page.tsx) acts as the central orchestrator. It manages the application's interactive state using React hooks and coordinates data flow.

    State Managed by Home:

    • Diagram State: diagram (DiagramData | null), loading, error, saving.
    • Source Code State: source, sourceDraft, sourceSaving, sourceError.
    • Selection State: selectedNodeId, selectedEdgeId.
    • UI/Layout State: theme ('light' | 'dark'), leftPanelWidth, rightPanelWidth, isLeftPanelResizing, isRightPanelResizing, isLeftPanelCollapsed, isRightPanelCollapsed.
    • Feature Modes: codeMapMode, codedownMode.
    • Other: markdownContent, selectedFile, highlightedLines.

    Persistence and Side Effects:

    • useRef: Used for mutable values that don't trigger re-renders, such as saveTimer (for auto-saving) and lastSubmittedSource.
    • useEffect: Manages side effects like applying the data-theme attribute to the document body and handling dynamic panel resizing logic.
  6. Generate a Codedown (Markdown + Code Mappings)

    master

    Codedowns are Markdown documents with embedded metadata that make headings, paragraphs, and inline code clickable, allowing them to jump directly to the relevant code in your editor.

    Use --codedown <PATH> to generate them. You can specify a style using --codedown-style (architecture, tutorial, or api) and provide additional context via --prompt.

    Common usage patterns:

    • Launch viewer immediately:

      oxdraw --codedown ./ --gemini YOUR_API_KEY
    • Generate with specific style and instructions:

      oxdraw --codedown ./ --codedown-style architecture --gemini YOUR_API_KEY --prompt "Focus on auth + request lifecycle"
    • Save to a specific file:

      oxdraw --codedown ./ --codedown-style api --gemini YOUR_API_KEY --output docs/architecture.md
    • Print to stdout:

      oxdraw --codedown ./ --gemini YOUR_API_KEY --output -
    oxdraw --codedown ./ --gemini YOUR_API_KEY
  7. Generate a codebase codemap

    master

    A codemap is a visual diagram where nodes are linked to specific code segments in your repository. You can generate this using AI (e.g., Gemini) or via a deterministic static analysis approach if AI access is not configured.

    Using AI:

    oxdraw --code-map ./ --gemini YOUR_API_KEY

    Using static analysis (no AI):

    oxdraw --code-map ./src/diagram.rs --no-ai --output test.png
  8. Set up Google AI Studio for free LLM access

    master

    You can use Google AI Studio to obtain a free API key for LLM access in oxdraw.

    1. Sign in to Google AI Studio with your Google account.
    2. Click on "Create API Key" and "Create Project".
    3. Copy the generated API key.
    4. Use the key with the --gemini flag when running the code map generation command.
    oxdraw --code-map ./ --gemini YOUR_API_KEY
  9. Augment an existing Markdown file with code mappings

    master

    If you have an existing .md file and want to add clickable code mappings to it, use the --augment-markdown command. This requires a --repo-path to locate the code definitions.

    Standard usage (outputs <stem>-mapped.md):

    oxdraw --augment-markdown docs/notes.md --repo-path . --gemini YOUR_API_KEY

    Explicit output path:

    oxdraw --augment-markdown docs/notes.md --repo-path . --gemini YOUR_API_KEY --output docs/notes.codedown.md
  10. How edge route computation works

    master

    The compute_routes method generates paths for all edges in the diagram. The process follows this priority:

    1. Manual Overrides: If an edge ID is found in the provided LayoutOverrides, its path is set directly to the provided points.
    2. Bidirectional Routing: For pairs of edges connecting the same two nodes in opposite directions, the engine attempts to resolve_bidirectional_pair to create distinct, non-overlapping paths using offsets and stubs.
    3. Automatic Collision Avoidance: For standard edges, the engine calculates a route and then checks for collisions with:
      • Other nodes (route_collides_with_nodes)
      • Edge labels (label_collides_with_nodes)
      • Existing routes (count_route_intersections)
    4. Detour Logic: If a collision is detected, the engine attempts to adjust_edge_for_conflicts (using orthogonal or axis-aligned detours) or detour_route_for_collisions (up to 3 attempts) to find a clear path.

    Routes are finally trimmed to the node boundaries using trim_route_endpoints.

  11. Define node shapes using specialized syntax

    master

    Oxdraw supports a specialized syntax for defining node shapes within a diagram. You can specify a node's shape by wrapping its label in specific delimiters. If no shape is specified, the node defaults to a Rectangle.

    Supported Shapes and Syntax

    ShapeSyntaxExample
    Double Circle(((label)))stop(((Stop)))
    Circle((label))((Circle))
    Subroutine[[label]]sub[[Subroutine]]
    Cylinder[(label)]db[(Database)]
    Hexagon{{label}}hex{{Prep}}
    Parallelogram[/label/]lean[/Tilt/]
    Parallelogram Alt[\label\]leanAlt[\Lean\]
    Trapezoid[/label\]prio[/Priority\]
    Trapezoid Alt[\label/]manual[\Manual/]
    Stadium(label) or ([label])term([Terminal])
    Rectangle[label][Rectangle]
    Diamond{label}{Diamond}
    Asymmetric>label]asym>Skewed]

    Note: Labels can be enclosed in double quotes (e.g., A["Label"]) to handle special characters.

    // Example of node definitions in a diagram
    sub[[Subroutine]]
    db[(Database)]
    hex{{Prep}}
    stop(((Stop)))
    lean[/Tilt/]
    leanAlt[\Lean\]
    prio[/Priority\]
    manual[\Manual/]
    asym>Skewed]
    term([Terminal])