### Parse TypeScript Code with TSDiagram Parser Source: https://context7.com/3rd/tsdiagram/llms.txt Demonstrates initializing the TSDiagram Parser with TypeScript code and accessing parsed interfaces, type aliases, and classes. It also shows how to update the source code and access the TypeScript checker. ```typescript import { Parser } from "./lib/parser/Parser"; // Initialize parser with TypeScript code const code = ` interface User { id: string; name: string; email: string; get fullName(): string; } interface Post { id: string; title: string; author: User; tags: string[]; } type Status = "draft" | "published" | "archived"; class BlogService { posts: Post[]; getPostsByAuthor(authorId: string): Post[] { return []; } } `; const parser = new Parser(code); // Access parsed interfaces const interfaces = parser.interfaces; // Returns: [{ name: "User", properties: [...], methods: [...], extends: [] }, // { name: "Post", properties: [...], methods: [...], extends: [] }] // Access parsed type aliases const typeAliases = parser.typeAliases; // Returns: [{ name: "Status", type: Type }] // Access parsed classes const classes = parser.classes; // Returns: [{ name: "BlogService", properties: [...], methods: [...], extends: undefined, implements: [] }] // Update source code dynamically parser.setSource(` interface NewInterface { value: number; } `); // Access TypeScript checker for advanced type operations const checker = parser.checker; const tsChecker = parser.tsChecker; // Underlying TypeScript compiler checker ``` -------------------------------- ### Manage User Options with React Hook and localStorage Persistence (TypeScript) Source: https://context7.com/3rd/tsdiagram/llms.txt This snippet demonstrates how to use the `useUserOptions` hook to manage user preferences for the editor, renderer, and UI settings. It utilizes localStorage for persistence, allowing settings to be saved and retrieved across sessions. The hook provides access to and methods for updating various options, such as editor themes, editing modes, renderer direction, and panel split directions. ```typescript import { optionsStore, useUserOptions, UserOptions } from "./stores/user-options"; // React hook usage function Settings() { const options = useUserOptions(); return (
{/* Editor settings */} {/* Renderer settings */} {/* Panel settings */}
); } // Options structure // { // general: { sidebarOpen: boolean }, // panels: { splitDirection: "horizontal" | "vertical" }, // editor: { theme: string, editingMode: "default" | "vim" }, // renderer: { // direction: "horizontal" | "vertical", // autoFitView: boolean, // theme: "light" | "dark", // enableMinimap: boolean // } // } ``` -------------------------------- ### Manage Document State with Documents Store Source: https://context7.com/3rd/tsdiagram/llms.txt The documents store provides functionality for managing document state, including creation, deletion, and persistence to localStorage. It also supports URL sharing through LZ-string compression. Dependencies include the documentsStore, useDocuments hook, and Document type from './stores/documents'. It allows direct state access and provides a React hook for component integration. ```typescript import { documentsStore, useDocuments, Document } from "./stores/documents"; // Access store state directly const { currentDocument, documents } = documentsStore.state; // React hook usage function DocumentList() { const docs = useDocuments(); return (

Current: {docs.currentDocument.title}

