### Install Rete.js with Rete Kit Source: https://github.com/retejs/rete/blob/main/README.md Use the Rete Kit command-line tool to quickly set up a new Rete.js application, allowing selection of frontend frameworks and features. ```Bash npx rete-kit app ``` -------------------------------- ### Install d3-node-editor via CDN Source: https://github.com/retejs/rete/wiki/Home Includes the d3-node-editor library and its dependencies (alight, d3) using script and link tags for direct browser inclusion. This is useful for quick prototyping or projects not using a build system. ```html ``` -------------------------------- ### Install d3-node-editor via npm Source: https://github.com/retejs/rete/wiki/Home Installs the d3-node-editor package from npm into your project. This is the recommended method for projects using a build system like Webpack or Parcel. ```bash npm install d3-node-editor ``` -------------------------------- ### Rete.js Worker Function Example Source: https://github.com/retejs/rete/wiki/Nodes An example of a worker function that processes inputs, performs calculations, updates a control's value, and sets the node's output. ```javascript worker: function(node, inputs, outputs) { var sum = inputs[0][0] + inputs[1][0]; editor.nodes.find(n => n.id == node.id).controls[0].setValue(sum); outputs[0] = sum; } ``` -------------------------------- ### Apply Custom Node and Socket Styles (CSS) Source: https://github.com/retejs/rete/wiki/Customization Provides CSS examples for styling Rete.js nodes, sockets, and connections. It shows how to target elements using specific class names derived from socket IDs or node titles for visual customization. ```css .socket.id-of-socket{ background: #96b38a } .node.title-of-node{ background: #96b38a } .connection.input-id-of-socket{ stroke: red !important } .connection.output-id-of-socket{ stroke: red !important } ``` -------------------------------- ### Import d3-node-editor in JavaScript Source: https://github.com/retejs/rete/wiki/Home Demonstrates how to import the d3-node-editor library into your JavaScript code after installation. It's typically imported as a namespace for easy access to its classes and functions. ```js import * as D3NE from "d3-node-editor"; ``` -------------------------------- ### Define a Rete.js Component with Builder and Worker Source: https://github.com/retejs/rete/wiki/Components Demonstrates the basic structure of a Rete.js component, including its template, builder function for node setup, and worker function for processing. The builder runs once on node creation, while the worker executes during processing. ```js var myComponent = new D3NE.Component('My component', { template: nodeTemplate, builder(node){ /// modify node return node; }, worker(node, inputs, outputs){ } }); ``` -------------------------------- ### Rete.js Engine API: Processing with Arguments and Error Handling Source: https://github.com/retejs/rete/wiki/Engine Details advanced usage of the Rete.js Engine's `process` method, including specifying a starting node ID, passing custom arguments to workers, and setting up an error handler for processing failures. ```APIDOC Engine Class Methods: process(data, startNodeId, ...args) - Processes the flow graph with the provided data. - Parameters: - data: JSON representation of the editor's state. - startNodeId: Optional. The ID of the node from which processing should start. - ...args: Optional. Additional arguments passed to each worker function. - Returns: A promise that resolves when processing is complete, or 'error' if an error occurs. - Example: engine.process(data, node.id); engine.process(data, null, arg1, arg2); worker(node, inputs, outputs, ...args) - Custom worker function signature that can receive additional arguments. - Example: worker(node, inputs, outputs, arg1, arg2) { outputs[0] = node.data.num; } abort() - Cancels any ongoing processing and returns a promise that resolves when cancellation is complete. - Usage: await engine.abort(); onError = (msg, obj) => { ... } - Callback function to handle errors during processing. - Parameters: - msg: Error message string. - obj: Optional object containing error details. - Example: engine.onError = (msg, obj) => { console.error('Processing Error:', msg, obj); }; ``` -------------------------------- ### Define Custom Connection Curve Source: https://github.com/retejs/rete/wiki/Editor Enables customization of how connections between nodes are rendered. This example defines a 'step' curve for connections, but other options like 'linear' or 'basis' are also available. ```js editor.view.connectionProducer = (x1, y1, x2, y2) => { return { points: [[x1, y1], [x2, y2]], curve: 'step' }; }; ``` -------------------------------- ### Handle Editor Changes and Engine Processing Source: https://github.com/retejs/rete/wiki/Engine Shows how to integrate the Rete.js Engine with the editor's 'change' event to automatically re-process data when the graph is modified. It includes examples for both simple processing and using `abort` to manage concurrent processing. ```js editor.eventListener.on('change', () => { engine.process(editor.toJSON()); // imagine that it could take one second of time }); ``` ```js editor.eventListener.on('change', async () => { await engine.abort(); await engine.process(editor.toJSON()); }); ``` -------------------------------- ### Temporarily Disable Rete.js Context Menu Source: https://github.com/retejs/rete/wiki/Context-menu Provides an example of how to temporarily disable an existing Rete.js context menu instance by setting its 'disabled' property to true. This allows for dynamic control over menu availability. ```javascript menu.disabled = true; ``` -------------------------------- ### Initialize Node Editor and Context Menu Source: https://github.com/retejs/rete/wiki/Home Demonstrates the initialization of the d3-node-editor. It involves creating a context menu, selecting a container element for the editor, and then instantiating the NodeEditor with a unique ID, container, components, and the menu. ```js var menu = new D3NE.ContextMenu({ 'Actions':{ 'Action': function(){alert('Subitem selected');} }, 'Nodes':{ 'Number': numComp, 'Add': addComp } }); var container = document.querySelector('#d3ne'); var editor = new D3NE.NodeEditor('demo@0.1.0', container, components, menu); ``` -------------------------------- ### Initialize Rete.js Context Menu with Items Source: https://github.com/retejs/rete/wiki/Context-menu Demonstrates how to create a context menu for the Rete.js editor. It shows how to define menu items, including nested sub-items, functions, and components, and pass them to the ContextMenu constructor along with a search bar visibility flag. This menu is then passed to the NodeEditor. ```javascript var items = { 'Values':{ 'Number': numberComponent, 'Action': function(){alert('Subitem selected');} }, 'Add': addComponent, }; var menu = new D3NE.ContextMenu(items, searchBarIsVisible); var nodeEditor = new D3NE.NodeEditor('demo@0.1.0', container, components, menu); ``` -------------------------------- ### Create Rete.js Group with Initial Nodes Source: https://github.com/retejs/rete/wiki/Groups Shows how to create a group and immediately populate it with an array of nodes. The group's position and size are automatically adjusted to encompass these nodes. ```javascript var group = new D3NE.Group("Name", {nodes: arrayNodes}); // or add nodes latelly group.coverNodes(arrayNodes); // position and sized of the group are calculated to cover the selected nodes ``` -------------------------------- ### Rete.js Node Creation and Configuration Source: https://github.com/retejs/rete/wiki/Nodes Demonstrates how to create nodes with inputs, outputs, and controls using the Rete.js library. It covers defining connection points and adding custom HTML controls. ```javascript var in1 = new D3NE.Input('Number',numSocket); var in2 = new D3NE.Input('Number',numSocket, true); //can have multiple connections var out = new D3NE.Output('Number',numSocket); // the third parameter must be false to deny multiple connections var numControl = new D3NE.Control('',(element, control)=>{ control.setValue = (val) => { el.value = val; } }); var numNode = new D3NE.Node('Add'); numNode.addInput(in1); numNode.addInput(in2); numNode.addControl(numControl) numNode.addOutput(out); ``` -------------------------------- ### Initialize and Process Data with Rete.js Engine Source: https://github.com/retejs/rete/wiki/Engine Demonstrates the initialization of the Rete.js Engine with a specific version and components, followed by processing exported JSON data. This is the primary method for executing the flow graph. ```js var engine = new D3NE.Engine('demo@0.1.0', components); engine.process(data); ``` -------------------------------- ### Create and Configure D3NE Task in Worker Source: https://github.com/retejs/rete/wiki/Extras Demonstrates how to instantiate a `D3NE.Task` within a Rete.js worker function. It shows how to define the callback executed when `task.run()` is called and how to specify outputs for control flow transfer (`task.option`) and data transfer (`task.output`). ```javascript worker: function (node, inputs, outputs) { var task = new D3NE.Task(inputs, function (inps, data) { /// the function is executed when `task.run()` is called return [data] // output data excluding sockets to transfer control to the following tasks }); tasksToCallOutside.push(task); outputs[0] = task.option(0); // define that the first output is intended to transfer control to the next node outputs[1] = task.output(0); // just data transfer from second output } ``` -------------------------------- ### Create Rete.js NodeEditor Instance Source: https://github.com/retejs/rete/wiki/Editor Instantiates a new NodeEditor, which is the core component for building node-based interfaces. It requires an identifier, a container element, an array of components, and an optional context menu. ```js var nodeEditor = new D3NE.NodeEditor('demo@0.1.0', container, components, menu); ``` -------------------------------- ### Render Node Outputs with Angular Light (HTML) Source: https://github.com/retejs/rete/wiki/Customization Demonstrates using Angular Light directives within a Rete.js node template to iterate over node outputs. It shows how to display output titles and sockets, applying a 'used' class based on connection status. ```html
{{output.title}}
``` -------------------------------- ### Create Rete.js Control with Input Element Source: https://github.com/retejs/rete/wiki/Controls Demonstrates creating a custom Rete.js Control using a JavaScript template for an HTML input element. The control is initialized with a value and listens for 'change' events to update node data. ```javascript var template = ''; var ctrl = new D3NE.Control(template, (element, control) => { // called when an element is created in the DOM element.value = 1; element.addEventListener('change',()=>{ control.putData('num', element.value); // put data in the node under the key "num" }); }); ``` -------------------------------- ### Initialize Rete.js Node Editor Without Context Menu Source: https://github.com/retejs/rete/wiki/Context-menu Shows how to initialize a Rete.js NodeEditor instance without providing a context menu. This is useful if you do not want the context menu functionality in your editor. ```javascript var nodeEditor = new D3NE.NodeEditor('demo@0.1.0', container, components); ``` -------------------------------- ### Manage and Retrieve Rete.js Components Source: https://github.com/retejs/rete/wiki/Components Illustrates how to manage a collection of Rete.js components, typically by storing them in an array or object. It includes a utility function to retrieve a specific component by its name, throwing an error if not found. ```js /// index.js import numberComponent from './nodes/number'; var components = [ numberComponent ]; var components = { list : [...], get(name) { var comp = this .list .find(item => item.name === name); if (!comp) throw new Error(`Component '${name}' not found`); return comp; } } ``` -------------------------------- ### Define Rete.js Components with Builders Source: https://github.com/retejs/rete/wiki/Editor Illustrates how to define custom node components for the editor. Each component requires a name and a builder function, which is responsible for constructing the node's structure and is essential for restoring nodes from JSON data. ```js var components = [ new D3NE.Component('Number',{ builder(node){ // modify node return node; } }), new D3NE.Component('Add',{ builder(node){ // ... return node; } }) ]; ``` -------------------------------- ### Create a custom Socket in d3-node-editor Source: https://github.com/retejs/rete/wiki/Home Shows how to define a new Socket type, which represents a connection point for nodes. Sockets have a name, a display name, and an optional hint for user guidance. ```js var numSocket = new D3NE.Socket('number', 'Number value', 'hint'); ``` -------------------------------- ### Create Empty Rete.js Group Programmatically Source: https://github.com/retejs/rete/wiki/Groups Demonstrates how to create an empty group with specified dimensions and position. The group is then added to the editor instance. ```javascript var group = new D3NE.Group("Name", {position: [0,0], width: 400, height:200}); editor.addGroup(group); ``` -------------------------------- ### Apply Inline Styles to Rete.js Nodes and Groups (JavaScript) Source: https://github.com/retejs/rete/wiki/Customization Illustrates how to apply dynamic inline styles directly to Rete.js nodes, groups, or connections using their `style` property. This method allows for programmatic visual adjustments to individual elements. ```javascript node.style.boxShadow = "2px 2px 20px red"; group.style.BackgroundColor = "black"; connection.style.stroke = 8; // only properties for editor.view.update(); ``` -------------------------------- ### Rete.js Input Control for Node Data Source: https://github.com/retejs/rete/wiki/Controls Shows how to create a Rete.js Input control with an HTML input element. This control is used to put data into the node, specifically when there is no connection on the input, allowing for default or user-defined values. ```javascript var in1 = new D3NE.Input('Number',numSocket); var numControl = new D3NE.Control('',(element, control)=>{ control.putData('inputNumber', element.value); element.addEventListener('change',()=>{ control.putData('inputNumber', element.value); }); }); ``` -------------------------------- ### Process data with the Engine Source: https://github.com/retejs/rete/wiki/Home Explains how to use the d3-node-editor Engine to process the graph data. It involves creating an Engine instance and listening for editor changes to re-process the graph, updating it asynchronously. ```js var engine = new D3NE.Engine('demo@0.1.0', components); editor.eventListener.on('change', async () => { await engine.abort(); var status = await engine.process(editor.toJSON()); }); ``` -------------------------------- ### Combine Rete.js Sockets Source: https://github.com/retejs/rete/wiki/Sockets Shows how to use the `combineWith` method to allow connections between different socket types in Rete.js. This enables flexible data flow when strict type matching is not required, but note that the combination is unidirectional. ```js var anyTypeSocket = new D3NE.Socket('any', 'Any type', 'hint'); numSocket.combineWith(anyTypeSocket); ``` -------------------------------- ### Define an Add Component with async worker in d3-node-editor Source: https://github.com/retejs/rete/wiki/Home Shows the definition of an 'Add' component, which includes a template for its visual representation, a builder function for its structure, and an asynchronous worker function. The async worker allows for operations like fetching data or performing timed tasks. ```js var addComp = new D3NE.Component('Add',{ template: '
',(element, control)=>{ control.putData('num', 1); }); return node .addControl(numControl) .addOutput(out); }, worker(node, inputs, outputs){ outputs[0] = node.data.num; } }); ``` -------------------------------- ### Declare Rete.js Sockets Source: https://github.com/retejs/rete/wiki/Sockets Demonstrates how to declare unique sockets for different data types in Rete.js. Sockets define connection compatibility between nodes, indicating the type of data that can be transferred. ```js var numSocket = new D3NE.Socket('number', 'Number value', 'hint'); var strSocket = new D3NE.Socket('string', 'String', 'hint'); ``` -------------------------------- ### Exporting a Rete.js Component Source: https://github.com/retejs/rete/wiki/Components Shows a common pattern for modularizing Rete.js components by defining and exporting them from separate files. This approach facilitates better organization and management of complex editor structures. ```js /// nodes/number.js export default new D3NE.Component('Number',{ builder(node){ return node; }, worker(){ } }); ``` -------------------------------- ### Process Rete.js Engine on Multiple Events Source: https://github.com/retejs/rete/wiki/Events Combine multiple Rete.js events like 'nodecreate' and 'connectioncreate' to trigger an asynchronous engine re-processing. This is useful for updating the editor's state or logic after significant changes. ```javascript editor.eventListener.on('nodecreate connectioncreate noderemove connectionremove', (_,persistent) => { setTimeout(async () => { await engine.abort(); await engine.process(); }); }); ``` -------------------------------- ### Style Sockets in d3-node-editor Source: https://github.com/retejs/rete/wiki/Home Provides CSS rules to customize the visual appearance of specific Socket types. By targeting the socket's class name (e.g., '.socket.number'), you can change its background color or other styles. ```css .socket.number{ background: #96b38a } ``` -------------------------------- ### Customize Connection Rendering in Rete.js (JavaScript) Source: https://github.com/retejs/rete/wiki/Customization Explains how to override the default connection rendering in Rete.js by modifying the `connectionProducer` method. This allows specifying custom curve types like 'step' for connections between nodes. ```javascript editor.view.connectionProducer = (x1,y1,x2,y2) => { return { points:[[x1,y1],[x2,y2]], curve: 'step' // linear, step or basis(default) }; }; ``` -------------------------------- ### Style Rete.js Sockets Source: https://github.com/retejs/rete/wiki/Sockets Provides CSS styling for Rete.js sockets to visually differentiate them based on their type. This is crucial for usability when multiple socket types exist, ensuring users can easily identify compatible connections. ```css .socket.number{ background: #96b38a } ``` -------------------------------- ### Define Node Template in Rete.js (JavaScript) Source: https://github.com/retejs/rete/wiki/Customization Shows how to define a custom template for Rete.js nodes by passing a template string to the Component constructor. This allows overriding the default node rendering with custom HTML structures and Angular Light directives. ```javascript var componentNum = new D3NE.Component("number", { template: template, ... }); ``` -------------------------------- ### Customize Editor View Scale Extent Source: https://github.com/retejs/rete/wiki/Editor Allows setting the minimum and maximum zoom levels for the editor's view, controlling how much the user can zoom in or out. ```js editor.view.setScaleExtent(0.1, 1); ``` -------------------------------- ### Customize Editor View Zoom Source: https://github.com/retejs/rete/wiki/Editor Provides methods to control the visual presentation of the node editor. This snippet shows how to adjust the zoom level to fit specific nodes within the viewport. ```js editor.view.zoomAt(nodes); ``` -------------------------------- ### Define Rete.js Node Workers Source: https://github.com/retejs/rete/wiki/Engine Illustrates how to define custom node workers for Rete.js components. Workers are functions that receive node data, inputs, and outputs, allowing developers to define the logic for data processing within each node. ```js var components = [ new D3NE.Component('Number',{ worker(node, inputs, outputs){ outputs[0] = node.data.num; } }), new D3NE.Component('Add',{ async worker(node, inputs, outputs){ outputs[0] = inputs[0][0] + inputs[1][0]; await asyncTask(); } }) ]; ``` -------------------------------- ### Customize Editor View Translation Extent Source: https://github.com/retejs/rete/wiki/Editor Defines the boundaries for panning the editor's view, specifying the left, top, right, and bottom limits of the movable work area. ```js editor.view.setTranslateExtent(-1000, -1000, 1000, 1000); ``` -------------------------------- ### Manage Nodes within a Rete.js Group Source: https://github.com/retejs/rete/wiki/Groups Provides methods to check if a node is positioned within a group's bounds and to explicitly add or remove nodes from a group. ```javascript if(group.isCoverNode(node)) // check if the node is above the group group.addNode(node); group.removeNode(node); ``` -------------------------------- ### Import NodeEditor Data from JSON Source: https://github.com/retejs/rete/wiki/Editor Restores the NodeEditor's state from a previously exported JSON object. This method requires the editor's identifier to match the data's identifier to prevent compatibility issues. ```js await editor.fromJSON(data); ``` -------------------------------- ### Export NodeEditor Data to JSON Source: https://github.com/retejs/rete/wiki/Editor Serializes the current state of the NodeEditor, including all nodes, their data, connections, and group configurations, into a JSON object. This data can be saved and later used to restore the editor's state. ```js var data = editor.toJSON(); ``` -------------------------------- ### Handle Rete.js 'change' Event Source: https://github.com/retejs/rete/wiki/Events Listen for the 'change' event in Rete.js to execute logic after any modification to the editor's state. The `persistent` flag indicates if the change is part of a data import. ```javascript editor.eventListener.on('change', (_, persistent) => { // trigger after each of the first six events // `persistent` is false when data is importing into the editor (it is not necessary to perform any actions with the view) }); ``` -------------------------------- ### Prevent Rete.js Node Creation Source: https://github.com/retejs/rete/wiki/Events Intercept the 'nodecreate' event in Rete.js to conditionally prevent node creation. Returning `false` from the event handler stops the action, useful for validation like checking for duplicate node names. ```javascript editor.eventListener.on('nodecreate', (node, persistent) => { /// check if there is already a node with that name var haveSomeNode = editor.nodes.some(item => item.name === node.name); return !haveSomeNode; // prevent the addition of a new node }); ``` -------------------------------- ### Prevent Task Execution with task.closed Source: https://github.com/retejs/rete/wiki/Extras Illustrates how to use the `task.closed` property to specify sockets that should halt the execution flow. This is useful for conditional logic or preventing unintended node processing by defining which sockets should not carry tasks further. ```javascript task.closed = [1]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.