### Edge Styling Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example shows how to style edges with background color, gutter, and stroke color, and demonstrates edge labels with different alignments. ```nomnoml #background: #aaa #gutter: 1 #stroke: #eee8d5 #fill: #aaa [Left] left`association <-> right`association [Right] ``` -------------------------------- ### Edge Label Size Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example demonstrates how to apply labels to edges and control their appearance, including using a background color for the label. ```nomnoml #background: #aaa4 [a] - long label [c] [Long name] - [d] ``` -------------------------------- ### Graph Size Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example shows how to adjust graph size parameters like spacing, gutter, and padding to control the overall layout and visual density. ```nomnoml #spacing: 15 #gutter: 1 #padding: 3 #background: #aaa4 [a] - [foo] [foo] - [b] [a] - [bar] [bar] - [b] [a] - [b] ``` -------------------------------- ### Weightless Right Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example demonstrates a 'weightless' right-pointing association, indicated by '_>', which affects layout without adding visual weight. ```nomnoml #direction: right [a] _> [c] ``` -------------------------------- ### Ranker Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example utilizes the 'ranker' attribute to optimize the layout based on the longest path, influencing the arrangement of nodes. ```nomnoml #padding: 4 #ranker: longest-path [a] -> [b] [a] -> [c] [c] -> [d] ``` -------------------------------- ### Label Placement Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example demonstrates controlling label placement relative to edges using 'edgeMargin' and 'spacing' attributes, showing labels 'L' and 'R'. ```nomnoml #direction: right #spacing: 40 #edgeMargin: -5 [A] L - R [C1] [A] L - R [C2] [A] L - R [C3] [C1] L - R [B] [C2] L - R [B] [C3] L - R [B] ``` -------------------------------- ### Basic Diagram Syntax Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example shows the fundamental syntax for creating a simple diagram with nodes and associations. It uses default styling. ```nomnoml #.hello: underline stroke=teal fill=#ffa [Pirate| [a]--[b] [a]:>[c] ] [Marauder]<:--[Pirate] [Pirate] - 0..7[Arrrrrr] [db]->[Pirate] [db]->[rum] [Pirate]-> *[rum] ``` -------------------------------- ### Gravity Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example demonstrates the 'gravity' attribute, which influences the spacing and attraction between nodes in the diagram. ```nomnoml #padding: 4 #gravity: 2 [a] -> [b] [a] _> [c] [c] -> [d] ``` -------------------------------- ### Layout Bug Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This snippet shows an example related to a layout bug, adjusting gutter and spacing parameters. It demonstrates connections between nodes. ```nomnoml #gutter: 1 #spacing: 20 #padding: 5 [quux] [foo]-[bar] [foo]-[baz] [foo]-[quux] [quux]-[baz] ``` -------------------------------- ### Custom Styles Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example demonstrates applying custom styles to nodes, including fill color, font style (italic, bold), and visual shape (rhombus, ellipse). ```nomnoml #direction: right #.box: fill=pink italic bold visual=rhomb [box] #.blob: fill=limegreen dashed underline visual=ellipse [blob] #.quux: fill=pink italic bold visual=rhomb [quux] ``` -------------------------------- ### Association Sockets Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example demonstrates the use of 'sockets' in associations to represent different types of relationships like requests and dependencies, including ball-and-socket notation. ```nomnoml #direction: right [e] (-->o [req] [f] -->o [dep] [g] -(o [ball-socket]) ``` -------------------------------- ### Configure Diagram Directives Source: https://github.com/skanaar/nomnoml/blob/master/index.html Examples of how to set global diagram properties like font, spacing, and layout density using hash-prefixed directives. ```nomnoml #font: Times #fontSize: 8 #spacing: 12 #padding: 3 [Lorem ipsum]-[dolor sit amet] ``` -------------------------------- ### WebApp Bootstrap with CodeMirror Initialization Source: https://github.com/skanaar/nomnoml/blob/master/index.html This example shows how to initialize the CodeMirror editor within a WebApp bootstrap function. It highlights the integration of a code editor for user input or display within a web application context. ```javascript WebApp.bootstrap(CodeMirror) ``` -------------------------------- ### Associations Misc Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example shows miscellaneous association types, including a dashed line for 'hidden' relationships and a solid line to a 'note'. ```nomnoml #direction: right [i] -- [note] [j] -/- [hidden] ``` -------------------------------- ### Non-boxy Shapes Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example showcases the use of non-boxy shapes like choice, end, usecase, actor, and database, demonstrating different connection types. ```nomnoml [ choice|first|second] <:o [ end] [ usecase|row 2|row 3] -:> [ actor] [end] -:> [ database] [actor] -> [frame|[note]] ``` -------------------------------- ### Custom Direction Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example illustrates how to set a custom direction for the diagram layout, specifically 'right'. It also shows nesting within a node. ```nomnoml #direction: right #.right: direction=right [A] -> [B| [X]->[Y] ] ``` -------------------------------- ### Table Syntax Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This snippet demonstrates the syntax for creating tables within Nomnoml diagrams, including specifying column headers and cell content. It also sets the direction to right. ```nomnoml #direction: right [ Long table title| nuts | 89 || bolts | 18 ] [
shapes| number | 5 || capsule | [cell] | auto;row;break ] ``` -------------------------------- ### Text Heuristic Large Font Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example demonstrates text rendering with a specified font and font size, showcasing how Nomnoml handles larger text elements. ```nomnoml #zoom: 0.5 #font: Arial #fontSize: 20 #direction: right [iii] [🍌🐵] [MMM] [ABC] [漢字漢字] ``` -------------------------------- ### Text Heuristic Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This example showcases Nomnoml's text heuristic capabilities, including rendering emojis, non-Latin characters, and text with angle brackets. ```nomnoml #zoom: 0.5 #direction: right [iii] [🍌🐵] [MMM] [ABC] [漢字漢字] ``` -------------------------------- ### Create Interactive Diagrams with Click Handling (JavaScript) Source: https://context7.com/skanaar/nomnoml/llms.txt Provides a JavaScript example for creating interactive nomnoml diagrams. It uses `nomnoml.renderSvg` to generate SVG output and adds an event listener to handle clicks on diagram nodes. ```javascript const svg = nomnoml.renderSvg('[Clickable Node]->[Target]') document.getElementById('container').innerHTML = svg document.querySelector('svg').addEventListener('click', (e) => { const nodeName = e.target.closest('g[data-name]')?.attributes['data-name']?.value if (nodeName) { console.log('Clicked node:', nodeName) // Handle node click - navigate, show details, etc. } }) ``` -------------------------------- ### Built-in Styles Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This snippet demonstrates the use of built-in styles for various diagram elements like frames, notes, packages, and classes. It showcases how to apply predefined visual attributes. ```nomnoml #direction: right [frame|[ note]] [package|[ reference]] [class|items: Object[]] - [ hidden] [hidden] -- [
table|a|b] -- [abstract] [ package] <- [ frame] [ database|disk] <:- [ start] [start] -/- [ usecase] [end] -/- [ state] [state] - [ actor|subtitle] [lollipop] - [socket] [ choice] - [sync] [sync] - [ input] [ sender] <-+ [ receiver] [receiver] +-+ [transceiver] ``` -------------------------------- ### Apply Custom Classifier Styles Source: https://github.com/skanaar/nomnoml/blob/master/index.html Demonstrates how to define and apply custom styles to diagram elements using directives starting with a dot. ```nomnoml #.box: fill=#8f8 dashed [ GreenBox] ``` -------------------------------- ### Associations Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This snippet showcases various association types between nodes, including dependency, implementation, composition, and aggregation, using different arrow styles. ```nomnoml #direction: right [a] --> [depend] [b] -:> [impl] [c] +-> [compose] [d] o-> [aggr] ``` -------------------------------- ### Self Referential Example Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This snippet illustrates how to create a self-referential loop in a diagram, where a node connects back to itself. ```nomnoml [Banana] <-> self [Banana] ``` -------------------------------- ### Add Comments in nomnoml Source: https://context7.com/skanaar/nomnoml/llms.txt Explains how to add comments to nomnoml diagram source files. Comments must start at the beginning of a line and are ignored by the parser. ```nomnoml // This is a comment at the start of a line [Node] // This text is part of the node name, not a comment // Comments only work at line start [A]->[B] // [C]->[D] this entire line is commented out ``` -------------------------------- ### Nomnoml State Machine and Class Diagram Syntax Source: https://github.com/skanaar/nomnoml/blob/master/index.html This snippet demonstrates the Nomnoml syntax for creating state machine diagrams with states, choices, and transitions, as well as class diagram elements like attributes and methods. It also shows how to define relationships between classes and actors. ```nomnoml #.blob: fill=pink #import: blobby_styles [ Blobby] [start] -> [plunder] -> [more loot] -> [start] [more loot] no ->[e] [Pirate| [beard]--[parrot] [beard]:> [foul mouth] ] [
mischief| bawl | sing || yell | drink ] [Marauder]<:--[Pirate] [Pirate] - 0..7[mischief] [Jolly;Sailor] [sailor]->[Pirate] [sailor]->[rum] [Pirate]-> *[rum|tastiness: Int|swig()] ``` -------------------------------- ### compileFile Source: https://context7.com/skanaar/nomnoml/llms.txt Loads a nomnoml file from the filesystem and processes all #import directives recursively. ```APIDOC ## compileFile ### Description Loads a nomnoml file from the filesystem and processes all #import directives recursively. Essential for organizing large diagrams across multiple files in Node.js environments. ### Method Synchronous ### Parameters - **filename** (string) - Required - Path to the nomnoml file. - **maxDepth** (number) - Optional - Maximum recursion depth for imports to prevent infinite loops. ### Request Example nomnoml.compileFile('./diagrams/main.nomnoml', 5) ### Response - **source** (string) - The fully compiled nomnoml source code with all imports resolved. ``` -------------------------------- ### Define Basic UML Relationships Source: https://github.com/skanaar/nomnoml/blob/master/index.html Demonstrates how to define common UML relationships such as associations, dependencies, and compositions using nomnoml syntax. ```nomnoml [Car]->[Engine] [Car]+->0..*[RustPatch] [Car]o->[Manufacturer] [Car]<:-[Pickup] ``` -------------------------------- ### CLI Diagram Generation Source: https://github.com/skanaar/nomnoml/blob/master/README.md Explains how to use the nomnoml command-line interface to process a .noml file into an output format. ```bash npx nomnoml input-file.noml ``` -------------------------------- ### Configure Styling Directives in nomnoml Source: https://context7.com/skanaar/nomnoml/llms.txt Demonstrates how to use directives in nomnoml to control diagram appearance, including importing styles, setting layout direction, and customizing visual properties like arrow size, fonts, and colors. ```nomnoml // Import external files #import: shared-styles.noml // Layout direction #direction: down // top to bottom (default) #direction: right // left to right // Visual settings #arrowSize: 1 #bendSize: 0.3 #gutter: 5 #edgeMargin: 0 #gravity: 1 #edges: hard // or: rounded #background: transparent #fill: #eee8d5; #fdf6e3 #fillArrows: false #font: Calibri #fontSize: 12 #leading: 1.35 #lineWidth: 3 #padding: 8 #spacing: 40 #stroke: #33322E #title: MyDiagram #zoom: 1 #acyclicer: greedy #ranker: network-simplex // or: tight-tree, longest-path // Custom classifier styles #.box: fill=#8f8 dashed #.blob: visual=ellipse title=bold [GreenBox] [HideousBlob] // Style modifiers for custom classifiers: // fill=(css color), stroke=(css color) // align=center|left // direction=right|down // visual=actor|class|database|ellipse|end|frame|hidden|input|none|note|package|pipe|receiver|rhomb|roundrect|sender|start|sync|table|transceiver // title=left,italic,bold,underline,center // body=left,italic,bold,underline,center // dashed, empty ``` -------------------------------- ### Define Tables in Diagrams Source: https://github.com/skanaar/nomnoml/blob/master/index.html Shows the syntax for creating table-like structures within a node. ```nomnoml [
Fruits| Apples | 17 || Oranges | 4711 ] ``` -------------------------------- ### Define Class Attributes and Operations Source: https://github.com/skanaar/nomnoml/blob/master/index.html Shows how to define class structures including attributes and methods within the nomnoml syntax. ```nomnoml [Car|speed: Number;valves: Valve\[\]] [Engine||start()] ``` -------------------------------- ### processAsyncImports Source: https://context7.com/skanaar/nomnoml/llms.txt Processes #import directives using an asynchronous file loader. ```APIDOC ## processAsyncImports ### Description Processes #import directives using an asynchronous file loader. Ideal for loading diagram components from remote sources or async file systems. ### Method Asynchronous ### Parameters - **source** (string) - Required - The nomnoml source code. - **loader** (async function) - Required - An async function that returns a promise resolving to the file content. - **maxDepth** (number) - Optional - Maximum recursion depth. ### Request Example await nomnoml.processAsyncImports(mainSource, loadFromDisk, 10) ### Response - **result** (string) - The processed source code. ``` -------------------------------- ### Browser Script Include Source: https://context7.com/skanaar/nomnoml/llms.txt Includes Nomnoml in web pages via CDN for client-side diagram rendering. ```APIDOC ## Browser Script Include ### Description Include nomnoml in web pages via CDN. ### Method HTML Script Tag ### Endpoint N/A (CDN) ### Request Example ```html ``` ``` -------------------------------- ### Render SVG in Node.js Source: https://github.com/skanaar/nomnoml/blob/master/README.md Demonstrates how to use the nomnoml library in a Node.js environment to convert a diagram source string into an SVG string. ```javascript var nomnoml = require('nomnoml') var src = '[nomnoml] is -> [awesome]' console.log(nomnoml.renderSvg(src)) ``` -------------------------------- ### CLI for File Conversion (Bash) Source: https://context7.com/skanaar/nomnoml/llms.txt The command-line interface for Nomnoml allows direct conversion of .nomnoml files to SVG format. It supports the #import directive, enabling the rendering of modular diagram definitions from the terminal. ```bash # Basic conversion npx nomnoml diagram.noml # Output to specific file npx nomnoml diagram.noml output.svg # Example diagram file (diagram.noml): # #import: common-styles.noml # #direction: right # [Client]->[Server]->[Database] # Process multi-file project npx nomnoml main.noml architecture.svg ``` -------------------------------- ### Include nomnoml in HTML via CDN Source: https://context7.com/skanaar/nomnoml/llms.txt Demonstrates how to embed nomnoml diagrams in a web page by including the library via a CDN and using the `nomnoml.draw` function to render a diagram on a canvas element. ```html ``` -------------------------------- ### Render to HTML5 Canvas Source: https://github.com/skanaar/nomnoml/blob/master/README.md Illustrates how to render a nomnoml diagram directly onto an HTML5 canvas element using the browser-based library. ```html ``` -------------------------------- ### processImports Source: https://context7.com/skanaar/nomnoml/llms.txt Processes #import directives in source code using a custom synchronous file loader function. ```APIDOC ## processImports ### Description Processes #import directives in source code using a custom synchronous file loader function. Useful for custom build systems or virtual file systems. ### Method Synchronous ### Parameters - **source** (string) - Required - The nomnoml source code containing #import directives. - **loader** (function) - Required - A function that takes a filename and returns the file content. - **maxDepth** (number) - Optional - Maximum recursion depth. ### Request Example nomnoml.processImports(source, loadFile, 3) ### Response - **compiled** (string) - The processed source code. ``` -------------------------------- ### Interactive Diagram with Click Handling Source: https://context7.com/skanaar/nomnoml/llms.txt Creates clickable diagrams using SVG data attributes and event listeners. ```APIDOC ## Interactive Diagram with Click Handling ### Description Create clickable diagrams using SVG data attributes. ### Method JavaScript ### Endpoint N/A (Client-side rendering) ### Request Example ```javascript const svg = nomnoml.renderSvg('[Clickable Node]->[Target]') document.getElementById('container').innerHTML = svg document.querySelector('svg').addEventListener('click', (e) => { const nodeName = e.target.closest('g[data-name]')?.attributes['data-name']?.value if (nodeName) { console.log('Clicked node:', nodeName) // Handle node click - navigate, show details, etc. } }) ``` ``` -------------------------------- ### Server-Side SVG Generation Source: https://context7.com/skanaar/nomnoml/llms.txt Renders diagrams via URL parameters using a Vercel serverless function. ```APIDOC ## GET /api/image - Server-Side SVG Generation ### Description The included Vercel serverless function renders diagrams via URL parameters. ### Method GET ### Endpoint /api/image ### Query Parameters - **source** (string) - Required - The Nomnoml source code for the diagram. ### Request Example ```bash curl "https://your-domain.com/api/image?source=%5BUser%5D-%3E%5BSystem%5D" ``` ### Response #### Success Response (200) - **SVG Image Content** (string) - The generated SVG image. #### Response Example ```svg ... ``` ### Example with Styling ```bash curl "https://your-domain.com/api/image?source=%23fill%3A%20%23fdf6e3%0A%5BA%5D-%3E%5BB%5D" ``` ### Note The `source` parameter should be URL-encoded. For example, `[User]->[System]` becomes `%5BUser%5D-%3E%5BSystem%5D`. ``` -------------------------------- ### Compile File with Imports (Node.js) Source: https://context7.com/skanaar/nomnoml/llms.txt Loads a nomnoml file and recursively processes all #import directives. This is crucial for organizing large diagrams across multiple files in Node.js. It supports setting a maximum import depth to prevent infinite loops. ```javascript const nomnoml = require('nomnoml') // Given files: // styles.nomnoml: #fill: #fdf6e3 // main.nomnoml: #import: styles.nomnoml // [User]->[System] // Compile with imports resolved const source = nomnoml.compileFile('./diagrams/main.nomnoml') const svg = nomnoml.renderSvg(source) // Set maximum import depth to prevent infinite loops const sourceWithLimit = nomnoml.compileFile('./main.nomnoml', 5) // Typical file organization: // project/ // diagrams/ // common-styles.nomnoml -> #fill: #eee; #stroke: #333 // entities.nomnoml -> [User|...]; [Order|...] // main.nomnoml -> #import: common-styles.nomnoml // #import: entities.nomnoml // [User]->[Order] ``` -------------------------------- ### Process Imports with Custom Synchronous Loader (Node.js) Source: https://context7.com/skanaar/nomnoml/llms.txt Processes #import directives within source code using a provided custom synchronous file loader function. This is useful for integrating with custom build systems or virtual file systems where files are accessed synchronously. ```javascript const nomnoml = require('nomnoml') // Custom file loader (synchronous) const files = { 'styles.noml': '#fill: #fdf6e3 #stroke: #586e75', 'components.noml': '[UI Components|[Button];[Input]]' } function loadFile(filename) { return files[filename] || '' } const source = ` #import: styles.noml #import: components.noml [App]->[UI Components] ` const compiled = nomnoml.processImports(source, loadFile) const svg = nomnoml.renderSvg(compiled) // With max depth limit const limitedCompile = nomnoml.processImports(source, loadFile, 3) ``` -------------------------------- ### Configure Text Formatting in Styles Source: https://github.com/skanaar/nomnoml/blob/master/README.md This snippet shows how to apply text modifiers to the title and body of a classifier. It uses comma-separated lists to define alignment and font styles. ```nomnoml title=left,italic,bold body=center,italic,bold ``` -------------------------------- ### Server-Side SVG Generation with nomnoml API Source: https://context7.com/skanaar/nomnoml/llms.txt Shows how to use the nomnoml HTTP API to render diagrams as SVG images. The 'source' parameter accepts URL-encoded nomnoml code. ```bash # Render diagram via URL curl "https://your-domain.com/api/image?source=%5BUser%5D-%3E%5BSystem%5D" # URL-encoded source: [User]->[System] # Returns: SVG image content # Example with styling curl "https://your-domain.com/api/image?source=%23fill%3A%20%23fdf6e3%0A%5BA%5D-%3E%5BB%5D" # Decoded: #fill: #fdf6e3\n[A]->[B] ``` -------------------------------- ### Define Association Types in nomnoml Source: https://context7.com/skanaar/nomnoml/llms.txt Illustrates various ways to define associations between nodes in nomnoml diagrams, including basic, directed, bidirectional, and dependency relationships, as well as labeled associations. ```nomnoml // Basic associations [A] - [B] // association [A] -> [B] // directed association [A] <-> [B] // bidirectional association [A] --> [B] // dependency [A] <--> [B] // bidirectional dependency [A] -:> [B] // generalization (inheritance) [A] <:- [B] // reverse generalization [A] --:> [B] // implementation (interface) [A] <:-- [B] // reverse implementation [A] +- [B] // composition [A] +-> [B] // directed composition [A] o- [B] // aggregation [A] o-> [B] // directed aggregation [A] -o) [B] // ball and socket [A] o<-) [B] // ball and socket [A] ->o [B] // ball and socket [A] -- [B] // note connector [A] -/- [B] // hidden connector // Labeled associations [Customer] 1 -> * [Order] [User] owns -> [Account] [A] start label -> end label [B] ``` -------------------------------- ### Handle Interactive SVG Elements Source: https://github.com/skanaar/nomnoml/blob/master/README.md Shows how to attach click event listeners to SVG elements generated by nomnoml by querying the data-name attribute. ```javascript document.querySelector('svg').onclick = function (e) { console.log(e.target.closest('g[data-name]')?.attributes['data-name']) } ``` -------------------------------- ### Define and Apply Custom Classifier Styles Source: https://github.com/skanaar/nomnoml/blob/master/README.md This snippet demonstrates how to define custom styles using the dot directive and apply them to diagram elements. The styles control visual attributes like fill color, line style, and shape. ```nomnoml #.box: fill=#8f8 dashed #.blob: visual=ellipse title=bold [ GreenBox] [ HideousBlob] ``` -------------------------------- ### Parse Diagram Source to AST using nomnoml Source: https://context7.com/skanaar/nomnoml/llms.txt The `parse` function takes nomnoml source code and converts it into an Abstract Syntax Tree (AST). This AST can be used for programmatic analysis or custom rendering. The function returns an object containing the root node structure, directives, and computed configuration, allowing detailed inspection of the diagram's components and styles. ```javascript const nomnoml = require('nomnoml') // Parse simple diagram const result = nomnoml.parse('[User]->[System]') console.log(result.root.nodes) // [{ id: 'User', type: 'class', ... }, { id: 'System', type: 'class', ... }] console.log(result.root.assocs) // [{ start: 'User', end: 'System', type: '->', ... }] // Parse diagram with directives const parsed = nomnoml.parse(` #direction: right #background: blue [User]-->[DB] `) console.log(parsed.directives) // [{ key: 'direction', value: 'right' }, { key: 'background', value: 'blue' }] console.log(parsed.config.direction) // 'LR' console.log(parsed.config.background) // 'blue' // Parse nested nodes with compartments const classNode = nomnoml.parse('[Person|name;age|greet()]') console.log(classNode.root.nodes[0].parts) // [{ lines: ['Person'] }, { lines: ['name', 'age'] }, { lines: ['greet()'] }] // Typed nodes const typed = nomnoml.parse('[BaseClass]') console.log(typed.root.nodes[0].type) // 'abstract' ``` -------------------------------- ### Render Diagram to HTML Canvas using nomnoml Source: https://context7.com/skanaar/nomnoml/llms.txt The `draw` function renders nomnoml diagrams directly onto an HTML Canvas element. This is ideal for real-time rendering in web applications. It accepts the canvas element, the diagram source, and an optional scale factor for high-DPI displays. The function returns an object containing the parsed configuration. ```javascript // Browser usage const canvas = document.getElementById('diagram-canvas') const source = '[Component A]->[Component B]' // Basic rendering nomnoml.draw(canvas, source) // Render with scale factor for high-DPI displays nomnoml.draw(canvas, source, 2) // 2x scale // Complete web example const diagramSource = ` #font: Consolas #fontSize: 14 #lineWidth: 2 [MVC Pattern| [Controller] [Model] [View] [Controller] -> [Model] [Controller] -> [View] [Model] -> [View] ] ` const result = nomnoml.draw(canvas, diagramSource) // result.config contains the parsed configuration console.log(result.config.zoom, result.config.font) ``` -------------------------------- ### draw - Render Diagram to HTML Canvas Source: https://context7.com/skanaar/nomnoml/llms.txt Renders a nomnoml diagram directly to an HTML Canvas element. This is ideal for real-time rendering in web applications. ```APIDOC ## draw ### Description Renders a nomnoml diagram directly to an HTML Canvas element. Best for real-time rendering in web applications where you need bitmap output or canvas manipulation. ### Method `nomnoml.draw(canvas: HTMLCanvasElement, source: string, scale?: number): { config: object }` ### Parameters #### Arguments - **canvas** (HTMLCanvasElement) - Required - The HTML canvas element to draw on. - **source** (string) - Required - The nomnoml diagram source code. - **scale** (number) - Optional - A scale factor for high-DPI displays. ### Request Example ```javascript // Browser usage const canvas = document.getElementById('diagram-canvas') const source = '[Component A]->[Component B]' // Basic rendering nomnoml.draw(canvas, source) // Render with scale factor for high-DPI displays nomnoml.draw(canvas, source, 2) // 2x scale // Complete web example const diagramSource = "#font: Consolas\n#fontSize: 14\n#lineWidth: 2\n\n[MVC Pattern|\n [Controller]\n [Model]\n [View]\n [Controller] -> [Model]\n [Controller] -> [View]\n [Model] -> [View]\n]" const result = nomnoml.draw(canvas, diagramSource) console.log(result.config.zoom, result.config.font) ``` ### Response #### Success Response - **result** (object) - An object containing the parsed configuration. - **config** (object) - The parsed configuration object. #### Response Example ```json { "config": { "zoom": 1, "font": "Consolas" } } ``` ``` -------------------------------- ### Process Imports with Custom Asynchronous Loader Source: https://context7.com/skanaar/nomnoml/llms.txt Processes #import directives using an asynchronous file loader function. This is ideal for loading diagram components from remote sources or asynchronous file systems, making it suitable for modern web applications and Node.js environments using async operations. ```javascript const nomnoml = require('nomnoml') // Async file loader for remote or async sources async function loadRemoteFile(filename) { const response = await fetch(`/diagrams/${filename}`) return response.text() } const source = ` #import: remote-styles.noml [LocalComponent]->[RemoteComponent] ` // Process imports asynchronously const compiled = await nomnoml.processAsyncImports(source, loadRemoteFile) const svg = nomnoml.renderSvg(compiled) // With Node.js fs/promises const fs = require('fs/promises') async function loadFromDisk(filename) { return fs.readFile(`./diagrams/${filename}`, 'utf-8') } const result = await nomnoml.processAsyncImports(mainSource, loadFromDisk, 10) ``` -------------------------------- ### parse - Parse Diagram Source to AST Source: https://context7.com/skanaar/nomnoml/llms.txt Parses nomnoml source code into an Abstract Syntax Tree (AST) for programmatic analysis or custom rendering. ```APIDOC ## parse ### Description Parses nomnoml source code into an Abstract Syntax Tree (AST) for programmatic analysis or custom rendering. Returns the root node structure, directives, and computed configuration. ### Method `nomnoml.parse(source: string): { root: object, directives: Array, config: object }` ### Parameters #### Arguments - **source** (string) - Required - The nomnoml diagram source code. ### Request Example ```javascript const nomnoml = require('nomnoml') // Parse simple diagram const result = nomnoml.parse('[User]->[System]') console.log(result.root.nodes) // Parse diagram with directives const parsed = nomnoml.parse("#direction: right\n#background: blue\n[User]-->[DB]") console.log(parsed.directives) console.log(parsed.config.direction) // Parse nested nodes with compartments const classNode = nomnoml.parse('[Person|name;age|greet()]') console.log(classNode.root.nodes[0].parts) // Typed nodes const typed = nomnoml.parse('[BaseClass]') console.log(typed.root.nodes[0].type) ``` ### Response #### Success Response - **result** (object) - An object containing the parsed diagram structure. - **root** (object) - The root node of the AST representing the diagram. - **directives** (Array) - An array of parsed directives. - **config** (object) - The computed configuration object. #### Response Example ```json { "root": { "nodes": [ { "id": "User", "type": "class", ... }, { "id": "System", "type": "class", ... } ], "assocs": [ { "start": "User", "end": "System", "type": "->", ... } ] }, "directives": [ { "key": "direction", "value": "right" }, { "key": "background", "value": "blue" } ], "config": { "direction": "LR", "background": "blue" } } ``` ``` -------------------------------- ### renderSvg - Render Diagram to SVG String Source: https://context7.com/skanaar/nomnoml/llms.txt Renders a nomnoml diagram source code to an SVG string. This is useful for server-side rendering or when SVG output is needed for further processing. ```APIDOC ## renderSvg ### Description Renders a nomnoml diagram source code to an SVG string. This is the primary function for server-side rendering or when you need SVG output for further processing, embedding, or saving to files. ### Method `nomnoml.renderSvg(source: string, config?: object): string` ### Parameters #### Arguments - **source** (string) - Required - The nomnoml diagram source code. - **config** (object) - Optional - Configuration object for rendering options. ### Request Example ```javascript const nomnoml = require('nomnoml') // Basic usage - render a simple class diagram const source = '[Customer|name;email|login();logout()]' const svg = nomnoml.renderSvg(source) console.log(svg) // Render with styling directives const styledDiagram = "#direction: right\n#background: #282c34\n#stroke: #abb2bf\n#fill: #3e4451\n\n[User] -> [System]\n[System] -> [DB]\n" const styledSvg = nomnoml.renderSvg(styledDiagram) ``` ### Response #### Success Response - **svgString** (string) - The generated SVG markup as a string. #### Response Example ```xml ... ``` ``` -------------------------------- ### Mount Nomnoml Diagrams in DOM Source: https://github.com/skanaar/nomnoml/blob/master/test/index.html This function scans the document for script tags with the type 'text/vnd.nomnoml' nested within containers marked with 'nomnoml=canvas' or 'nomnoml=svg'. It then renders the diagram source into the parent element, handling potential rendering errors by adding a 'crashed' class to the container. ```javascript function mountNomnoml() { for (const el of document.querySelectorAll('[nomnoml=canvas]>script[type="text/vnd.nomnoml"]')) mountCanvas(el.parentElement, el.innerText) for (const el of document.querySelectorAll('[nomnoml=svg]>script[type="text/vnd.nomnoml"]')) mountSvg(el.parentElement, el.innerText) function mountCanvas(host, source){ try { nomnoml.draw(host.appendChild(document.createElement('canvas')), source) } catch (e) { host.parentElement.classList.add('crashed') } } function mountSvg(host, source){ var canvas = host.attributes['text-measure-canvas'] try { host.innerHTML = nomnoml.renderSvg(source, canvas ? document : undefined) } catch (e) { host.parentElement.classList.add('crashed') } } } mountNomnoml(); ``` -------------------------------- ### Render Diagram to SVG String using nomnoml Source: https://context7.com/skanaar/nomnoml/llms.txt The `renderSvg` function converts nomnoml diagram source code into an SVG string. It's suitable for server-side rendering or when SVG output is needed for further processing. Supports basic diagrams, relationships, and custom styling via directives. The SVG output includes data attributes for potential interactivity. ```javascript const nomnoml = require('nomnoml') // Basic usage - render a simple class diagram const source = '[Customer|name;email|login();logout()]' const svg = nomnoml.renderSvg(source) console.log(svg) // Output: ... // Render a relationship diagram const classDiagram = ` [User|+name: string;+email: string|+login();+logout()] [Order|+id: number;+total: number|+process()] [User] 1 -> * [Order] ` const svgOutput = nomnoml.renderSvg(classDiagram) // Render with styling directives const styledDiagram = ` #direction: right #background: #282c34 #stroke: #abb2bf #fill: #3e4451 [User] -> [System] [System] -> [DB] ` const styledSvg = nomnoml.renderSvg(styledDiagram) // Access node data attributes in SVG for interactivity // SVG output includes data-name attributes on shapes const interactiveSvg = nomnoml.renderSvg('[clickable]->[target]') // Use with: element.closest('g[data-name]')?.attributes['data-name'] ``` -------------------------------- ### Calculate Character Width Lookup Table Source: https://github.com/skanaar/nomnoml/blob/master/build/char-widths.html This script creates an off-screen canvas to measure the width of printable ASCII characters (32-126). It returns a JSON-encoded object mapping each character to its pixel width, which is useful for text layout calculations. ```javascript var ctx = document.createElement('canvas').getContext('2d'); ctx.font = 'normal 12pt Helvetica'; function range(start, end) { return [...(Array(end)).keys()].slice(start); } function toCharWidthMap(codes) { return codes .map(i => String.fromCharCode(i)) .map(c => [c, ctx.measureText(c).width]) .reduce((memo, e) => (memo[e[0]] = Math.ceil(e[1] + 0.2), memo), {}); } var lut = JSON.stringify(toCharWidthMap(range(32, 127))); document.querySelector('#output').innerText = lut; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.