### Install and Initialize jsPlumb Source: https://context7.com/jsplumb/community-edition/llms.txt Install jsPlumb via npm and initialize an instance within a ready callback. This sets up the canvas and default drag/paint options. ```javascript // Install via npm // npm install @jsplumb/browser-ui // Import and create a new instance import { newInstance, ready } from "@jsplumb/browser-ui" ready(() => { const instance = newInstance({ container: document.getElementById("canvas"), dragOptions: { cursor: 'pointer', zIndex: 2000 }, paintStyle: { stroke: '#666', strokeWidth: 2 }, endpoint: "Dot", anchor: "Bottom" }) // Your jsPlumb code here }) ``` -------------------------------- ### Applying custom CSS classes to connections Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/styling-via-css.md Example of using the cssClass parameter when creating a connection. ```javascript jsPlumb.connect({ source:"someElement", target:"someOtherElement", cssClass:"redLine" }); ``` -------------------------------- ### Install jsPlumb Community Edition via npm Source: https://github.com/jsplumb/community-edition/blob/master/changelog.md Use this command to install the package in your project. ```bash npm i @jsplumb/community ``` -------------------------------- ### Import jsPlumb via script tag Source: https://github.com/jsplumb/community-edition/blob/master/changelog.md Include the library in your HTML file after installation. ```html ``` -------------------------------- ### Full Connection Type API Examples Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/types.md Demonstrates registering multiple connection types, checking for types, adding, toggling, removing, and clearing types on a connection. Parameterized types like 'boz' can be applied with specific data. ```javascript jsPlumb.registerConnectionTypes({ "foo":{ paintStyle:{ stroke:"yellow", strokeWidth:5, cssClass:"foo" } }, "bar":{ paintStyle:{ stroke:"blue", strokeWidth:10 } }, "baz":{ paintStyle:{ stroke:"green", strokeWidth:1, cssClass:"${clazz}" } }, "boz":{ paintStyle: { stroke:"${color}", strokeWidth:"${width}" } } }); var c = jsPlumb.connect({ source:"someDiv", target:"someOtherDiv", type:"foo" }); // see what types the connection has. console.log(c.hasType("foo")); // -> true console.log(c.hasType("bar")); // -> false // add type 'bar' c.addType("bar"); // toggle both types (they will be removed in this case) c.toggleType("foo bar"); // toggle them back c.toggleType("foo bar"); // getType returns a list of current types. console.log(c.getType()); // -> [ "foo", "bar" ] // set type to be 'baz' only c.setType("baz"); // add foo and bar back in c.addType("foo bar"); // remove baz and bar c.removeType("baz bar"); // what are we left with? good old foo. console.log(c.getType()); // -> [ "foo" ] // now let's add 'boz', a parameterized type c.addType("boz", { color:"#456", width:35 }); console.log(c.getType()); // -> [ "foo", "boz" ] // now clear all types c.clearTypes(); console.log(c.getType()); // -> [ ] ``` -------------------------------- ### Install jsPlumb via NPM Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/home.md Use this command to install the jsPlumb package in your project. ```javascript npm install jsplumb ``` -------------------------------- ### Grid Position Finder Implementation Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/connections.md Example source code for the default 'Grid' position finder, demonstrating how it calculates anchor positions based on mouse event and element geometry. ```javascript function(eventOffset, elementOffset, elementSize, constructorParams) { var dx = eventOffset.left - elementOffset.left, dy = eventOffset.top - elementOffset.top, gx = elementSize[0] / (constructorParams.grid[0]), gy = elementSize[1] / (constructorParams.grid[1]), mx = Math.floor(dx / gx), my = Math.floor(dy / gy); return [ ((mx * gx) + (gx / 2)) / elementSize[0], ((my * gy) + (gy / 2)) / elementSize[1] ]; } ``` -------------------------------- ### Configure Endpoint Overlay Location Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/overlays.md Examples of setting the location property for an overlay on an Endpoint using [x, y] coordinates. ```javascript location:[ 0.5, 0.5 ] ``` ```javascript location: [ 5, 0 ] ``` ```javascript location: [ -5, 0 ] ``` -------------------------------- ### Select all Connections and set hover state Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Use the `select` function to get all connections and then chain the `setHover` method to disable hover effects. ```javascript jsPlumb.select().setHover(false); ``` -------------------------------- ### Positioning and Sizing Utilities Source: https://github.com/jsplumb/community-edition/blob/master/etc/api/browser-ui.api.md Utility functions for getting position, size, and offset information of DOM elements. ```APIDOC ## getOffset, getOffsetRelativeToRoot, getPosition ### Description Functions to get the offset and position of a DOM element. ### Method (Implicitly methods of a jsPlumb instance) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript instance.getOffset(element); instance.getOffsetRelativeToRoot(element); instance.getPosition(element); ``` ### Response #### Success Response (200) Type: PointXY #### Response Example None specified ``` ```APIDOC ## getSelector ### Description Finds DOM elements based on a selector string within a given context. ### Method (Implicitly a method of a jsPlumb instance) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript instance.getSelector('body', '.my-selector'); ``` ### Response #### Success Response (200) Type: ArrayLike #### Response Example None specified ``` ```APIDOC ## getSize ### Description Gets the size (width and height) of a DOM element. ### Method (Implicitly a method of a jsPlumb instance) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript instance.getSize(element); ``` ### Response #### Success Response (200) Type: Size #### Response Example None specified ``` ```APIDOC ## getStyle ### Description Gets the computed style property of a DOM element. ### Method (Implicitly a method of a jsPlumb instance) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript instance.getStyle(element, 'color'); ``` ### Response #### Success Response (200) Type: any #### Response Example None specified ``` -------------------------------- ### jsPlumb Endpoint Options for makeSource Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/connections.md Configure endpoint appearance, connector styles, and overlays when using `makeSource`. This example adds an Arrow overlay halfway along the connection. ```javascript var exampleGreyEndpointOptions = { endpoint:"Rectangle", paintStyle:{ width:25, height:21, fill:'#666' }, isSource:true, connectorStyle : { stroke:"#666" }, isTarget:true, connectorOverlays: [ [ "Arrow", { location:0.5 } ] ] }; ``` -------------------------------- ### Paint Style Configuration Parameters Source: https://github.com/jsplumb/community-edition/blob/master/doc/paint-styles.md A reference guide for the properties used to define the visual style of jsPlumb elements. ```APIDOC ## Paint Style Parameters ### Description Defines the visual properties for Connectors and Endpoints. Note that 'fill' is ignored by Connectors and 'stroke' is ignored by Endpoints. ### Parameters - **fill** (string) - Color for an Endpoint (e.g., "blue", "#456", "rgba(100,100,100,50)"). - **stroke** (string) - Color for a Connector. - **strokeWidth** (integer) - Width of a Connector's line. - **outlineWidth** (integer) - Width of the outline for an Endpoint or Connector. - **outlineStroke** (string) - Color of the outline for an Endpoint or Connector. - **dashstyle** (array) - Array of strokes and spaces defining dashed lines, where values are multiples of the Connector width. - **stroke-dasharray** (string) - SVG equivalent of dashstyle. - **stroke-dashoffset** (string) - Specifies how far into the dash pattern to start painting. - **stroke-linejoin** (string) - Specifies how individual segments of connectors are joined. ``` -------------------------------- ### Initialize Instance with Defaults Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/home.md Pass a configuration object to getInstance to set defaults upon creation. ```javascript var secondInstance = jsPlumb.getInstance({ PaintStyle:{ strokeWidth:6, stroke:"#567567", outlineStroke:"black", outlineWidth:1 }, Connector:[ "Bezier", { curviness: 30 } ], Endpoint:[ "Dot", { radius:5 } ], EndpointStyle : { fill: "#567567" }, Anchor : [ 0.5, 0.5, 1, 1 ] }); secondInstance.connect({ source:"element4", target:"element3", scope:"someScope" }); ``` -------------------------------- ### Create Custom Overlays Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/overlays.md Demonstrates implementing a Custom overlay by providing a create method that returns a DOM element. ```javascript var conn = jsPlumb.connect({ source:"d1", target:"d2", paintStyle:{ stroke:"red", strokeWidth:3 }, overlays:[ ["Custom", { create:function(component) { return $(""); }, location:0.7, id:"customOverlay" }] ] }); ``` -------------------------------- ### Initialize QUnit test suite Source: https://github.com/jsplumb/community-edition/blob/master/tests/groups/qunit.html Standard entry point for executing a QUnit test suite within jsPlumb. ```javascript jsPlumb.ready(testSuite); ``` -------------------------------- ### Establish a basic connection Source: https://github.com/jsplumb/community-edition/blob/master/doc/connect-examples.md Connects two elements using default settings. ```javascript jsPlumb.connect({source:"window1", target:"window2"}); ``` -------------------------------- ### Get All Connections Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Retrieves all connections managed by jsPlumb, regardless of scope. This is a general utility function. ```javascript jsPlumb.getAllConnections(); ``` -------------------------------- ### Configure and Connect Instance Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/home.md Set defaults and create connections using a specific jsPlumb instance. ```javascript firstInstance.importDefaults({ Connector : [ "Bezier", { curviness: 150 } ], Anchors : [ "TopCenter", "BottomCenter" ] }); firstInstance.connect({ source:"element1", target:"element2", scope:"someScope" }); ``` -------------------------------- ### GET jsPlumb.selectEndpoints Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Selects a collection of endpoints based on provided criteria and returns a chainable object for operations. ```APIDOC ## GET jsPlumb.selectEndpoints ### Description Provides a fluid interface for working with lists of Endpoints. Returns an object that supports chainable setter operations and non-chainable getter operations. ### Parameters #### Query Parameters - **element** (string/selector/DOM element/array) - Optional - Element(s) to get both source and target endpoints from. - **source** (string/selector/DOM element/array) - Optional - Element(s) to get source endpoints from. - **target** (string/selector/DOM element/array) - Optional - Element(s) to get target endpoints from. - **scope** (string/array) - Optional - Scope(s) for endpoints to retrieve. ### Request Example jsPlumb.selectEndpoints({source:"d1"}); ### Response - **Selection Object** (Object) - A chainable object containing the selected endpoints and methods for manipulation. ``` -------------------------------- ### Container and UI Group Management Source: https://github.com/jsplumb/community-edition/blob/master/etc/api/browser-ui.api.md Functions for setting the container element and getting UI group content areas. ```APIDOC ## setContainer ### Description Sets the new container element for jsPlumb. ### Method (Implicitly a method of a jsPlumb instance) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript instance.setContainer(document.getElementById('myContainer')); ``` ### Response #### Success Response (200) Type: void #### Response Example None specified ``` ```APIDOC ## getGroupContentArea ### Description Retrieves the content area element for a given UI group. ### Method (Implicitly a method of a jsPlumb instance) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript instance.getGroupContentArea(uiGroup); ``` ### Response #### Success Response (200) Type: Element #### Response Example None specified ``` -------------------------------- ### Select all Connections and add CSS classes Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Apply multiple CSS classes to all selected connections using the `addClass` method. ```javascript jsPlumb.select().addClass("foo bar"); ``` -------------------------------- ### Initialize jsPlumb instance with defaults Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/defaults.md Pass a configuration object to jsPlumb.getInstance to set default styles, drag options, and endpoint definitions for the new instance. ```javascript jsPlumb.getInstance({ PaintStyle : { strokeWidth:13, stroke: 'rgba(200,0,0,100)' }, DragOptions : { cursor: "crosshair" }, Endpoints : [ [ "Dot", { radius:7 } ], [ "Dot", { radius:11 } ] ], EndpointStyles : [ { fill:"#225588" }, { fill:"#558822" } ] }); ``` -------------------------------- ### Get Connections for a Single Named Scope Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Retrieves all connections for a specific named scope. The return value is a list. ```javascript jsPlumb.getConnections({scope:"myTestScope"}); ``` -------------------------------- ### Event Handling and Instance Management Source: https://github.com/jsplumb/community-edition/blob/master/etc/api/core.api.md Methods for event handling, instance configuration, and utility functions. ```APIDOC ## Event Handling ### abstract off(el: Document | T["E"] | ArrayLike, event: string, callback: Function): void - **Description**: Removes an event listener from an element or document. ### abstract on(el: Document | T["E"] | ArrayLike, event: string, callbackOrSelector: Function | string, callback?: Function): void - **Description**: Adds an event listener to an element or document. ## Instance Management ### each(spec: T["E"] | Array, fn: (e: T["E"])=> any): JsPlumbInstance - **Description**: Iterates over elements or connections and applies a function. ### importDefaults(d: JsPlumbDefaults): JsPlumbInstance - **Description**: Imports default settings into the jsPlumb instance. ### getContainer(): any - **Description**: Gets the container element for the jsPlumb instance. ### getSuspendedAt(): string - **Description**: Gets the suspension state of the instance. ### getType(id: string, typeDescriptor: string): TypeDescriptor - **Description**: Retrieves a type descriptor by ID and type. ### isHoverSuspended(): boolean - **Description**: Checks if hover events are currently suspended. ### hoverSuspended: boolean - **Description**: Flag indicating if hover events are suspended. ## Utility Methods ### _idstamp(): string - **Description**: Internal method to generate a unique ID. (Internal Use Only) ### _getAssociatedElements(el: T["E"]): Array - **Description**: Internal method to get associated elements. (Internal Use Only) ### _getRotation(elementId: string): number - **Description**: Internal method to get the rotation of an element. (Internal Use Only) ### _getRotations(elementId: string): Rotations - **Description**: Internal method to get the rotations of an element. (Internal Use Only) ### getConnectorClass(connector: AbstractConnector): string - **Warning**: This symbol is marked as @public, but its signature references "AbstractConnector" which is marked as @internal. - **Description**: Gets the class name of a connector. ### _internal_newEndpoint(params: InternalEndpointOptions): Endpoint - **Description**: Internal method to create a new endpoint with internal options. (Internal Use Only) ``` -------------------------------- ### Get Connections for a Specific Scope Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Retrieves all connections belonging to a specified scope. The return value is a list of Connection objects. ```javascript var connectionList = jsPlumb.getConnections("myScope"); // you get a list of Connection objects that are in "myScope". ``` -------------------------------- ### Manage Connection Overlays Source: https://context7.com/jsplumb/community-edition/llms.txt Adds Arrow, Label, and Custom DOM overlays to connections, and demonstrates programmatic control. ```javascript // Arrow overlay instance.connect({ source: "el1", target: "el2", overlays: [ { type: "Arrow", options: { location: 1, // At end of connection width: 12, length: 15, foldback: 0.8, // Arrow indentation direction: 1, // 1 = forward, -1 = backward id: "arrow1" } } ] }) // Label overlay instance.connect({ source: "el1", target: "el2", overlays: [ { type: "Label", options: { label: "Connection Label", location: 0.5, // Middle of connection cssClass: "my-label", id: "label1" } } ] }) // Custom overlay with DOM element instance.connect({ source: "el1", target: "el2", overlays: [ { type: "Custom", options: { create: function(component) { const el = document.createElement("select") el.innerHTML = '' return el }, location: 0.7, id: "customOverlay" } } ] }) // Manipulating overlays programmatically const conn = instance.connect({ source: "el1", target: "el2", label: "Click me" }) const labelOverlay = conn.getOverlay("label") labelOverlay.setLabel("New Label") conn.hideOverlay("label") conn.showOverlay("label") conn.removeOverlay("label") ``` -------------------------------- ### Initialize a Flowchart with jsPlumb Source: https://context7.com/jsplumb/community-edition/llms.txt Sets up a jsPlumb instance with custom drag options and connection overlays, then defines endpoint styles and establishes initial connections within a batch operation. ```javascript import { newInstance, ready, AnchorLocations, DotEndpoint, FlowchartConnector } from "@jsplumb/browser-ui" ready(() => { const instance = newInstance({ container: document.getElementById("canvas"), dragOptions: { cursor: 'pointer', zIndex: 2000, grid: { w: 20, h: 20 }, containment: "notNegative" }, connectionOverlays: [ { type: "Arrow", options: { location: 1, width: 11, length: 11, id: "arrow" } }, { type: "Label", options: { location: 0.5, id: "label", cssClass: "conn-label" } } ] }) // Define endpoint styles const sourceEndpoint = { endpoint: { type: DotEndpoint.type, options: { radius: 7 } }, paintStyle: { fill: "#7AB02C", stroke: "#7AB02C", strokeWidth: 1 }, source: true, connector: { type: FlowchartConnector.type, options: { stub: 40, gap: 10, cornerRadius: 5 } }, connectorStyle: { stroke: "#61B7CF", strokeWidth: 2 }, connectorHoverStyle: { stroke: "#216477", strokeWidth: 3 } } const targetEndpoint = { endpoint: { type: DotEndpoint.type, options: { radius: 7 } }, paintStyle: { fill: "#7AB02C", radius: 7 }, target: true, maxConnections: -1 } // Batch all initialization instance.batch(() => { // Add endpoints to nodes const nodes = ["node1", "node2", "node3", "node4"] nodes.forEach(nodeId => { const el = document.getElementById(nodeId) instance.addEndpoint(el, sourceEndpoint, { anchor: "Bottom", uuid: `${nodeId}-source` }) instance.addEndpoint(el, targetEndpoint, { anchor: "Top", uuid: `${nodeId}-target` }) }) // Create initial connections instance.connect({ uuids: ["node1-source", "node2-target"] }) instance.connect({ uuids: ["node2-source", "node3-target"] }) instance.connect({ uuids: ["node2-source", "node4-target"] }) }) // Event handlers instance.bind("connection", (info) => { info.connection.getOverlay("label").setLabel( `${info.sourceId} -> ${info.targetId}` ) }) instance.bind("click", (conn, e) => { if (confirm(`Delete connection from ${conn.sourceId} to ${conn.targetId}?`)) { instance.deleteConnection(conn) } }) }) ``` -------------------------------- ### Get Connections for Default Scope Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Retrieves all connections belonging to the default scope. The return value is a list of Connection objects. ```javascript var connectionList = jsPlumb.getConnections(); // you get a list of Connection objects that are in the default scope. ``` -------------------------------- ### Get All Parameters from Connection Source: https://github.com/jsplumb/community-edition/blob/master/doc/parameters.md Retrieve all parameters associated with a connection using the `getParameters()` method. This returns an object containing all key-value pairs. ```javascript var params = conn.getParameters(); console.log(params.p1); // 34 console.log(params.p2); // Mon May 14 2012 12:57:12 GMT+1000 (EST) (or however your console prints out a Date) console.log((params.p3)()); // "i am p3" (note: we executed the function after retrieving it) console.log(params.p5); // 343 ``` -------------------------------- ### Define Basic Endpoint Options Source: https://github.com/jsplumb/community-edition/blob/master/doc/draggable-connections-examples.md Sets up a basic configuration object for an Endpoint that acts as both a source and a target. ```javascript var endpointOptions = { isSource:true, isTarget:true }; ``` -------------------------------- ### Handle max connections in makeTarget Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/connections.md Demonstrates using the onMaxConnections callback to handle events when the connection limit is reached. ```javascript jsPlumb.makeTarget("aTargetDiv", { isTarget:true, maxConnections:5, endpoint:"Rectangle", paintStyle:{ fill:"gray" }, maxConnections:3, onMaxConnections:function(params, originalEvent) { console.log("user tried to drop connection", params.connection, "on element", params.endpoint.element, "with max connections", params.maxConnections); } }; ``` -------------------------------- ### Get Parameter from Connection Source: https://github.com/jsplumb/community-edition/blob/master/doc/parameters.md Retrieve a specific parameter from a connection using `getParameter(key)`. The value can be any JavaScript object, including functions. ```javascript myConnection.getParameter("p3")(); ``` -------------------------------- ### Configure Endpoint Types Source: https://context7.com/jsplumb/community-edition/llms.txt Sets up Dot, Rectangle, Blank, and Image endpoints for connection anchors. ```javascript // Dot endpoint instance.addEndpoint("element", { endpoint: { type: "Dot", options: { radius: 10 } }, paintStyle: { fill: "#456", stroke: "#000", strokeWidth: 1 } }) // Rectangle endpoint instance.addEndpoint("element", { endpoint: { type: "Rectangle", options: { width: 20, height: 15 } }, paintStyle: { fill: "#789" }, hoverPaintStyle: { fill: "#abc" } }) // Blank endpoint (invisible, but still functional) instance.connect({ source: "el1", target: "el2", endpoint: "Blank" }) // Image endpoint instance.addEndpoint("element", { endpoint: { type: "Image", options: { src: "/images/endpoint.png" } }, cssClass: "custom-endpoint" }) ``` -------------------------------- ### Configure jsPlumb Instance with ListStyle Defaults Source: https://github.com/jsplumb/community-edition/blob/master/demonstrations/scrollable-lists/js/index.html Initialize jsPlumb with default settings, including `ListStyle` for automatic scrollable list configuration. ```javascript var instance = jsPlumbBrowserUI.getInstance({ connector: "Straight", paintStyle: { strokeWidth: 3, stroke: "#ffa500", "dashstyle": "2 4" }, endpoint: [ "Dot", { radius: 5 } ], endpointStyle: { fill: "#ffa500" }, container: "canvas", listStyle:{ endpoint:["Rectangle", { width:30, height:30 }] } }); ``` -------------------------------- ### Get jsPlumb Instance with Constructor Container Option Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/home.md Obtain a new jsPlumb instance and specify the container element directly in the constructor parameters. ```javascript var j = jsPlumb.getInstance({ Container:"foo" }); ... jsPlumb.addEndpoint(someDiv, { endpoint:options }); ``` -------------------------------- ### Use Reference Parameters Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/connections.md Shares common configuration parameters across multiple makeSource calls. ```javascript var common = { anchor:"Continuous", endpoint:["Rectangle", { width:40, height:20 }], }; jsPlumb.makeSource("el1", { maxConnections:1, onMaxConnections:function(params, originalEvent) { console.log("element is ", params.endpoint.element, "maxConnections is", params.maxConnections); } }, common); ``` -------------------------------- ### LabelOverlay Class Source: https://github.com/jsplumb/community-edition/blob/master/etc/api/core.api.md Represents an overlay for displaying text labels on jsPlumb connections. It provides methods to get and set the label text and manage its dimensions. ```typescript export class LabelOverlay extends Overlay { constructor(instance: JsPlumbInstance, component: Component, p: LabelOverlayOptions); // (undocumented) cachedDimensions: Size; // (undocumented) component: Component; // (undocumented) getDimensions(): Size; // (undocumented) getLabel(): string; // (undocumented) instance: JsPlumbInstance; // (undocumented) label: string | Function; // (undocumented) labelText: string; // (undocumented) setLabel(l: string | Function): void; // (undocumented) static type: string; // (undocumented) type: string; // (undocumented) updateFrom(d: any): void; } ``` -------------------------------- ### Select all Endpoints and set hover state Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Selects all Endpoints on the page and disables their hover effect. No specific setup is required beyond initializing jsPlumb. ```javascript jsPlumb.selectEndpoints().setHover(false); ``` -------------------------------- ### Configure Connection Targets with makeTarget Source: https://context7.com/jsplumb/community-edition/llms.txt Configures elements to accept dropped connections. Supports custom anchor positioning and loopback constraints. ```javascript // Make an element a connection target instance.makeTarget("targetElement", { anchor: "Continuous", endpoint: { type: "Dot", options: { radius: 8 } }, paintStyle: { fill: "#666" }, maxConnections: 5, allowLoopback: false, // Prevent self-connections dropOptions: { hoverClass: "dragHover" // CSS class when dragging over } }) // Target with fixed anchor position based on drop location instance.makeTarget("dropZone", { anchor: { type: "Assign", options: { position: "Fixed" } // Anchor at exact drop position }, endpoint: "Blank" }) // Target with grid-based anchor positioning instance.makeTarget("gridElement", { anchor: { type: "Assign", options: { position: "Grid", grid: [3, 3] } }, deleteEndpointsOnDetach: false, uniqueEndpoint: true }) ``` -------------------------------- ### Add item to dictionary Source: https://github.com/jsplumb/community-edition/blob/master/etc/api/util.api.md Adds a value to an array associated with a key in a record. This is an internal function and should not be used directly. It can optionally insert the item at the start of the array. ```typescript export function addToDictionary(map: Record>, key: string, value: any, insertAtStart?: boolean): Array; ``` -------------------------------- ### Create a Source Endpoint Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/connections.md Initializes an endpoint that acts as a drag source for new connections. ```javascript var endpointOptions = { isSource:true }; var endpoint = jsPlumb.addEndpoint('elementId', endpointOptions); ``` -------------------------------- ### Configure Connection Sources with makeSource Source: https://context7.com/jsplumb/community-edition/llms.txt Transforms elements into connection sources. Use the filter property to restrict drag initiation to specific child elements. ```javascript // Make an element a connection source instance.makeSource("sourceElement", { anchor: "Continuous", endpoint: { type: "Dot", options: { radius: 5 } }, paintStyle: { fill: "#456" }, maxConnections: 3, connectorStyle: { stroke: "#456", strokeWidth: 2 }, connector: { type: "Bezier", options: { curviness: 100 } }, filter: ":not(button)", // Exclude buttons from drag start onMaxConnections: function(params, originalEvent) { alert("Max connections reached: " + params.maxConnections) } }) // Make a source with specific drag filter instance.makeSource("cardElement", { filter: ".drag-handle", // Only drag from elements with this class filterExclude: true, // Exclude instead of include anchor: ["Top", "Bottom", "Left", "Right"], endpoint: "Rectangle", uniqueEndpoint: true // Reuse the same endpoint for all connections }) ``` -------------------------------- ### Endpoints with Different Gradient Styles Source: https://github.com/jsplumb/community-edition/blob/master/doc/paint-styles.md Apply distinct gradient styles to each endpoint of a connector. This is useful for creating visual differentiation between the start and end points of a connection. ```javascript var w23Stroke = 'rgb(189,11,11)'; jsPlumb.connect({ source : 'window2', target : 'window3', paintStyle:{ strokeWidth:8, stroke:w23Stroke }, anchors:[ [0.3,1,0,1], "TopCenter" ], endpoint:"Rectangle", endpointStyles:[{ gradient : { stops:[[0, w23Stroke], [1, '#558822']] } },{ gradient : { stops:[[0, w23Stroke], [1, '#882255']] } }] }); ``` -------------------------------- ### beforeDrag Interceptor Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/interceptors.md Called when the user starts to drag a new connection. Returning false cancels the drag, while returning an object provides data for the new connection. ```APIDOC ## beforeDrag ### Description Called when the user starts to drag a new connection. Returning false aborts the drag; returning an object passes data to the new Connection constructor. ### Parameters - **endpoint** (object) - The Endpoint from which the user is dragging. - **source** (element) - The DOM element the Endpoint belongs to. - **sourceId** (string) - The ID of the DOM element. ``` -------------------------------- ### Import jsPlumb Defaults Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/connections.md Sets global default anchor positions for connections. ```javascript jsPlumb.importDefaults({ Anchors : [ "Left", "BottomRight" ] }); ``` -------------------------------- ### Add item to Map list Source: https://github.com/jsplumb/community-edition/blob/master/etc/api/util.api.md Adds a value to an array associated with a key in a Map. This is an internal function and should not be used directly. It can optionally insert the item at the start of the array. ```typescript export function addToList(map: Map>, key: string, value: any, insertAtStart?: boolean): Array; ``` -------------------------------- ### Dynamic Label Generation with Functions Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/overlays.md Illustrates passing a function to setLabel to dynamically generate label content. ```javascript var conn = jsPlumb.connect({ source:"d1", target:"d2" }); ... conn.setLabel(function(c) { var s = new Date(); return s.getTime() + "milliseconds have elapsed since 01/01/1970"; }); console.log("Label is now", conn.getLabel()); ``` -------------------------------- ### Get Connections with Scope, Source, and Target Filters Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Retrieves connections filtered by a specific scope, source element ID, and target element ID. The return value is a list of connections. ```javascript jsPlumb.getConnections({ scope:'myScope", source:"mySourceElement", target:"myTargetElement" }); ``` -------------------------------- ### Static Anchor with Pixel Offset Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/anchors.md Add pixel offsets to a static anchor definition using [x, y, dx, dy, x_offset, y_offset]. This example adds a 50px offset in the y-axis below the element. ```javascript jsPlumb.connect({...., anchor:[ 0.5, 1, 0, 1, 0, 50 ], ... }); ``` -------------------------------- ### Direct Label Manipulation on Connections Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/overlays.md Shows how to use convenience methods setLabel and getLabel directly on a Connection object. ```javascript var conn = jsPlumb.connect({ source:"d1", target:"d2", label:"FOO" }); ... console.log("Label is currently", conn.getLabel()); conn.setLabel("BAR"); console.log("Label is now", conn.getLabel()); ``` -------------------------------- ### Connect Elements with Perimeter Anchors (Triangle and Diamond) Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/anchors.md Connects two elements using Perimeter anchors with Triangle and Diamond shapes. This example demonstrates specifying different shapes for source and target anchors. ```javascript jsPlumb.connect({ source:"someDiv", target:"someOtherDiv", endpoint:"Dot", anchors:[ [ "Perimeter", { shape:"Triangle" } ], [ "Perimeter", { shape:"Diamond" } ] ] }); ``` -------------------------------- ### Initialize jsPlumb Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/home.md Use these methods to ensure code runs after the DOM is ready. ```javascript jsPlumb.bind("ready", function() { ... // your jsPlumb related init code goes here ... }); ``` ```javascript jsPlumb.ready(function() { ... // your jsPlumb related init code goes here ... }); ``` -------------------------------- ### Get Connections for Multiple Scopes Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Retrieves connections for multiple specified scopes. The return value is a list if only default scope connections exist, otherwise it's a map of scope names to connection lists. ```javascript jsPlumb.getConnections({ scope:["myTestScope", "yourTestScope"] }); ``` -------------------------------- ### Create Basic Connection Source: https://context7.com/jsplumb/community-edition/llms.txt Create a basic visual connection between two DOM elements using default settings. Ensure the source and target elements exist in the DOM. ```javascript // Basic connection with default settings instance.connect({ source: "element1", target: "element2" }) ``` -------------------------------- ### Set Parameters on Connection Source: https://github.com/jsplumb/community-edition/blob/master/doc/parameters.md Pass parameters as an object literal to the `connect` call. These parameters can be any valid JavaScript objects. ```javascript var myConnection = jsPlumb.connect({ source:"foo", target:"bar", parameters:{ "p1":34, "p2":new Date(), "p3":function() { console.log("i am p3"); } } }); ``` -------------------------------- ### Get Connections for a Specific Target Element Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Retrieves connections terminating at a specific target element ID. The return value is a list if only default scope connections exist, otherwise it's a map of scope names to connection lists. ```javascript jsPlumb.getConnections({ target:"myTargetElement" }); ``` -------------------------------- ### Get Connections for Multiple Source Elements Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Retrieves connections originating from any of the specified source element IDs. The return value is a list if only default scope connections exist, otherwise it's a map of scope names to connection lists. ```javascript jsPlumb.getConnections({ source:["mySourceElement", "yourSourceElement"] }); ``` -------------------------------- ### Custom Overlay Configuration Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/overlays.md Details on creating custom overlays using the Custom overlay type. ```APIDOC ## Custom Overlay ### Description Allows creation of custom DOM-based overlays. ### Parameters - **create** (function) - Required - Method that returns a DOM element or selector. - **location** (number) - Optional - Position of the overlay. - **id** (string) - Optional - Unique identifier for retrieval. ``` -------------------------------- ### Get Connections for a Specific Source Element Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Retrieves connections originating from a specific source element ID. The return value is a list if only default scope connections exist, otherwise it's a map of scope names to connection lists. ```javascript jsPlumb.getConnections({ source:"mySourceElement" }); ``` -------------------------------- ### Create Detachable Connection (Default Behavior) Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/connections.md Use this to create a connection that can be detached and reattached by default. No specific parameters are needed as this is the default behavior. ```javascript jsPlumb.connect({ source:"someElement", target:"someOtherElement" }); ``` -------------------------------- ### Get Connections for Specific Source and Target Elements Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/querying.md Retrieves connections originating from a specific source and terminating at any of the specified target element IDs. The return value is a list if only default scope connections exist, otherwise it's a map of scope names to connection lists. ```javascript jsPlumb.getConnections({ source:"mySourceElement", target:["target1", "target2"] }); ``` -------------------------------- ### Create a Basic Programmatic Connection Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/connections.md Establishes a connection between two elements using default jsPlumb settings for endpoints, anchors, and connectors. ```javascript jsPlumb.connect({source:"element1", target:"element2"}); ``` -------------------------------- ### Create a Programmatic Connection Source: https://github.com/jsplumb/community-edition/blob/master/doc/draggable-connections-examples.md Connects two existing Endpoints using a Bezier connector with specific styling. ```javascript jsPlumb.connect({ source:window3Endpoint, target:window4Endpoint, connector: [ "Bezier", { curviness:175 } ], paintStyle:{ strokeWidth:25, stroke:'yellow' } }); ``` -------------------------------- ### Create Custom Styled Connection Source: https://context7.com/jsplumb/community-edition/llms.txt Create a connection with custom styling, anchors, connector type (Bezier), endpoint, and overlays like arrows and labels. Hover styles are also defined. ```javascript // Connection with custom styling and anchors instance.connect({ source: "element1", target: "element2", anchors: ["Right", "Left"], connector: { type: "Bezier", options: { curviness: 150 } }, paintStyle: { stroke: "#5c96bc", strokeWidth: 2 }, hoverPaintStyle: { stroke: "#1e8151", strokeWidth: 3 }, endpoint: "Dot", endpointStyle: { fill: "#5c96bc", radius: 7 }, overlays: [ { type: "Arrow", options: { location: 1, width: 11, length: 11 } }, { type: "Label", options: { label: "Connection", location: 0.5 } } ] }) ``` -------------------------------- ### Configure Connector Types Source: https://context7.com/jsplumb/community-edition/llms.txt Defines Bezier, Straight, Flowchart, and StateMachine connection styles with specific options. ```javascript // Bezier connector (smooth curve) instance.connect({ source: "el1", target: "el2", connector: { type: "Bezier", options: { curviness: 150 } } }) // Straight connector with stub instance.connect({ source: "el1", target: "el2", connector: { type: "Straight", options: { stub: 20, gap: 5 } } }) // Flowchart connector (right-angle paths) instance.connect({ source: "el1", target: "el2", connector: { type: "Flowchart", options: { stub: [40, 60], // Different stub for source/target gap: 10, cornerRadius: 5, alwaysRespectStubs: true, midpoint: 0.5 } } }) // StateMachine connector (for state diagrams, supports loopback) instance.connect({ source: "state1", target: "state2", connector: { type: "StateMachine", options: { curviness: 10, proximityLimit: 80, margin: 5 } } }) ``` -------------------------------- ### Create a Target Endpoint Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/connections.md Initializes an endpoint that acts as a drop target for connections. ```javascript var endpointOptions = { isTarget:true, endpoint:"Rectangle", paintStyle:{ fill:"gray" } }; var endpoint = jsPlumb.addEndpoint("otherElementId", endpointOptions); ``` -------------------------------- ### Instance Creation and Utilities Source: https://github.com/jsplumb/community-edition/blob/master/etc/api/browser-ui.api.md Functions for creating new jsPlumb instances and utility functions for common operations. ```APIDOC ## newInstance ### Description Creates a new jsPlumb instance with optional default configurations. ### Method `newInstance` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **defaults** (BrowserJsPlumbDefaults) - Optional - Default configurations for the new instance. ### Request Example ```javascript const instance = jsPlumb.newInstance(); const instanceWithOptions = jsPlumb.newInstance({ dragOptions: { cursor: 'pointer' } }); ``` ### Response - **BrowserJsPlumbInstance** - A new jsPlumb instance. ## normal ### Description Calculates the normal between two points. ### Method `normal` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **p1** (PointXY) - The first point. - **p2** (PointXY) - The second point. ### Request Example ```javascript const p1 = { x: 10, y: 20 }; const p2 = { x: 30, y: 40 }; const normalValue = jsPlumb.normal(p1, p2); ``` ### Response - **number** - The calculated normal value. ## onDocumentReady ### Description Executes a function once the document is ready. ### Method `onDocumentReady` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **f** (Function) - The function to execute. ### Request Example ```javascript jsPlumb.onDocumentReady(function() { console.log('Document is ready!'); }); ``` ### Response None ``` -------------------------------- ### Comprehensive Connection with Multiple Definitions Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/basic-concepts.md Establishes a connection with custom definitions for anchor, endpoint, connector, and overlays. Common properties can be applied to multiple components. ```javascript var common = { cssClass:"myCssClass" }; jsPlumb.connect({ source:"someDiv", target:"someOtherDiv", anchor:[ "Continuous", { faces:["top","bottom"] }], endpoint:[ "Dot", { radius:5, hoverClass:"myEndpointHover" }, common ], connector:[ "Bezier", { curviness:100 }, common ], overlays: [ [ "Arrow", { foldback:0.2 }, common ], [ "Label", { cssClass:"labelClass" } ] ] }); ``` -------------------------------- ### Label Overlay Configuration Source: https://github.com/jsplumb/community-edition/blob/master/doc/ported/overlays.md Details on the Label overlay constructor arguments and dynamic manipulation methods. ```APIDOC ## Label Overlay ### Description Provides a text label to decorate Connectors. Supports static text or functions returning strings. ### Parameters - **label** (string/function) - Required - The text to display or a function returning a string. - **cssClass** (string) - Optional - CSS class for the label. - **labelStyle** (object) - Optional - Styling object containing font, fill, color, padding, borderWidth, and borderStyle. - **location** (number) - Optional - Position from 0 to 1 or absolute offset. ### Methods - **getLabel()**: Returns the current label content. - **setLabel(content)**: Updates the label content dynamically. ``` -------------------------------- ### Define Overlay Specifications Source: https://github.com/jsplumb/community-edition/blob/master/changelog.md Updated format for defining overlay types and options, replacing the legacy 3-argument syntax. ```javascript overlays:[ [ "Label", { label:"foo" } ] ] ``` ```javascript overlays:[ { type:"Label", options:{ label:"foo" } } ] ``` ```javascript [ "Label", { label:"foo" }, { location:0.2 } ] ``` -------------------------------- ### Overlay Class and Factory Source: https://github.com/jsplumb/community-edition/blob/master/etc/api/browser-ui.api.md Defines the base Overlay class and the factory for creating and managing overlays. ```APIDOC ## Overlay Class ### Description Represents an overlay on a jsPlumb component. This is an abstract class and should be extended. ### Properties - **attributes** (Record) - HTML attributes for the overlay. - **component** (Component) - The jsPlumb component this overlay is attached to. - **cssClass** (string) - CSS class for the overlay. - **events** (Record any>) - Event handlers for the overlay. - **id** (string) - Unique identifier for the overlay. - **instance** (JsPlumbInstance) - The jsPlumb instance. - **location** (number | Array) - The location of the overlay. - **visible** (boolean) - Whether the overlay is currently visible. ### Methods - **isVisible()**: boolean - Checks if the overlay is visible. - **setLocation(l: number | string)**: void - Sets the location of the overlay. - **setVisible(v: boolean)**: void - Sets the visibility of the overlay. - **shouldFireEvent(event: string, value: any, originalEvent?: Event)**: boolean - Determines if an event should be fired. - **updateFrom(d: any)**: void - Updates the overlay from a data object. ### Abstract Methods - **type**: string - The type of the overlay (e.g., 'Label', 'Arrow'). - **updateFrom(d: any)**: void - Abstract method to update overlay properties. ## OverlayFactory ### Description Factory object for creating and registering Overlay instances. ### Methods - **get(instance: JsPlumbInstance, name: string, component: Component, params: any)**: Overlay - Creates and returns an Overlay instance. - **register(name: string, overlay: Constructable)**: void - Registers a new Overlay constructor with a given name. ``` -------------------------------- ### PlainArrowOverlay Class Source: https://github.com/jsplumb/community-edition/blob/master/etc/api/browser-ui.api.md Represents a plain arrow overlay for connections. ```APIDOC ## PlainArrowOverlay Class ### Description An overlay that renders a plain arrow at the end of a connection. It extends the `ArrowOverlay` class. ### Properties - **instance** (JsPlumbInstance) - The JsPlumb instance. - **static type** (string) - The type identifier for this overlay ('PlainArrow'). - **type** (string) - The type identifier for this overlay ('PlainArrow'). ### Constructor - **constructor(instance: JsPlumbInstance, component: Component, p: ArrowOverlayOptions)**: Initializes a new PlainArrowOverlay. ```