{docs.documents.map((doc: Document) => (
{doc.title}
))}
); } // Document operations documentsStore.state.create(); // Create new document documentsStore.state.setCurrentDocumentTitle("My Diagram"); documentsStore.state.setCurrentDocumentSource(` interface MyType { value: string; } `); documentsStore.state.save(); // Persist to localStorage and URL // Document structure // { // id: string, // title: string, // source: string, // lastModified: number // } // URL sharing - state is compressed and stored in URL hash // Example: https://tsdiagram.com/#/N4IgJg9gxgrgtgUwHYBcDO... // This allows sharing diagrams via URL ``` -------------------------------- ### Manage Diagram Interaction State with Graph Store Hooks (TypeScript) Source: https://context7.com/3rd/tsdiagram/llms.txt This snippet illustrates the use of the `graphStore` and associated React hooks for managing diagram interaction states, such as node highlighting and edge decoration. It shows how to directly manipulate the store's state for hovered nodes and provides hooks like `useIsNodeHighlighted` and `useIsEdgeDecorated` to conditionally apply styles based on the hover state. ```typescript import { graphStore, useGraphStore, useIsNodeHighlighted, useIsEdgeDecorated } from "./stores/graph"; import { Model } from "./lib/parser/ModelParser"; import { EdgeProps, Node } from "reactflow"; // Set hovered node directly graphStore.state.hoveredNode = someNode; graphStore.state.hoveredNode = null; // Clear hover // React hook for checking if a node should be highlighted function ModelNodeComponent({ model }: { model: Model }) { const isHighlighted = useIsNodeHighlighted(model); // Returns true if: // - This node is currently hovered // - This node is a dependency of the hovered node // - This node is a dependant of the hovered node return (
{model.name}
); } // React hook for edge decoration based on hover state function CustomEdgeComponent(props: EdgeProps) { const { highlighted, faded } = useIsEdgeDecorated(props); // highlighted: true if edge connects to hovered node // faded: true if another node is hovered but this edge doesn't connect to it return ( ); } ``` -------------------------------- ### Create TypeScript Editor with Monaco Source: https://context7.com/3rd/tsdiagram/llms.txt The Editor component utilizes the Monaco editor to provide a rich TypeScript editing experience. It includes features like syntax highlighting, optional Vim mode, and automatic saving to a document store. It's designed to be integrated into a layout alongside the diagram renderer. ```typescript import { Editor } from "./components/Editor"; // The Editor component is a Monaco editor pre-configured for TypeScript // with the following features: // - TypeScript language support with latest ES target // - Syntax highlighting with configurable themes // - Optional Vim mode editing // - Auto-save to documents store // Editor is typically used within the main App layout: function App() { return (
{/* Left panel: code editor */} {/* Right panel: diagram */}
); } // Editor options (internal configuration) const editorOptions = { minimap: { enabled: false }, renderLineHighlight: "none", fontSize: 15, scrollbar: { vertical: "auto", horizontal: "auto" } }; // The editor automatically syncs with documentsStore: // - Reads from: documentsStore.state.currentDocument.source // - Writes to: documentsStore.state.setCurrentDocumentSource(value) ``` -------------------------------- ### TypeScript Interfaces for Diagram Generation Source: https://context7.com/3rd/tsdiagram/llms.txt Defines various TypeScript interfaces and classes used for generating diagrams. Includes interfaces for nodes, tasks, schedules, sessions, repositories, and serializable entities, along with a base class and a user class. ```typescript // Interfaces with properties and methods interface Node { id: string; path: string; source: string; get meta(): Record; get title(): string; get links(): Node[]; get backlinks(): Node[]; get tasks(): Task[]; } // Interfaces with status unions and nested types interface Task { title: string; children: Task[]; status: "default" | "active" | "done" | "cancelled"; schedule: TaskSchedule; sessions: TaskSession[]; get isInProgress(): boolean; } // Simple interfaces with computed properties interface TaskSchedule { start: Date; end: Date; get duration(): number; get isCurrent(): boolean; } interface TaskSession { start: Date; end?: Date; // Optional property get duration(): number; get isCurrent(): boolean; } // Classes with constructors and methods class Wiki { rootPath: string; constructor(rootPath: string) { this.rootPath = rootPath; } getNodes(): Node[] { return []; } } // Type aliases type Status = "pending" | "active" | "completed"; type UserID = string; type Handler = (item: T) => void; // Generic interfaces interface Repository { items: T[]; add(item: T): void; remove(id: string): boolean; find(predicate: (item: T) => boolean): T | undefined; } // Class extending and implementing interface Serializable { toJSON(): string; } class BaseEntity { id: string; createdAt: Date; } class User extends BaseEntity implements Serializable { name: string; email: string; toJSON(): string { return JSON.stringify(this); } } ``` -------------------------------- ### Render Interactive Node Graph with React Flow Source: https://context7.com/3rd/tsdiagram/llms.txt The Renderer component displays parsed models as an interactive node graph using React Flow and ELK for automatic layout. It supports features like manual repositioning, auto-fit view, orientation toggles, fullscreen mode, and minimap navigation. ```typescript import { Renderer, RendererProps } from "./components/Renderer/Renderer"; import { ModelParser } from "./lib/parser/ModelParser"; import { ReactFlowProvider } from "reactflow"; function DiagramView() { const code = "\n interface User { id: string; name: string; }\n interface Post { id: string; author: User; }\n "; const parser = new ModelParser(code); const models = parser.getModels(); return ( ); } // Renderer features: // - Automatic layout using ELK algorithm // - Manual node repositioning (persisted per session) // - Auto-fit view toggle // - Horizontal/vertical orientation toggle // - Fullscreen mode // - Node hover highlighting with dependency visualization // - MiniMap navigation // - Zoom and pan controls // Internal layout options (ELK configuration) const elkOptions = { "elk.algorithm": "layered", "elk.direction": "RIGHT", // or "DOWN" for vertical "elk.edgeRouting": "ORTHOGONAL", "elk.layered.nodePlacement.strategy": "LINEAR_SEGMENTS", "elk.layered.spacing.nodeNodeBetweenLayers": "50", "elk.spacing.nodeNode": "50" }; ``` -------------------------------- ### Parse TypeScript to Diagram Models with ModelParser Source: https://context7.com/3rd/tsdiagram/llms.txt The ModelParser extends the base Parser to convert parsed TypeScript code into a structured model format suitable for visualization. It computes dependencies and schema fields from interfaces, types, and classes. Dependencies include the ModelParser and Model types from './lib/parser/ModelParser'. It takes TypeScript code as input and outputs an array of Model objects. ```typescript import { ModelParser, Model } from "./lib/parser/ModelParser"; const code = ` interface Task { id: string; title: string; status: TaskStatus; assignee?: User; subtasks: Task[]; } interface User { id: string; name: string; tasks: Task[]; } type TaskStatus = "pending" | "in_progress" | "completed"; class TaskManager { tasks: Task[]; users: User[]; createTask(title: string, assignee: User): Task { return {} as Task; } getTasksByUser(userId: string): Task[] { return []; } } `; const modelParser = new ModelParser(code); const models: Model[] = modelParser.getModels(); // Each model contains: // - id: unique identifier // - name: type/interface/class name // - type: "interface" | "typeAlias" | "class" // - schema: array of fields with their types // - dependencies: models this type references // - dependants: models that reference this type // - arguments: generic type parameters // Example model structure for Task interface: // { // id: "Task", // name: "Task", // type: "interface", // schema: [ // { name: "id", type: "string", optional: false }, // { name: "title", type: "string", optional: false }, // { name: "status", type: TaskStatusModel, optional: false }, // { name: "assignee", type: UserModel, optional: true }, // { name: "subtasks", type: "array", elementType: TaskModel, optional: false } // ], // dependencies: [TaskStatusModel, UserModel, TaskModel], // dependants: [UserModel, TaskManagerModel], // extends: [], // arguments: [] // } // Schema field types: // - DefaultSchemaField: { name, type: Model | string, optional } // - ArraySchemaField: { name, type: "array", elementType: Model | string, optional } // - GenericSchemaField: { name, type: "generic", genericName, arguments: (Model | string)[], optional } // - FunctionSchemaField: { name, type: "function", arguments: [], returnType: Model | string, optional } // - UnionSchemaField: { name, type: "union", types: (Model | string)[], optional } // Type guards for schema fields import { isArraySchemaField, isGenericSchemaField, isFunctionSchemaField, isUnionSchemaField, isDefaultSchemaField } from "./lib/parser/ModelParser"; for (const model of models) { for (const field of model.schema) { if (isArraySchemaField(field)) { console.log(`${field.name} is array of ${field.elementType}`); } else if (isFunctionSchemaField(field)) { console.log(`${field.name} is function returning ${field.returnType}`); } else if (isUnionSchemaField(field)) { console.log(`${field.name} is union of ${field.types.join(" | ")}`); } } } ``` -------------------------------- ### Export Diagrams to SVG Format Source: https://context7.com/3rd/tsdiagram/llms.txt Utility functions for exporting diagrams rendered with React Flow as SVG images. This process involves calculating node bounds, generating a transform to fit the content, and then using a library to convert the DOM to an SVG string for download or clipboard. ```typescript import { exportReactFlowToSVG, downloadSVG, copySVG } from "./utils/svg-export"; import { getNodesBounds, getTransformForBounds, useReactFlow } from "reactflow"; function ExportButton() { const { getNodes } = useReactFlow(); const handleExport = async () => { // Calculate bounds of all nodes const nodesBounds = getNodesBounds(getNodes()); const width = nodesBounds.width; const height = nodesBounds.height; // Get transform to fit content const transform = getTransformForBounds(nodesBounds, width, height, 0.5, 2); const cssTransform = `translate(${transform[0]}px, ${transform[1]}px) scale(${transform[2]})`; // Export to SVG string const svgString = await exportReactFlowToSVG(width, height, cssTransform); // Download as file await downloadSVG(svgString, "my-diagram.svg"); // Or copy to clipboard await copySVG(svgString); }; return ; } // Export process: // 1. Creates hidden iframe with diagram clone // 2. Applies styles (main CSS + React Flow CSS) // 3. Converts DOM to SVG using dom-to-svg library // 4. Returns SVG string for download or clipboard ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.