🎉 JointJS has new documentation! 🥳
This is the API reference to the open source JointJS core library. If you're looking for the Rappid diagramming toolkit documentation, you can find that here.
JointJS library exports three global variables: joint
, V
and g
.
The joint
namespace contains all the objects that you will use to build your diagrams.
Additionally, joint.version
property tells you which version of JointJS you're using.
The V global is lightweight SVG library that we call Vectorizer
. This tiny library makes manipulation with SVG documents much easier. JointJS uses this library internally. Normally, you don't have to get in touch with this library at all but for advanced uses, it can be handy.
The g global is another lighweight library used internally by JointJS that provides many useful geometry operations. Again, you might not get in touch with this library but when you do have the need to perform geometric operations in your applications, you'll certainly find it helpful.
A link anchor is a point on the paper that the link wants to reach as its endpoint. (In reality, the end element will probably be in the way - then, it will be the job of the connection point function to determine the actual location of the route endpoint taking the respective end element into account.) Anchors are set via an anchor
property provided within link end definitions (i.e. the objects provided to link.source()
and link.target()
functions).
There are many built-in anchor functions in JointJS:
'center'
- default anchor at center of view bbox'modelCenter'
- anchor at center of model bbox'perpendicular'
- anchor that ensures an orthogonal route to the other endpoint'midSide'
- anchor in the middle of the side of view bbox closest to the other endpoint'bottom'
- anchor in the middle of the bottom side of view bbox'left'
- anchor in the middle of the left side of view bbox'right'
- anchor in the middle of the right side of view bbox'top'
- anchor in the middle of the top side of view bbox'bottomLeft'
- anchor at the bottom-left corner of view bbox'bottomRight'
- anchor at the bottom-right corner of view bbox'topLeft'
- anchor at the top-left corner of view bbox'topRight'
- anchor at the top-right corner of view bboxExample:
link.source(model, {
anchor: {
name: 'midSide',
args: {
rotate: true,
padding: 20
}
}
});
The default anchor function is 'center'
; this can be changed with the defaultAnchor
paper option. Example:
paper.options.defaultAnchor = {
name: 'midSide',
args: {
rotate: true,
padding: 20
}
};
JointJS also contains mechanisms to define one's own custom anchor functions.
The 'bottom'
anchor function places the anchor of the link in the middle of the bottom side of the view bbox. It accepts three arguments, which can be passed within the anchor.args
property:
rotate | boolean | Should the anchor bbox rotate with the end view? Default is false , meaning that the unrotated bbox is used. |
---|---|---|
dx | number | Offset the anchor by dx . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
dy | number | Offset the anchor by dy . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
Example:
link.source(model, {
anchor: {
name: 'bottom',
args: {
rotate: true,
dx: 10,
dy: '40%'
}
}
});
The 'bottomLeft'
anchor function places the anchor of the link at the bottom-left corner of the view bbox. It accepts three arguments, which can be passed within the anchor.args
property:
rotate | boolean | Should the anchor bbox rotate with the end view? Default is false , meaning that the unrotated bbox is used. |
---|---|---|
dx | number | Offset the anchor by dx . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
dy | number | Offset the anchor by dy . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
Example:
link.source(model, {
anchor: {
name: 'bottomLeft',
args: {
rotate: true,
dx: 10,
dy: '40%'
}
}
});
The 'bottomRight'
anchor function places the anchor of the link at the bottom-left corner of the view bbox. It accepts three arguments, which can be passed within the anchor.args
property:
rotate | boolean | Should the anchor bbox rotate with the end view? Default is false , meaning that the unrotated bbox is used. |
---|---|---|
dx | number | Offset the anchor by dx . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
dy | number | Offset the anchor by dy . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
Example:
link.source(model, {
anchor: {
name: 'bottomRight',
args: {
rotate: true,
dx: 10,
dy: '40%'
}
}
});
The 'center'
anchor function is the default anchor function. It places the anchor of the link at center of the view bbox. It accepts three arguments, which can be passed within the anchor.args
property:
rotate | boolean | Should the anchor bbox rotate with the end view? Default is false , meaning that the unrotated bbox is used. |
---|---|---|
dx | number | Offset the anchor by dx . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
dy | number | Offset the anchor by dy . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
Example:
link.source(model, {
anchor: {
name: 'center',
args: {
rotate: true,
dx: 10,
dy: '40%'
}
}
});
New anchor functions can be defined in the joint.anchors
namespace (e.g. joint.anchors.myAnchor
) or passed directly as a function to the anchor
property of link source/target (or to the defaultAnchor
option of a paper).
In either case, the anchor function must return the anchor as a Point. The function is expected to have the form function(endView, endMagnet, anchorReference, args)
:
endView | dia.ElementView | The ElementView to which we are connecting. The Element model can be accessed as endView.model ; this may be useful for writing conditional logic based on element attributes. |
---|---|---|
endMagnet | SVGElement | The SVGElement in our page that contains the magnet (element/subelement/port) to which we are connecting. |
anchorReference | g.Point | A reference to another component of the link path that may be necessary to find this anchor point. If we are calling this method for a source anchor, it is the first vertex, or if there are no vertices the target anchor. If we are calling this method for a target anchor, it is the last vertex, or if there are no vertices the source anchor... |
SVGElement | ...if the anchor in question does not exist (yet), it is that link end's magnet. | |
args | object | An object with additional optional arguments passed to the anchor method by the user when it was called (the args property). |
The 'left'
anchor function places the anchor of the link in the middle of the left side of the view bbox. It accepts three arguments, which can be passed within the anchor.args
property:
rotate | boolean | Should the anchor bbox rotate with the end view? Default is false , meaning that the unrotated bbox is used. |
---|---|---|
dx | number | Offset the anchor by dx . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
dy | number | Offset the anchor by dy . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
Example:
link.source(model, {
anchor: {
name: 'left',
args: {
rotate: true,
dx: 10,
dy: '40%'
}
}
});
The 'midSide'
anchor function places the anchor of the link in the middle of the side of view bbox closest to the other endpoint. It accepts two arguments, which can be passed within the anchor.args
property:
rotate | boolean | Should the anchor bbox rotate with the end view? Default is false , meaning that the unrotated bbox is used. |
---|---|---|
padding | number | Offset the anchor by padding away from view bbox. Default is 0 . |
Example:
link.source(model, {
anchor: {
name: 'midSide',
args: {
rotate: true,
padding: 20
}
}
});
The 'modelCenter'
anchor function places the anchor of the link at center of the model bbox.
Example:
link.source(model, {
anchor: {
name: 'modelCenter'
}
});
The 'perpendicular'
anchor function tries to place the anchor of the link inside the view bbox so that the link is made orthogonal. The anchor is placed along two line segments inside the view bbox (between the centers of the top and bottom side and between the centers of the left and right sides). If it is not possible to place the anchor so that the link would be orthogonal, the anchor is placed at the center of the view bbox instead. The function accepts one argument, which can be passed within the anchor.args
property:
padding | number | Limit the area inside the view bbox available for placing the anchor by padding . Default is 0 . |
---|
Example:
link.source(model, {
anchor: {
name: 'perpendicular',
args: {
padding: 10
}
}
});
The 'right'
anchor function places the anchor of the link in the middle of the right side of the view bbox. It accepts three arguments, which can be passed within the anchor.args
property:
rotate | boolean | Should the anchor bbox rotate with the end view? Default is false , meaning that the unrotated bbox is used. |
---|---|---|
dx | number | Offset the anchor by dx . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
dy | number | Offset the anchor by dy . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
Example:
link.source(model, {
anchor: {
name: 'right',
args: {
rotate: true,
dx: 10,
dy: '40%'
}
}
});
The 'top'
anchor function places the anchor of the link in the middle of the top side of the view bbox. It accepts three arguments, which can be passed within the anchor.args
property:
rotate | boolean | Should the anchor bbox rotate with the end view? Default is false , meaning that the unrotated bbox is used. |
---|---|---|
dx | number | Offset the anchor by dx . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
dy | number | Offset the anchor by dy . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
Example:
link.source(model, {
anchor: {
name: 'top',
args: {
rotate: true,
dx: 10,
dy: '40%'
}
}
});
The 'topLeft'
anchor function places the anchor of the link at the top-left corner of the view bbox. It accepts three arguments, which can be passed within the anchor.args
property:
rotate | boolean | Should the anchor bbox rotate with the end view? Default is false , meaning that the unrotated bbox is used. |
---|---|---|
dx | number | Offset the anchor by dx . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
dy | number | Offset the anchor by dy . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
Example:
link.source(model, {
anchor: {
name: 'topLeft',
args: {
rotate: true,
dx: 10,
dy: '40%'
}
}
});
The 'topRight'
anchor function places the anchor of the link at the top-right corner of the view bbox. It accepts three arguments, which can be passed within the anchor.args
property:
rotate | boolean | Should the anchor bbox rotate with the end view? Default is false , meaning that the unrotated bbox is used. |
---|---|---|
dx | number | Offset the anchor by dx . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
dy | number | Offset the anchor by dy . Default is 0 . |
string | Percentage strings (e.g. '40%' ) are also accepted. |
Example:
link.source(model, {
anchor: {
name: 'topRight',
args: {
rotate: true,
dx: 10,
dy: '40%'
}
}
});
A link connection point is an endpoint of the link route. This point is (usually) different from the link anchor point, as it takes into account the presence of the end element. Connection points are set via an connectionPoint
property provided within link end definitions (i.e. the objects provided to link.source()
and link.target()
functions).
The built-in functions work by finding an intersection between the link path (the path from the link's source anchor, through its vertices, to its target anchor). However, the functions always only have access to a single path segment; the source connectionPoint is found by investigating the first segment (i.e. source anchor - first vertex, or source anchor - target anchor if there are no vertices), while the target connectionPoint is found by investigating the last segment (i.e. last vertex - target anchor, or source anchor - target anchor). This has consequences if the investigated path segment is entirely contained within the end element.
There are four built-in connection point functions in JointJS:
'anchor'
- connection point at anchor'bbox'
- default connection point at bbox boundary'boundary'
- connection point at actual shape boundary'rectangle'
- connection point at unrotated bbox boundaryExample:
link.source(model, {
connectionPoint: {
name: 'boundary',
args: {
sticky: true
}
}
});
The default connection point is 'bbox'
; this can be changed with the defaultConnectionPoint
paper option. Example:
paper.options.defaultConnectionPoint = {
name: 'boundary',
args: {
sticky: true
}
};
All four of the built-in connection point functions accept the following optional argument, in addition to their own arguments:
offset | number | Offset the connection point from the anchor by the specified distance along the end link path segment. Default is 0 . |
---|
Example:
link.source(model, {
connectionPoint: {
name: 'bbox',
args: {
offset: 10
}
}
});
JointJS also contains mechanisms to define one's own custom connection point functions.
The 'anchor'
connection point function is the simplest connection point function. It places the connection point at the link end's anchor point (determined either by the anchor
function or by the defaultAnchor
paper option).
Example:
link.source(model, {
connectionPoint: {
name: 'anchor',
args: {
offset: 10
}
}
});
The 'bbox'
connection point function is the default connection point function. It places the connection point at the intersection between the link path end segment and the end element bbox. It accepts one additional argument, which can be passed within the connectionPoint.args
property:
stroke | boolean | Should the stroke width be included when calculating the connection point? Default is false . |
---|
Example:
link.source(model, {
connectionPoint: {
name: 'bbox',
args: {
offset: 10,
stroke: true
}
}
});
The 'boundary'
connection point function places the connection point at the intersection between the link path end segment and the actual shape of the end element. (If JointJS is unable to determine the actual shape - e.g. for text - the element bbox is used instead, just as in the 'bbox'
connection point function.) It accepts six additional arguments, which can be passed within the connectionPoint.args
property:
insideout | boolean | What happens if the link path never leaves the interior area of the end element (e.g. because the other end anchor lies within the first end element)? Should the path line be extended until an intersection with the boundary is found? Default is true . |
---|---|---|
extrapolate | boolean | What happens if the link path never enters the interior area of the end element (e.g. because the anchor lies outside the end element)? Should the path line be extended to try and find the boundary? Default is false . Note that even if this option is true , an intersection is still not guaranteed. This option takes precedence over connectionPoint.args.sticky . |
sticky | boolean | What happens if the link path never enters the interior area of the end element (e.g. because the anchor lies outside the end element)? Should the closest point on the end element boundary be used instead? Default is false . Note that setting this option to true guarantees that a connection point will be found on the shape boundary. |
precision | number | The precision of the path intersection algorithm. Uses a logarithmic scale; increasing the number by 1 reduces the maximum observed error by a factor of ten. Default is 2 , corresponding to 1% error. |
selector | string | A selector to identify subelement/magnet of the end element at whose boundary we want the connection point to be found. Default is undefined , meaning that the first non-group descendant of the end element's node will be considered. (An example of another setting that may be useful is 'root' , which forces the usage of the root group bbox instead.) |
stroke | boolean | Should the stroke width be included when calculating the connection point? Default is false . |
Example:
link.source(model, {
connectionPoint: {
name: 'boundary',
args: {
offset: 10,
insideout: false,
extrapolate: true,
sticky: true,
precision: 3,
stroke: true
}
}
});
New connection point function can be defined in the joint.connectionPoints
namespace (e.g. joint.connectionPoints.myConnectionPoint
) or passed directly as a function to the connectionPoint
property of link source/target (or to the defaultConnectionPoint
option of a paper).
In either case, the connection point function must return the connection point as a Point. The function is expected to have the form function(endPathSegmentLine, endView, endMagnet, args)
:
endPathSegmentLine | g.Line | The link path segment at which we are finding the connection point. If we are calling this method for a source connection point, it is the first segment (source anchor - first vertex, or source anchor - target anchor). If we are calling this method for a target connection point, it is the last segment (last vertex - target anchor, or source anchor - target anchor). |
---|---|---|
endView | dia.ElementView | The ElementView to which we are connecting. The Element model can be accessed as endView.model ; this may be useful for writing conditional logic based on element attributes. |
endMagnet | SVGElement | The SVGElement in our page that contains the magnet (element/subelement/port) to which we are connecting. |
args | object | An object with additional optional arguments passed to the connection point method by the user when it was called (the args property). |
The 'rectangle'
connection point function places the connection point at the intersection between the link path end segment and the element's unrotated bbox. It accepts one additional argument, which can be passed within the connectionPoint.args
property:
stroke | boolean | Should the stroke width be included when calculating the connection point? Default is false . |
---|
Example:
link.source(model, {
connectionPoint: {
name: 'rectangle',
args: {
offset: 10,
stroke: true
}
}
});
Connection strategies come into play when the user modifies the position of link endpoints. There are two situations in which this is relevant:
anchor
property that might have been assigned on the dragged link endpoint will be overridden by the connection strategy. If necessary, have a look at the custom connectionStrategy documentation for information on replicating the functionality of anchor functions.)Both the anchor
and connectionPoint
properties are rewritten in response to user interaction. None of the built-in connection strategies preserve the originally assigned anchor and connection point functions. To assign precisely what you need as the anchor and connection point functions, you may need to define your own custom connection strategy.
Connection strategies are not assigned on a link-by-link basis. They are set with the connectionStrategy
option on a paper.
There are three built-in connection strategies in JointJS:
useDefaults
- default strategy; ignore user pointer and use default anchor and connectionPoint functionspinAbsolute
- use user pointer coordinates to position anchor absolutely within end element; use default connectionPointpinRelative
- use user pointer coordinates to position anchor relatively within end element; use default connectionPointThe default connection strategy is specified as null
in paper settings, which is equivalent to joint.connectionStrategies.useDefaults
.
joint.connectionStrategies
namespace. Example:
paper.options.connectionStrategy = joint.connectionStrategies.pinAbsolute;
New connection strategies can be defined in the joint.connectionStrategies
namespace (e.g. joint.connectionStrategies.myConnectionStrategy
) or passed directly as a function to the connectionStrategy
option of a paper.
In either case, the connection strategy function must return an end definition (i.e. an object in the format supplied to the link.source()
and link.target()
functions). The function is expected to have the form function(endDefinition, endView, endMagnet, coords)
:
endDefinition | object | An end definition; the output of the appropriate end function (link.source() or link.target() ). An object containing at least an id of the Element to which we are connecting. This object is expected to be changed by this function and then sent as the return value. |
---|---|---|
endView | dia.ElementView | The ElementView to which we are connecting. The Element model can be accessed as endView.model ; this may be useful for writing conditional logic based on element attributes. |
endMagnet | SVGElement | The SVGElement in our page that contains the magnet (element/subelement/port) to which we are connecting. |
coords | g.Point | A Point object recording the x-y coordinates of the user pointer when the connection strategy was invoked. |
Custom connection strategies may be enormously useful for your users. Here we provide some examples of custom functionality.
If your diagram makes heavy use of nested elements, it may be useful to always connect links to a top-level ancestor element (instead of the element on which the arrowhead was actually dropped by user interaction):
joint.connectionStrategies.topAncestor = function(end, endView) {
var ancestors = endView.model.getAncestors();
var numAncestors = ancestors.length;
var end = numAncestors ? ancestors[numAncestors - 1] : end;
return end;
}
paper.options.connectionStrategy = joint.connectionStrategies.topAncestor;
If your diagram uses ports, you usually do not want links to be able to connect anywhere else. The solution is similar to the one above:
joint.connectionStrategies.firstPort = function(end, endView) {
var ports = endView.model.getPorts();
var numPorts = ports.length;
var end = numPorts ? { id: end.id, port: ports[0].id } : end;
return end;
}
paper.options.connectionStrategy = joint.connectionStrategies.firstPort;
Furthermore, it is very easy to replicate the built-in anchor functions for connection strategy scenarios - simply apply the anchor function to the received end
parameter:
joint.connectionStrategy.midSide = function(end) {
end.anchor = {
name: 'midSide',
args: {
rotate: true
}
};
return end;
}
paper.options.connectionStrategy = joint.connectionStrategy.midSide;
What if we needed to replicate a built-in connection point function instead? We use the same idea as in the previous example:
joint.connectionStrategy.boundary = function(end) {
end.connectionPoint = {
name: 'boundary',
args: {
offset: 5
}
};
return end;
}
paper.options.connectionStrategy = joint.connectionStrategy.boundary;
Of course, it is also possible to combine both of the examples and assign an anchor
as well as connectionPoint
to the end
parameter of the modified link.
The pinAbsolute
connection strategy records the coordinates of user pointer and assigns the end anchor absolutely, by reference to the top-left corner of the view bbox of the element above which the endpoint was dropped. Absolute positioning ensures that if the element is subsequently resized, the anchor stays at the same absolute distance from the edges (e.g. staying 10 pixels away from the left side and 20 pixels away from the top side).
The end connection point is assigned according to defaultConnectionPoint
paper option.
Example:
paper.options.connectionStrategy = joint.connectionStrategies.pinAbsolute;
The end (source or target) that is being modified gets the 'topLeft'
anchor assigned by this connection strategy:
end.anchor = {
name: 'topLeft',
args: {
rotate: true
dx: (coords.x - bbox.x),
dy: (coords.y - bbox.y)
}
};
The pinRelative
connection strategy records the coordinates of user pointer and assigns the end anchor relatively, by reference to the top-left corner of the view bbox of the element above which the endpoint was dropped. Relative positioning ensures that if the element is subsequently resized, the anchor stays at the same relative distance from the edges (e.g. staying 25% of the way from the left side and 75% of the way from the top side).
The end connection point is assigned according to defaultConnectionPoint
paper option.
Example:
paper.options.connectionStrategy = joint.connectionStrategies.pinRelative;
The end (source or target) that is being modified gets the 'topLeft'
anchor assigned by this connection strategy:
end.anchor = {
name: 'topLeft',
args: {
rotate: true
dx: percentageString(coords.x - bbox.x),
dy: percentageString(coords.y - bbox.y)
}
};
The useDefaults
connection strategy is the simplest connection strategy. It ignores the coordinates of user pointer and assigns the end anchor according to the defaultAnchor
paper option and the end connection point according to the defaultConnectionPoint
paper option.
Thus, this connection strategy is equivalent to a connection strategy of null
.
Example:
paper.options.connectionStrategy = joint.connectionStrategies.useDefaults;
Connectors take an array of link route points and generate SVG path commands so that the link can be rendered. The connector
property of a link can be accessed with the link.connector()
function.
There are four built-in connectors in JointJS:
'jumpover'
- connector with bridges over link intersections'normal'
- default simple connector'rounded'
- connector with rounded edges'smooth'
- connector interpolated as a bezier curveExample:
link.connector('rounded', {
radius: 20
});
The default connector is 'normal'
; this can be changed with the defaultConnector
paper option. Example:
paper.options.defaultConnector = {
name: 'rounded',
args: {
radius: 20
}
}
All four of the built-in connectors accept the following optional argument, in addition to their own arguments:
raw | boolean | Should the router return the connection path as a g.Path rather than as a string? Default is false . |
---|
Example:
link.connector('normal', {
raw: true
});
JointJS also contains mechanisms to define one's own custom connectors.
Note that the modular architecture of JointJS allows mixing-and-matching connectors with routers as desired; for example, a link may be specified to use the 'jumpover'
connector on top of the 'manhattan'
router:
var link = new joint.shapes.standard.Link();
link.source(rect);
link.target(rect2);
link.router('manhattan');
link.connector('jumpover');
New connectors can be defined in the joint.connectors
namespace (e.g. joint.connectors.myConnector
) or passed directly as a function to the connector
property of a link (or to the defaultConnector
paper option).
In either case, the connector function must return a g.Path representing the SVG path data that will be used to render the link. The function is expected to have the form function(sourcePoint, targetPoint, routePoints, args)
:
sourcePoint | g.Point | The source connection point. |
---|---|---|
targetPoint | g.Point | The target connection point. |
routePoints | Array<g.Point> | The points of the route, as returned by the router in use. |
args | object | An object with additional optional arguments passed to the connector method by the user when it was called (the args property). |
Example of a connector defined in the joint.connectors
namespace:
joint.connectors.wobble = function(sourcePoint, targetPoint, vertices, args) {
var SPREAD = args.spread || 20;
var points = vertices.concat(targetPoint)
var prev = sourcePoint;
var path = new g.Path(g.Path.createSegment('M', prev));
var n = points.length;
for (var i = 0; i < n; i++) {
var next = points[i];
var distance = prev.distance(next);
var d = SPREAD;
while (d < distance) {
var current = prev.clone().move(next, -d);
current.offset(
Math.floor(7 * Math.random()) - 3,
Math.floor(7 * Math.random()) - 3
);
path.appendSegment(g.Path.createSegment('L', current));
d += SPREAD;
}
path.appendSegment(g.Path.createSegment('L', next));
prev = next;
}
return path;
}
var link = new joint.shapes.standard.Link();
link.source(source);
link.target(target);
link.connector('wobble', {
spread: 10
});
An example of a connector passed as a function is provided below. Notice that this approach does not enable passing custom args
nor can it be serialized with the graph.toJSON()
function.
var link = new joint.shapes.standard.Link();
link.source(source);
link.target(target);
link.connector(function(sourcePoint, targetPoint, vertices, args) {
var SPREAD = 20;
var points = vertices.concat(targetPoint)
var prev = sourcePoint;
var path = new g.Path(g.Path.createSegment('M', prev));
var n = points.length;
for (var i = 0; i < n; i++) {
var next = points[i];
var distance = prev.distance(next);
var d = SPREAD;
while (d < distance) {
var current = prev.clone().move(next, -d);
current.offset(
Math.floor(7 * Math.random()) - 3,
Math.floor(7 * Math.random()) - 3
);
path.appendSegment(g.Path.createSegment('L', current));
d += SPREAD;
}
path.appendSegment(g.Path.createSegment('L', next));
prev = next;
}
return path;
});
The 'jumpover'
connector draws straight lines with small arcs in place of link-link intersections. (For the time being, it cannot detect intersections with 'smooth'
router links). It accepts the following additional arguments, which can be passed as the connector.args
property:
size | number | The size of the jump (the diameter of the arc, or the length of the empty spot on the line). Defaults to 5 . |
---|---|---|
jump | string | The style of the jump. Either 'arc' (using an Arcto SVG path command), 'cubic' (using a Curveto path command as a normalized approximation to Arcto), or 'gap' (leaving a blank space). Defaults to 'arc' . |
Example:
link.connector('jumpover', {
type: 'gap'
});
The 'normal'
connector is the default connector for links and it is the simplest connector. It simply connects provided route points with straight-line segments.
Example:
link.connector('normal');
The 'rounded'
connector connects provided route points with straight lines while smoothing all corners on the route. It accepts one additional argument, which can be passed within the connector.args
property:
radius | boolean | The curve radius of the rounded corners. Default is 10 . |
---|
Example:
link.connector('rounded', {
radius: 20
});
The 'smooth'
connector interpolates route points using a cubic bezier curve.
Example:
link.connector('smooth');
(Deprecated) For the purposes of backwards compatibility, the 'smooth'
connector may also be enabled by setting the link.smooth
property to true
.
// deprecated
link.set('smooth', true)
The attributes in JointJS define how the graphics elements are to be rendered inside of the element and link views.
All the standard SVG styling properties are available (both kebab-case
and camelCase
styles).
In addition JointJS defines new so-called "special" attributes and allows programmers to define their own. Here is the list of all built-in attributes.
Move the subelement to the point at a given distance along the connection path but do not auto-orient it according to the path's gradient. Use a positive number to define the distance from the source of the link and a negative number from the target of the link. It is valid only within the LinkView context.
link.attr('rectSelector', { atConnectionLengthIgnoreGradient: 30, width: 10, height: 10, fill: 'red' });
alias: atConnectionLength
Move and auto-orient the subelement to the point at a given distance along the connection path. Use a positive number to define the distance from the source of the link and a negative number from the target of the link. It is valid only within the LinkView context.
link.attr('rectSelector', { atConnectionLength: 30, width: 10, height: 10, fill: 'red' });
link.attr('rectSelector', { atConnectionLengthKeepGradient: 30, width: 10, height: 10, fill: 'red' });
Move the subelement to the point at a given ratio of the connection total length but do not auto-orient it according to the path's gradient. It accepts a number in the [0,1]
range. It is valid only within the LinkView context.
link.attr('rectSelector', { atConnectionRatioKeepGradient: .5, width: 10, height: 10, fill: 'red' });
alias: atConnectionRatio
Move and auto-orient the subelement to the point at a given ratio of the connection total length. It accepts a number in the [0,1]
range. It is valid only within the LinkView context.
link.attr('rectSelector', { atConnectionRatio: .5, width: 10, height: 10, fill: 'red' });
link.attr('rectSelector', { atConnectionRatioKeepGradient: .5, width: 10, height: 10, fill: 'red' });
Set the 'd'
attribute based on the current link connection (the result of the link`s connector). It's valid only for SVGPathElement
within the LinkView context.
link.attr('pathSelector', { connection: true, stroke: 'red', fill: 'none' });
The event
attribute makes the selected node and its descendants trigger an arbitrary event when clicked (mousedown/touchstart).
This event is triggered on the view itself and the paper.
The paper handler is called with the signature cellView
, evt
, x
, y
,
while the cell view handler is called only with evt
, x
, y
.
element.attr({
image: {
// pointerdown on the image SVG node will trigger the `element:delete` event
event: 'element:delete',
xlinkHref: 'trash.png'
width: 20,
height: 20
}
});
// Binding handler to the event
paper.on('element:delete', function(elementView, evt) {
// Stop any further actions with the element view e.g. dragging
evt.stopPropagation();
if (confirm('Are you sure you want to delete this element?')) {
elementView.model.remove();
}
});
The fill
attribute becomes a special attribute only in case it's defined as an object, instead of the usual SVG syntax (e.g. "#ffaabb"
).
If it's defined as an object, it is assumed to be a gradient definition and must have the form defined by the defineGradient() paper method.
element.attr('rect/fill', {
type: 'linearGradient',
stops: [
{ offset: '0%', color: '#E67E22' },
{ offset: '20%', color: '#D35400' },
{ offset: '40%', color: '#E74C3C' },
{ offset: '60%', color: '#C0392B' },
{ offset: '80%', color: '#F39C12' }
]
});
The filter
attribute becomes a special attribute only in case it's defined as an object, instead of the usual SVG syntax (e.g. "url(#myfilter)"
).
If it's defined as an object, it must have the form defined by by the filterGradient() paper method.
element.attr('rect/filter', {
name: 'dropShadow',
args: {
dx: 2,
dy: 2,
blur: 3
}
});
When set to true
, the subelement can become a source/target of a link during link reconnection. Useful for
so called 'ports'.
An object containing at least an id
property. This property uniquely identifies the port.
If a link gets connected to a magnet that has also a port
object defined, the id
property of the port object will be copied to the port
property
of the source/target of the link.
CSS selector pointing to an element that is used as a reference for relative positioning attributes.
Set cx
attribute of the subelement relatively to the width of the element referenced to by the selector in ref
attribute.
If the value is in the [0, 1]
interval (or expressed in percentages, e.g. '80%'
), the cx
of the subelement will be set as a percentage
of the width of the referenced element. If the value is <0
or >1
, the height
of the subelement will be smaller/bigger than the width of the referenced element by the amount specified.
Note that this makes sense only for SVG elements that support rx
and ry
attributes, such
as <ellipse>
.
Set cy
attribute of the subelement relatively to the height of the element referenced to by the selector in ref
attribute.
If the value is in the [0, 1]
interval (or expressed in percentages, e.g. '80%'
), the cy
of the subelement will be set as a percentage
of the height of the referenced element. If the value is <0
or >1
, the height
of the subelement will be smaller/bigger than the height of the referenced element by the amount specified.
Note that this makes sense only for SVG elements that support rx
and ry
attributes, such
as <ellipse>
.
Set d
attribute of the <path>
subelement relatively to the dimensions and position of the element referenced by the selector in the ref
attribute. The refD
path data is scaled so that the path's dimensions match the reference element's dimensions, and translated so that the path's origin matches the origin of the reference element.
The original path data offset is preserved. This means that if the top-left corner of the refD
bounding box does not lie at 0,0
, the gap between the path and origin is preserved in the rendered shape, as well.
var Path = joint.dia.Element.define('examples.Path', {
attrs: {
path: {
refDKeepOffset: 'M 10 10 30 10 30 30 z', // path offset is 10,10
fill: 'red',
stroke: 'black'
}
}
}, {
markup: 'path'
});
var p = (new Path()).resize(40, 40).addTo(graph);
// the rendered path's `d` attribute will be 'M 10 10 50 10 50 50 z'
// can be obtained by `p.findView(paper).vel.findOne('path').attr('d');`
alias: refD
Set d
attribute of the <path>
subelement relatively to the dimensions and position of the element referenced by the selector in the ref
attribute. The refD
path data is scaled so that the path's dimensions match the reference element's dimensions, and translated so that the path's origin matches the origin of the reference element.
The original path data offset is not preserved. This means that if the top-left corner of the refD
bounding box does not lie at 0,0
, the path is translated so that this gap disappears. The rendered path then fits perfectly into the reference element's bounding box.
var Path = joint.dia.Element.define('examples.Path', {
attrs: {
path: {
refDResetOffset: 'M 10 10 30 10 30 30 z', // path offset of 10,10 will be discarded
fill: 'red',
stroke: 'black'
}
}
}, {
markup: 'path'
});
var p = (new Path()).resize(40, 40).addTo(graph);
// the rendered path's `d` attribute will be 'M 0 0 40 0 40 40 z'
// can be obtained by `p.findView(paper).vel.findOne('path').attr('d');`
alias: ref-dx
Make x-coordinate of the subelement relative to the right edge of the element referenced to by the selector in ref
attribute.
Make y-coordinate of the subelement relative to the bottom edge of the element referenced to by the selector in ref
attribute.
alias: ref-height
Set height of the subelement relatively to the height of the element referenced to by the selector in ref
attribute.
If the value is in the [0, 1]
interval (or expressed in percentages, e.g. '80%'
), the height of the subelement will be set as a percentage
of the height of the referenced element. If the value is <0
or >1
, the height
of the subelement will be smaller/bigger than the height of the referenced element by the amount specified.
Note that this makes sense only for SVG elements that support width
and height
attributes, such
as <rect>
.
Same as refHeight
. Useful when one needs to resize an element absolutely and relatively at the same time. Note that all percentages are relative to 100% of the referenced height.
{ refHeight: 20, refHeight2: '-75%' } // resizes the element to 25% of the reference height (25% = 100% - 75%) plus extra 20 pixels
Set the points
attribute of the <polygon>
or <polyline>
subelement relatively to the dimensions and position of the element referenced by the selector in the ref
attribute. The refPoints
are scaled so that the subelement's dimensions match the reference element's dimensions, and translated so that the their origin matches the origin of the reference element.
The original points offset is preserved. This means that if the top-left corner of the refPoints
bounding box does not lie at 0,0
, the gap between the points and origin is preserved in the rendered shape, as well.
var Polygon = joint.dia.Element.define('examples.Polygon', {
attrs: {
polygon: {
refPoints: '10,10 30,10 30,30', // points offset is 10,10
fill: 'red',
stroke: 'black'
}
}
}, {
markup: 'polygon'
});
var p = (new Polygon()).resize(40, 40).addTo(graph);
// the rendered polygon's `points` attribute will be '10,10 50,10 50,50'
// can be obtained by `p.findView(paper).vel.findOne('polygon').attr('points');`
alias: refPoints
Set the points
attribute of the <polygon>
or <polyline>
subelement relatively to the dimensions and position of the element referenced by the selector in the ref
attribute. The refPoints
are scaled so that the subelement's dimensions match the reference element's dimensions, and translated so that the their origin matches the origin of the reference element.
The original points offset is not preserved. This means that if the top-left corner of the refPoints
bounding box does not lie at 0,0
, the subelement is translated so that this gap disappears. The rendered subelement then fits perfectly into the reference element's bounding box.
var Polygon = joint.dia.Element.define('examples.Polygon', {
attrs: {
polygon: {
refPoints: '10,10 30,10 30,30', // points offset of 10,10 will be discarded
fill: 'red',
stroke: 'black'
}
}
}, {
markup: 'polygon'
});
var p = (new Polygon()).resize(40, 40).addTo(graph);
// the rendered polygon's `points` attribute will be '0,0 40,0 40,40'
// can be obtained by `p.findView(paper).vel.findOne('polygon').attr('d');`
Set the r
attribute of the subelement relatively to the circumscribed size (length of the diagonal of the bounding box) of the element referenced by the selector in the ref
attribute. If the value is in the [0, 1]
interval (or expressed in percentages, e.g. '80%'
), the r
of the subelement will be set as a percentage of the size of the referenced element. If the value is <0
or >1
, the size of the subelement will be smaller/bigger than the size of the referenced element by the amount specified. Note that this makes sense only for SVG elements that support r
attribute, such as <circle>
.
alias: refR
Set the r
attribute of the subelement relatively to the inscribed size (width or height of the bounding box, whichever is smaller) of the element referenced by the selector in the ref
attribute. If the value is in the [0, 1]
interval (or expressed in percentages, e.g. '80%'
), the r
of the subelement will be set as a percentage of the size of the referenced element. If the value is <0
or >1
, the size of the subelement will be smaller/bigger than the size of the referenced element by the amount specified. Note that this makes sense only for SVG elements that support r
attribute, such as <circle>
.
Set rx
attribute of the subelement relatively to the width of the element referenced to by the selector in ref
attribute.
If the value is in the [0, 1]
interval (or expressed in percentages, e.g. '80%'
), the rx
of the subelement will be set as a percentage
of the width of the referenced element. If the value is <0
or >1
, the height
of the subelement will be smaller/bigger than the width of the referenced element by the amount specified.
Note that this makes sense only for SVG elements that support rx
and ry
attributes, such
as <ellipse>
.
Set ry
attribute of the subelement relatively to the height of the element referenced to by the selector in ref
attribute.
If the value is in the [0, 1]
interval (or expressed in percentages, e.g. '80%'
), the ry
of the subelement will be set as a percentage
of the height of the referenced element. If the value is <0
or >1
, the height
of the subelement will be smaller/bigger than the height of the referenced element by the amount specified.
Note that this makes sense only for SVG elements that support rx
and ry
attributes, such
as <ellipse>
.
alias: ref-width
Set width of the subelement relatively to the width of the element referenced to by the selector in ref
attribute.
If the value is in the [0, 1]
interval (or expressed in percentages, e.g. '80%'
), the width of the subelement will be set as a percentage
of the width of the referenced element. If the value is <0
or >1
, the width
of the subelement will be smaller/bigger than the width of the referenced element by the amount specified.
For example, 'ref-width': .75
sets the width of the subelement to 75%
of the width of the referenced element.
'ref-width': 20
makes the width to be 20px
less than the width of the referenced element.
Note that this makes sense only for SVG elements that support width
and height
attributes, such
as <rect>
.
Same as refWidth
. Useful when one needs to resize an element absolutely and relatively at the same time. Note that all percentages are relative to 100% of the referenced width.
{ refWidth: 20, refWidth2: '-75%' } // resizes the element to 25% of the reference width (25% = 100% - 75%) plus extra 20 pixels
alias: ref-x
Make x-coordinate of the subelement relative to the x-coordinate of the element referenced to by the selector in ref
attribute.
If ref-x
is in the (0,1)
interval (or expressed in percentages, e.g. '80%'
), the offset is
calculated from the fraction of the bounding box of the referenced element. Otherwise, it is an absolute value in pixels.
Same as refX
. Useful when one needs to position an element absolutely and relatively at the same time.
{ refX: '50%', refX2: 20 } // moves the element by 50% of the referenced width plus extra 20 pixels.
alias: ref-y
Make y-coordinate of the subelement relative to the y-coordinate of the element referenced to by the selector in ref
attribute.
If ref-y
is in the (0,1)
interval (or expressed in percentages, e.g. '80%'
), the offset is
calculated from the fraction of the bounding box of the referenced element. Otherwise, it is an absolute value in pixels.
Same as refY
. Useful when one needs to position an element absolutely and relatively at the same time.
{ refY: '50%', refY2: 20 } // moves the element by 50% of the referenced height plus extra 20 pixels.
If set to true
, the subelement offset (the distance from x0 y0 to the most top-left point) will be reset to x0 y0.
element.attr({
path: {
// The path bbox for `d="M 10 10 20 20"` is x10 y10 w10 h10.
d: 'M 10 10 20 20',
// The path bbox will be changed to x0 y0 w10 h10.
// This has same effect as passing path with `d="M 0 0 10 10"`
resetOffset: true
}
});
Valid for <path>
subelements. It draws an SVG element at the beginning of a path. The element is automatically rotated based on the path direction.
It's defined as an object with type
property and any other visual attributes. The valid values for type
are 'path'
, 'circle'
, 'ellipse'
, 'rect'
, 'polyline'
and 'polygon'
.
link.attr('.connection/sourceMarker', {
type: 'circle', // SVG Circle
fill: '#666',
stroke: '#333',
r: 5, // radius of the circle
cx: 5 // move the centre of the circle 5 pixels from the end of the path
});
The stroke
attribute becomes a special attribute only in case it's defined as an object. This has the exact same
behaviour as the fill attribute.
An object containing CSS styles for a subelement.
Valid for <path>
subelements. The same as sourceMarker but draws an SVG element at the end of the path.
Note the coordinate system for drawing is rotated by 180 degrees for convenience (this allows to use the same marker for source and target and have them both face the connected elements).
Valid only for <text>
subelements.
The text
attribute contains the text that should be set on the subelement. If the provided string does not contain any newline characters ('\n'
), the text is set directly as the content of the <text>
subelement. Alternatively, if the provided string has multiple lines, each line becomes the content of a <tspan>
child of the <text>
subelement.
If you need the text to be automatically wrapped inside the <text>
subelement, you should use the textWrap
attribute instead. It can automatically add line breaks into the provided string as necessary, and mark them with newline characters.
Valid only for <text>
subelements.
textPath
can be either a string or an object.
If it is a string, it specifies a path the text will be rendered along.
If it is an object, then it can contain a d
property that specifies the path the text will be rendered along.
Alternatively use selector
property, which is useful for targeting a specific SVGPathElement within the shape. The option expects a string selector (CSS or JSONMarkup selector).
Use startOffset
property to control the text position on the path (e.g. '50%'
, 20
). See the Vectorizer.text
method for more details.
Valid only for <text/>
subelements. The attribute is used to (top-, middle- or bottom-) align a text, relative to a point determined by reference to provided x
, y
, refX
, refY
, and similar attributes. See the Vectorizer.text
method for more details.
Valid only for <text>
subelements.
Similar to the text
attribute, except the provided string is automatically wrapped to fit within the reference bounding box.
Expects an object with a text
property and optional width
and height
, which can adjust the final size of the wrapped text. Negative values decrease the dimension (e.g. to add padding around the wrapped text); positive values increase the dimension. Percentage values are accepted as well.
If the text cannot fit into the bounding box as specified, the overflowing words are cut off. If the ellipsis
option is provided, an ellipsis string is inserted before the cutoff. If no words can fit into the bounding box at all, no text is inserted. See util.breakText for more info.
textWrap: {
text: 'lorem ipsum dolor sit amet consectetur adipiscing elit',
width: -10, // reference width minus 10
height: '50%', // half of the reference height
ellipsis: true // could also be a custom string, e.g. '...!?'
}
Add the text-only description in form of a <title>
element to the associated node. The title is not rendered as part of the graphics, but it's displayed as a tooltip.
element.attr('rect/title', 'Description of the rectangle');
Valid for <path>
subelements. The same as sourceMarker but draws SVG elements at every vertex of the path.
alias: x-alignment
If set to 'middle'
, the subelement will be centered around its new x-coordinate.
alias: y-alignment
If set to 'middle'
, the subelement will be centered around its new y-coordinate.
The basic model for diagram cells. It's a Backbone model with a few additional properties and methods. Most importantly, every cell has a unique ID that is stored in the id
property.
define(type [, defaultAttributes, prototypeProperties, staticProperties])
Helper to define a new Cell class or extend an existing one.
The type
must be a unique identifier of the class, which determines the location of the class definition in the joint.shapes
namespace (type
is the path to the class definition delimited by dots: .
). When creating an instance of the cell, attributes will be set to the value from the defaultAttributes
, unless overridden by subclass or instance attributes.
// Define a new Ellipse class in `joint.shapes.examples` namespace
// Inherits from generic Element class
var Ellipse = joint.dia.Element.define('examples.Ellipse', {
// default attributes
markup: [{
tagName: 'ellipse',
selector: 'ellipse' // not necessary but faster
],
attrs: {
ellipse: {
fill: 'white',
stroke: 'black',
strokeWidth: 4,
refRx: .5,
refRy: .5,
refCx: .5,
refCy: .5
}
}
});
// Instantiate an element
var ellipse = (new Ellipse()).position(100, 100).size(120, 50).addTo(graph);
// Define a new ColoredEllipse class
// Inherits from Ellipse
var ColoredEllipse = Ellipse.define('examples.ColoredEllipse', {
// overridden Ellipse default attributes
// other Ellipse attributes preserved
attrs: {
ellipse: {
fill: 'lightgray'
}
}
}, {
// prototype properties
// accessible on `this.(...)` - as well as, more precisely, `this.prototype.(...)`
// useful for custom methods that need access to this instance
// shared by all instances of the class
randomizeStrokeColor: function() {
var randomColor = '#' + ('000000' + Math.floor(Math.random() * 16777215).toString(16)).slice(-6);
return this.attr('ellipse/stroke', randomColor);
}
}, {
// static properties
// accessible on `this.constructor.(...)`
// useful for custom methods and constants that do not need an instance to operate
// however, a new set of static properties is generated every time the constructor is called
// (try to only use static properties if absolutely necessary)
createRandom: function() {
return (new ColoredEllipse()).randomizeStrokeColor();
}
});
// Instantiate an element
var coloredEllipse = ColoredEllipse.createRandom().position(300, 100).size(120, 50).addTo(graph);
markup
Either an XML string or JSON markup specifying an array of JSON elements. Used as a template to build DOM Elements on the fly when the associated cellView is rendered.
A valid XML string that contains either a single tagName
or XML that can be parsed with DOMParser
.
markup: 'rect'
markup: '<rect class="rectangle"/>'
markup: '<rect><g><circle/><circle/></g>'
JSON markup is defined recursively as an array of JSONElement
, where JSONElement
is a plain object with the following properties:
tagName
(string) (required) The type of element to be created.selector
(string) A unique selector for targeting the element within the attr
cell attribute.groupSelector
(string | string[]) A selector for targeting multiple elements within the attr
cell attribute. The group selector name must not be the same as an existing selector name.namespaceURI
(string) The namespace URI of the element. It defaults to SVG namespace "http://www.w3.org/2000/svg"
.attributes
(object with attributes name-value pairs) Attributes of the element.style
(object with CSS property-value pairs) The style
attribute of the element.className
(string) The class
attribute of the element.children
(JSONMarkup) The children of the element.textContent
(string) The text content of the element.// single DOM element
markup: [{ tagName: 'rect' }]
// multiple DOM elements
markup: [{
tagName: 'rect',
selector: 'body'
}, {
tagName: 'text',
selector: 'label',
attributes: {
'stroke': 'none'
}
}]
// nested DOM elements
markup: [{
tagName: 'g',
children: [{
tagName: 'circle',
selector: 'circle1',
groupSelector: 'circles'
}, {
tagName: 'circle',
selector: 'circle2',
groupSelector: 'circles'
}]
}]
selector
and groupSelector
.
selector
is unique i.e. can target a single node only.selector
takes precedence over groupSelector
.groupSelector
targeting n
nodes takes precedence over groupSelector
targeting m
nodes for n
< m
. When n
=== m
the order how the attributes are applied is unspecified.In the example below, the circle with the selector circle1
is filled with "red"
color. All the other circles are filled with "blue"
color.
cell.attr({
circle1: { fill: 'red' },
circles: { fill: 'blue', stroke: 'black' }
});
cell.getParentCell()
Return the parent cell of cell
or null
if there is none.
cell.isElement()
Always returns false
. The reason the method is here is that both joint.dia.Element
and joint.dia.Link
inherit from joint.dia.Cell
. This method is useful if you don't know what the cell is. Calling cell.Element()
is equivalent to cell instanceof joint.dia.Element
. Example:
var cell = graph.getCell(myId)
if (cell.isElement()) {
// Do something if the cell is an element.
}
element.isLink()
Always returns false
. The reason the method is here is that both joint.dia.Element
and joint.dia.Link
inherit from joint.dia.Cell
. This method is useful if you don't know what the cell is. Calling cell.isLink()
is equivalent to cell instanceof joint.dia.Link
. Example:
var cell = graph.getCell(myId)
if (cell.isLink()) {
// Do something if the cell is a link.
}
cell.parent()
Return the parent
property of the cell.
If the cell is a part of an embedding, the id
of the parent cell is returned as a string.
If you need to be sure that a Cell is returned (and not its id
), use the cell.getParentCell
function instead.
cell.parent(parentId [, opt])
Set the parent
property of the cell to parentId
provided.
The view for the joint.dia.Cell model. It inherits from Backbone.View and is responsible for:
To find the view associated with a specific cell (model), use the findViewByModel method of the paper. For example:
var cellView = paper.findViewByModel(cell);
cellView.findAttribute(attribute, node)
Return the value of the specified attribute
of node
.
If node
does not set a value for attribute
, start recursing up the DOM tree from node
to look for attribute
at the ancestors of node
. If the recursion reaches CellView's own node and attribute
is not found even there, return null
.
cellView.highlight([el[, options]])
Highlights the cell view.
Arguments:
$el
will be usedname
cellView.unhighlight([el[, options]])
Removes the highlighting being done to the cell.
It is important to note that if you highlighted a cell using custom options, you must provide those exact same options when using the unhighlight method.
The model for diagram elements. It inherits from joint.dia.Cell with a few additional properties and methods specific to elements. These properties can be put into three groups:
Coordinates of an element are stored in the position
property that is an object with x
and y
keys. position
can be accessed or set directly using the regular Backbone set()
/get()
methods or through the translate method.
Rotation angle is stored in the angle
property. This angle is in degrees and the rotation origin is always considered to be the center of the element. angle
can be also accessed or set directly using the regular Backbone set()
/get()
methods or through the rotate method.
Size of an element is stored in the size
property that is an object with width
and height
keys. Again, size
can be accessed or set directly using the regular Backbone set()
/get()
methods or through the resize method.
Another important property is attrs
which is an object with keys representing selectors that match subelements and values which are SVG attributes that will be set on the subelements. One can find a list of SVG attributes and their descriptions e.g. on MDN.
It is important to note that each joint.dia.Element
defines an SVG markup which is then used by joint.dia.ElementView
to render the element to the paper. For instance, the joint.shapes.basic.Rect
element (that inherits from joint.dia.Element
) defines its markup as follows:
<g class="rotatable"><g class="scalable"><rect/></g><text/></g>
Therefore, in order to set a red fill color for the rectangle subelement, the attrs
object should contain:
rect: { fill: 'red' }
Again, it is not recommended to change the attrs
object directly. Instead, use the attr method.
The z
property specifies the stack order of the element in the SVG DOM. An element with a higher z
level is in front of an element with a lower z
level. (This also stands for links which have the exact same property.)
The last two properties of elements are embeds
and parent
. These two are related to elements that contain or are contained within other elements forming a hierarchical structure. embeds
is a list of cell id
's that are embedded inside the element. parent
is an id
of the parent element of the embedded one. When a parent element is translated, all its children get translated too.
The following list contains events that you can react on:
change
- generic event triggered for any change on the element - fn(element, opt)change:position
- triggered when the element changes its position - fn(element, newPosition, opt)change:angle
- triggered when the element gets rotated - fn(element, newAngle, opt)change:size
- triggered when the element gets resized - fn(element, newSize, opt)change:attrs
- triggered when the element changes its attributes - fn(element, newAttrs, opt)change:embeds
- triggered when other cells were embedded into the element - fn(element, newEmbeds, opt)change:parent
- triggered when the element got embedded into another element - fn(element, newParent, opt)change:z
- triggered when the element is moved in the z-level (toFront and toBack) - fn(element, newZ, opt)transition:start
- triggered when a transition starts. - fn(element, pathToAttribute)transition:end
- triggered when a transiton ends. - fn(element, pathToAttribute)// Listening for changes of the position to a single element
element1.on('change:position', function(element1, position) {
alert('element1 moved to ' + position.x + ',' + position.y);
});
// All elements events are also propagated to the graph.
graph.on('change:position', function(element, position) {
console.log('Element ' + element.id + 'moved to ' + position.x + ',' + position.y);
});
// Using the option parameter and a custom attribute
graph.on('change:custom', function(element, custom, opt) {
if (opt.consoleOutput) {
console.log('Custom attribute value changed to "' + custom + '"');
}
});
element2.prop('custom', 'myValue', { consoleOutput: true });
Many diagramming applications deal with elements with ports. Ports are usually displayed as circles inside diagram elements and are used not only as "sticky" points for connected links but they also further structure the linking information. It is common that certain elements have lists of input and output ports. A link might then point not to the element as a whole but to a certain port instead.
It's easy to add ports to arbitrary shapes in JointJS. This can be done either by passing a ports definition as an option
in the constructor or using the ports API to get/add/remove single or multiple ports. For more information on how to define ports please see Port configuration section.
joint.dia.Element
hasPort
/ hasPorts
addPort
/ addPorts
removePort
/
removePorts
getPort
/ getPorts
portProp
getPortPositions
// Single port definition
var port = {
// id: 'abc', // generated if `id` value is not present
group: 'a',
args: {}, // extra arguments for the port layout function, see `layout.Port` section
label: {
position: {
name: 'right',
args: { y: 6 } // extra arguments for the label layout function, see `layout.PortLabel` section
},
markup: '<text class="label-text" fill="blue"/>'
},
attrs: { text: { text: 'port1' } },
markup: '<rect width="16" height="16" x="-8" strokegit ="red" fill="gray"/>'
};
// a.) add a port in constructor.
var rect = new joint.shapes.standard.Rectangle({
position: { x: 50, y: 50 },
size: { width: 90, height: 90 },
ports: {
groups: {
'a': {}
},
items: [port]
}
});
// b.) or add a single port using API
rect.addPort(port);
id | string | It is automatically generated if no `id` provided. IDs must be unique in the context of a single shape - two ports with the same port id are therefore not allowed (`Element: found id duplicities in ports.` error is thrown). |
group | string | Group name, more info in [groups](#groupssection) section. |
args | object | Arguments for the port layout function. Available properties depends on the type of layout. More information could be found in [`layout.Port`](#layout.Port). |
attrs | object | JointJS style attribute definition. The same notation as the `attrs` property on [`Element`](#joint.dia.Element.presentation). |
markup | string |
Custom port markup. Multiple roots are not allowed. Valid notation would be:
` It defaults to ` |
label | object | Port label layout configuration. E.g. label position, label markup. More information about port label layouts could be found in [`layout.PortLabel`](#layout.PortLabel) section. |
|
string | object |
Port label position configuration. It could be a `string` for setting the port layout type directly with default
settings or an `object` where it's possible to set the layout type and options.
|
|
string | Stands for the layout type, match the layout method name defined in `joint.layout.PortLabel` namespace: `name:'left'` is implemented as `joint.layout.PortLabel.left`. |
|
object | Additional arguments for the layout method. Available properties depends on the layout type. More information could be found in [`layout.PortLabel`](#layout.PortLabel) section. |
|
string |
Custom port label markup. Multiple roots are not allowed. It defaults to ` |
z | number | string |
Alternative to HTML `z-index`. `z` sets the position of a port in the list of DOM elements within an `ElementView`. Shapes most likely consist of 1 or more DOM elements, `
` will be rendered like this:
Another example with simplified markup `
|
All properties described above are optional and everything has own default. E.g. element.addPorts([{}, {}])
will add 2 ports with default settings.
group
attribute comes to play when you're not happy with the default port alignment. It's also handy when you need to define multiple ports with similar properties. group
defines defaults for ports belonging to the group. Any group
property can be overwritten by a port in this group except the type of layout - position
. 'group' defines the layout and port 'args' are the only way how a port can affect it.
// Define ports and port groups in element constructor.
var groupA;
var rect = new joint.shapes.basic.Rect({
// ...
ports: {
groups: {
'group1': groupA,
// 'group2': ...,
// 'group3': ...,
},
items: []
}
});
groupA = {
position: {
name: 'string', // layout name
args: {}, // arguments for port layout function, properties depends on type of layout
},
label: {
// ....
},
attrs: {},
markup: '<rect width="10" height="10" stroke="red"/>'
};
position | string | object | Port position configuration. Could be `string` to set port layout type directly with default settings or `object` where is possible to set layout type and options. |
|
string | Stands for the layout type, match the layout method name defined in `joint.layout.Port` namespace: `name:'left'` is implemented as `joint.layout.Port.left`. |
|
object | Arguments for the port layout function. Available properties depends on the type of layout. More information could be found in [`layout.Port`](#layout.Port). |
attrs | object | JointJS style attribute definition. The same notation as the `attrs` property on [`Element`](#joint.dia.Element.presentation). |
markup | string |
Custom port markup. Multiple roots are not allowed. Valid notation would be:
. It defaults to `` |
label | object | Port label layout configuration. E.g. label position, label markup. More information about port label layouts could be found in [`layout.PortLabel`](#layout.PortLabel) section. |
|
string | object |
Port label position configuration. It could be a `string` for setting the port layout type directly with default
settings or an `object` where it's possible to set the layout type and options.
|
|
string | Stands for the layout type, match the layout method name defined in `joint.layout.PortLabel` namespace: `name:'left'` is implemented as `joint.layout.PortLabel.left`. |
|
object | Additional arguments for the layout method. Available properties depends on the layout type. More information could be found in [`layout.PortLabel`](#layout.PortLabel) section. |
|
string |
Custom port label markup. Multiple roots are not allowed. It defaults to ` |
Both port and port label can have custom markup.
var rect = new joint.shapes.basic.Rect({
// ...
});
rect.addPort({ markup: '<rect width="10" height="10" fill="blue"/>' })
rect.addPort({ markup: '<rect width="15" height="15" fill="red"/>', label: { markup: '<text fill="#000000"/>' }})
or, it can be set as an default port markup/port label markup on an element model:
var rect = new joint.shapes.basic.Rect({
portMarkup: '<rect width="20" height="20" fill="black"/>',
portLabelMarkup: '<text fill="yellow"/>',
// ...
});
element.addPort(port, [opt])
Add a single port, where port
could be defined as described in section Port interface
element.addPorts(ports, [opt])
Add array of ports
. Ports are validated for id
duplicities, if there is a id collision, no new ports are added, where port
could be defined as describe in section Port interface
element.addTo(graph)
Add the element to the graph
(an instance of joint.dia.Graph
). This is equivalent to calling graph.addCell(element)
.
element.angle()
Return the rotation of the element in degrees (0° - 360°).
element.attr(attrs)
Set SVG attributes (and JointJS special attributes) on subelements. attr
can either be an object or string representing a path to a nested attribute. If it is an object, the keys of the attrs
object are CSS selectors matching the subelements. The values are objects containing SVG attributes and their values. attrs
object will be mixined with attrs
property of the element
model. This is a convenient way of rewriting only some of the attributes of the subelements. For overwritting all attributes of all subelements, use element.set(attrs)
.
element.attr({
rect: { fill: 'blue' },
text: { fill: 'white', 'font-size': 15 },
'.myrect2': { fill: 'red' }
});
An alternative call using a string path and a value:
element.attr('text/font-size', 12);
element.clone(options)
Returns a new instance of the element with identical attributes. If options.deep === true
, then
all the embedded cells (elements, links) of the element are cloned as well. In this case, the return value is an array of
instances rather then a single instance.
element.embed(cell)
Embed a cell (element or link) into the element. The element then becomes a parent of the embedded cell. When a parent is moved (translated), all cells embedded into that parent will move as well. If links are embedded, their vertices move with the parent. This way both options are available: if a link is not embedded but its source/target elements are and their parent moves, the embedded elements move with the parent but the link vertices stay at the same position. If the link is embedded with its source/target elements, its vertices move as the parent moves.
element.findView(paper)
Find view (joint.dia.ElementView
) for the element model in the paper
.
This is a shortcut to the equivalent call paper.findViewByModel(element)
element.fitEmbeds([opt])
Resize the element so that it fits all the embedded elements inside it. If opt.deep
is true
,
the resizing will be done recursively for any embedded elements that contain embedded elements themselves.
Set opt.padding
if you want certain padding on all the parent elements.
element.getAncestors()
Return an array of all the ancestors of this element starting from the immediate parent all the way up to the most distant ancestor.
element.getBBox()
Returns an element's bounding box represented as a g.rect
object (see geometry library).
if (element1.getBBox().intersect(element2.getBBox())) {
// elements intersect
}
element.getEmbeddedCells([opt])
Return an array of all the embedded cells of an element. If all you need is id
's of all the embedded cells,
use element.get('embeds')
. If opt.deep
is true
, all the deeply embedded
cells will be returned. The order in which the cells are returned depends on the search algorithm used. By
default, Depth-first search (DFS) algorithm is used. If
opt.breadthFirst
is true
, the Breadth-first search algorithm will be used instead.
element.getPort(id)
Returns the port specified by an id
. If such a port does not exist the method returns undefined
.
element.getPortIndex(portId)
Returns the port index in the array of port items.
element.getPorts()
Returns an array of all ports on the element. If there is no port an empty array is returned.
element.getPortsPositions(groupName)
Returns the positions and the angle of all ports in the group, relatively to the element position.
element.getTransitions()
Return an array of all active transitions (their paths).
element.hasPort(id)
Check if an element contains a port with id
. Returns boolean
.
element.hasPorts()
Check if an element has any ports defined. Returns boolean
.
element.isElement()
Always returns true
. The reason the method is here is that both joint.dia.Element
and joint.dia.Link
inherit from joint.dia.Cell
. This method is useful if you don't know what the cell is. Calling cell.isElement()
is equivalent to cell instanceof joint.dia.Element
. Example:
var cell = graph.getCell(myId)
if (cell.isElement()) {
// Do something if the cell is an element.
}
element.isEmbeddedIn(element [, opt])
Return true
if the element is embedded in another element element
. If opt.deep
is false
, only direct parentage will be checked. opt.deep
is true
by default.
element.isLink()
Always returns false
. The reason the method is here is that both joint.dia.Element
and joint.dia.Link
inherit from joint.dia.Cell
. This method is useful if you don't know what the cell is. Calling cell.isLink()
is equivalent to cell instanceof joint.dia.Link
. Example:
var cell = graph.getCell(myId)
if (cell.isLink()) {
// Do something if the cell is a link.
}
element.portProp(portId, path, [value])
Set properties, possibly nested, on the element port. This is an equivalent of the attr() method but this time for custom data properties.
element.portProp('port-id', 'attrs/circle/fill', 'red');
element.portProp('port-id', 'attrs/circle/fill'); // 'red'
element.portProp('port-id', 'attrs/circle', { r: 10, stroke: 'green' });
element.portProp('port-id', 'attrs/circle'); // { r: 10, stroke: 'green', fill: 'red' }
element.position(x, y, [opt])
Set the element position to x
and y
coordinates. This is almost equivalent to
element.set('position', { x: x, y: y }, opt)
. However, this method provides some additional functionality.
If you set opt.parentRelative
flag to true
, the x
and y
coordinates will be treated relatively to the parent element of this element. If position()
is called
without arguments, it returns the current position. If position({ parentRealtive: true })
is called
without x
and y
coordinates and with the parentRelative
flag set to true
,
the method returns the current position of the element relative to its parent.
Setting opt.deep
to true
will position not only the element but also all its descendants keeping
the original distances from a child to the element origin.
el1.position(100, 100);
el1.embed(el2);
el2.position(10, 10, { parentRelative: true });
el2.position() // --> 110@110
el1.position(200,200, { deep: true });
el2.position() // --> 210@210
element.prop(properties)
Set properties, possibly nested, on the element model. This is an equivalent of the attr() method but this time for custom data properties.
element.prop('name/first', 'John')
element.prop('name/first') // 'John'
element.prop({ name: { first: 'John' } })
// Nested arrays are supported too:
element.prop('mylist/0/data/0/value', 50)
element.prop({ mylist: [ { data: [ { value: 50 } ] } ] })
element.remove(options)
Remove the element from the graph. All its embedded elements will get removed too and the element gets unembedded from its parent element. By default,
all the associated links are removed too. To suppress this behaviour, set options.disconnectLinks === true
. In this case, all the associated
links get disconnected from this element rather then removed completely from the graph.
element.removeAttr(path, [options])
Remove a previously set attribute from the element. path
can either be a string that specifies
the path to the, possibly nested, attribute to be removed or an array of more paths.
The associated element view makes sure the element gets re-rendered properly.
If options
is passed, it can contain data that is passed over to
the event listeners for the change:attrs
event triggered on the element
itself and also on the graph the element is in.
element.removePort(port, [opt])
Remove a port from an element, where port
is a port object, or portId
.
element.removePorts(ports [, opt])
Remove an array of ports
from the element.
The ports can be specified as Port interfaces or portIds
. The function skips over any ports in the array that do not exist on the element.
element.removePorts([opt])
If no array is provided, the function removes all ports from the element.
element.resize(width, height [, opt])
Resize an element in place so that the "scalable" group has width width
and height height
. In place in this case means
that the top-left corner of the element stays at the same position after resizing. In other words,
the element is streched to the bottom/right (by default). To change the direction of resizing, set
opt.direction
to one of 'left'
, 'right'
, 'top'
, 'bottom'
,
'top-right'
, 'top-left'
, 'bottom-left'
or 'bottom-right'
(the default).
There is a difference between a classical scale and
resize operations. resize
doesn't actually scale the whole SVG <g>
element grouping
all its subelements. It only scales subelements of the <g class"scalable"/>
group. This is very
useful and brings a lot of flexibility in defining which subelements should be scaled and which not. Imagine a simple
rectangle element with text inside. Usually, when we resize the whole element, we expect the rectangle to
get scaled while the text should stay the same size, only its position should be adjusted so that the text stays
in the center of the rectangle. This can be easilly achieved by adding the <rect/>
element to the <g class"scalable"/>
group
in the markup and positioning the text
subelement relatively to the <rect />
element: <text ref-x=".5" ref-y=".5" ref="rect" />
.
Note that neither of ref-x, ref-y and ref
attributes is an SVG standard attribute. These are special
attributes introduced by JointJS. More on these in the section on Special attributes.
element.rotate(deg, [absolute, origin, opt])
Rotate an element by deg
degrees around its center. If the optional absolute
parameter is true
,
the deg
will be considered an absolute angle, not an addition to the previous angle.
If origin
is passed in the form of an object with x
and y
properties,
then this point will be used as the origin for the rotation transformation.
element.scale(sx, sy, origin[, opt])
Scales the element's position and size relative to the given origin.
element.stopTransitions([path])
Stops all running transitions. If parameter path
is provided, it will stop only transitions specified by this path.
element.toBack([opt])
Move the element so it is behind all other cells (elements/links).
If opt.deep
is true
, all the embedded cells of this
element will get higher z
index than that of this element in a Breadth-first search (BFS) fashion. This
is especially useful in hierarchical diagrams where if you want to send an element to the back, you don't want
its children (embedded cells) to be hidden behind that element.
element.toFront([opt])
Move the element so it is on top of all other cells (element/links).
If opt.deep
is true
, all the embedded cells of this
element will get higher z
index than that of this element in a Breadth-first search (BFS) fashion. This
is especially useful in hierarchical diagrams where if you want to send an element to the front, you don't want
its children (embedded cells) to be hidden behind that element.
All elements have a z
property defining their z-level in the graph. This z
property
can even be set directly by element.set('z', 123)
. This change will be automatically handled by the joint.dia.Paper
object associated with the joint.dia.Graph
object this element is part of and all the SVG elements will get resorted so that
their position in the DOM reflects the z
level.
element.toJSON()
Return a copy of the element's attributes for JSON serialization. This can be used for persistance or serialization. Note that this method doesn't return a JSON string but rather an object that can be then serialized to JSON with JSON.stringify()
.
element.transition(path, value [, opt])
Allows to change the element's property gradually over a period of time. This method lets you specify what property to change (path
), when the transition will start (options.delay
), how long the transition will last (options.duration
), how the transition will run (options.timingFunction
), and how to interpolate the property value (options.valueFunction
).
element.transition('position/x', 250, {
delay: 100,
duration: 500,
timingFunction: function(t) { return t*t; },
valueFunction: function(a, b) { return function(t) { return a + (b - a) * t }}
});
// will start changing the element's x-coordinate in 100ms, for period of 500ms.
JointJS comes pre-built with some common timing and interpolating functions. The timing functions are defined in the joint.util.timing
namespace and the interpolating functions in the joint.util.interpolate
namespace. The predefined timing functions are:
linear
quad
cubic
inout
exponential
bounce
and the predefined interpolating functions are:
number
object
hexColor
unit
element.transition('attrs/text/font-size', '1em', {
valueFunction: joint.util.interpolate.unit,
timingFunction: joint.util.timing.bounce
});
// will start changing the current font size value to 1em in the bounce fashion.
element.translate(tx, [ty], [opt])
Translate an element by tx
pixels in x axis and ty
pixels in y axis.
ty
is optional in which case the translation in y axis will be considered zero.
The optional options object opt
can be used to pass additional parameters to the event handlers
listening on 'change:position'
events. opt.transition
can be used to initiate an animated
transition rather than a sudden move of the element. See joint.dia.Element:transition for more info
on transitions. If opt.restrictedArea
is set, the translation of the element will be restricted to that area only.
The restrictedArea
is an object of the form { x: Number, y: Number, width: Number, height: Number }
.
This is useful, e.g. if you want to restrict the translation of an embedded element within its parent. The only thing
you have to do in this case is to pass the bounding box of the parent element to the restrictedArea
option:
myElement.translate(50, 50, { restrictedArea: graph.getCell(myElement.get('parent')).getBBox() })
The code above makes sure that the element myElement
never crosses the bounding box of its parent element.
note that this also works if the element myElement
has other embedded elements. In other words, the
bounding box of the myElement
that is used to calculate the restriction is the total bounding box,
including all its children (in case they are sticking out
).
element.unembed(cell)
Free up an embedded cell from its parent element.
The view for the joint.dia.Element model. It inherits from joint.dia.CellView and is responsible for:
To find the view associated with a specific element (model), use the findViewByModel method of the paper.
var elementView = paper.findViewByModel(element);
elementView.getBBox([opt])
Return a bounding box for an element view. If opt.useModelGeometry
option is set to true
, the resulting bounding box will be calculated
based on the element model dimensions (so that SVG sub elements sticking out
of the element will be excluded). The difference from
dia.Element.prototype.getBBox is that in this case, the bounding box will be adjusted based on the
joint.dia.Paper
translate and scale.
elementView.getNodeBBox(magnet)
Return the bounding box of the SVGElement provided as magnet
(element/subelement/port of this element view).
elementView.getNodeUnrotatedBBox(magnet)
Return the unrotated bounding box of the SVGElement provided as magnet
(element/subelement/port of this element view).
joint.dia.Graph is the model holding all the cells (elements and links) of the diagram. It's a Backbone model.
The collection of all the cells is stored in the property cells
.
The graph is a powerful data model behind all JointJS diagrams. It not only provides an efficient storage for directed graphs but also offers useful algorithms for traversing the graphs.
Additionally, the graph accepts an option object in its constructor function that can contain the cellNamespace
option.
This option can be used to change the default behavior of JointJS which by default reads cell model definitions from the joint.shapes
namespace.
For example, if a cell is of type 'myshapes.MyElement'
, then the graph looks up joint.shapes.myshapes.MyElement
model when deserializing a graph from the JSON format. If the graph is instantiated as e.g. var graph = new joint.dia.Graph({}, { cellNamespace: myShapesNamespace })
, then
the graph will read the model definition from the myShapesNamespace.myshapes.MyElement
object instead. This is useful in situations where you don't want to - for any reason -
use the joint.shapes
namespace for defining your own custom shapes. This option is often used in combination with the
cellNamespaceView
option on the joint.dia.Paper object.
The following list contains events that you can react on:
change
- generic event triggered for any change in the graphadd
- triggered when a new cell is added to the graphremove
- triggered when a cell is removed from the graphgraph.on('add', function(cell) {
alert('New cell with id ' + cell.id + ' added to the graph.')
})
The JointJS graph JSON representation has the following format:
{
cells: [// Array of cells (ie. links and elements).
{
id: '3d90f661-fe5f-45dc-a938-bca137691eeb',// Some randomly generated UUID.
type: 'basic.Rect',
attrs: {
'stroke': '#000'
},
position: {
x: 0,
y: 50
},
angle: 90,
size: {
width: 100,
height: 50
},
z: 2,
embeds: [
'0c6bf4f1-d5db-4058-9e85-f2d6c74a7a30',
'cdbfe073-b160-4e8f-a9a0-22853f29cc06'
],
parent: '31f348fe-f5c6-4438-964e-9fc9273c02cb'
// ... and some other, maybe custom, data properties
}
]
}
graph.addCell(cell)
Add a new cell to the graph. If cell
is an array, all the cells in the array will be added to the graph.
var rect = new joint.shapes.basic.Rect({
position: { x: 100, y: 100 },
size: { width: 70, height: 30 },
attrs: { text: { text: 'my rectangle' } }
})
var rect2 = rect.clone()
var link = new joint.dia.Link({ source: { id: rect.id }, target: { id: rect2.id } });
var graph = new joint.dia.Graph
graph.addCell(rect).addCell(rect2).addCell(link)
graph.addCells(cells[, opt])
graph.addCells(cell, cell, ..[, opt])
Add new cells to the graph. This is just a convenience method that wraps the addCell method.
graph.bfs(element, iteratee [, opt])
Traverse the graph using the Breadth-first search algorithm starting at element
(note the element itself will be visited too). iteratee
is a function of the form function(element, distance) {}
that will be called with the currently visited element and distance of that element from the root element of the search (the element
passed to bfs()
). If iteratee
explicitely returns false
, the search stops.
The following image shows the order in which elements are traversed in the graph:
Note that the bfs()
algorithm is not only capable of traversing tree graphs but it can traverse any directed graph too.
It is smart enough not to traverse an element that was already visited.
If opt.inbound
is true
, reverse the search direction (it's like reversing all the link directions, i.e. swaping their source
and target
).
If opt.outbound
is true
, search follows the link directions. Calling bfs()
with opt.outbound
set to true
is the most common case (graph is traversed following the direction of links).
If none of opt.inbound
and opt.outbound
are used or both options are set to true
, the graph is traversed in both directions (very rare use case).
If opt.deep
is true
, the traversal takes into account embedded elements too. This option has the usual meaning as in other methods were deep
option is used. For example, in a hierarchy A (top level element), A1 (embedded in A), B (top level element), where A is not directly connected to B but its embedded element is (there is a link from A1 ----> B), bfs(A)would not visit B but bfs(A, function() {}, { deep: true }) would.
graph.clear([options)
Remove all the cells from the graph. options
object can optionally contain additional data that is passed overto the event listeners of the graph cells remove event.
graph.cloneCells(cells)
Clone all the cells (elements and/or links) from the cells
array and return an
object that maps the original cell ID to the clone (i.e. an object of the form { [original cell ID]: [clone] }
).
The reason why this object is returned instead of an array of clones is that it is very useful to know which object the clone
was created for.
The number of clones returned equals cells.length
. This function does not simply
clone all the cells but it also reconstructs all the source/target and parent/embed references
within cells
. This is very useful. For example, for a graph A --- L ---> B
,
cloneCells([A, L, B])
returns { A.id: A2, L.id: L2, B.id: B2 }
resulting
in a graph A2 --- L2 ---> B2
, i.e. the source and target of the link L2
is changed to point to A2
and B2
(in contrast to just looping over cells
and calling cell.clone()
on each item).
graph.cloneSubgraph(cells [, opt])
Clone the whole subgraph, including all the connected links whose source/target is in the subgraph.
This is equivalent to calling graph.cloneCells(graph.getSubgraph(cells))
.
If opt.deep
is true
, take into account embedded cells of the subgraph cells.
Return an object of the form { [original cell ID]: [clone] }
.
graph.dfs(element, iteratee [, opt])
Traverse the graph using the Depth-first search algorithm starting at element
(note the element itself will be visited too). iterate
is a function of the form function(element, distance) {}
that will be called with the currently visited element and distance of that element from the root element of the search (the element
passed to dfs()
). If iteratee
explicitely returns false
, the search stops.
The following image shows the order in which elements are traversed in the graph:
Note that the dfs()
algorithm is not only capable of traversing tree graphs but it can traverse any directed graph too. It is smart enough not to traverse an element that was already visited.
If opt.inbound
is true
, reverse the search direction (it's like reversing all the link directions, i.e. swaping their source
and target
).
If opt.outbound
is true
, search follows the link directions. Calling dfs()
with opt.outbound
set to true
is the most common case (graph is traversed following the direction of links).
If none of opt.inbound
and opt.outbound
are used or both options are set to true
, the graph is traversed in both directions (very rare use case).
If opt.deep
is true
, the traversal takes into account embedded elements too. This option has the usual meaning as in other methods were deep
option is used. For example, in a hierarchy A (top level element), A1 (embedded in A), B (top level element), where A is not directly connected to B but its embedded element is (there is a link from A1 ----> B), dfs(A) would not visit B but dfs(A, function() {}, { deep: true }) would.
graph.disconnectLinks(element)
Disconnect all the associated links with the element
.
graph.findModelsFromPoint(point)
Find elements (instance of joint.dia.Element
) under a certain point in the graph. point
is an object with x
and y
properties. Returns an
array of elements whose bounding box contains point
. Note that there can be more then one element as elements might overlap.
graph.findModelsInArea(rect)
Find elements (instance of joint.dia.Element
) in a certain area in the graph. rect
is an object with x
, y
, width
and height
properties. Returns an
array of elements whose bounding box top/left coordinate falls into the rect
rectangle.
graph.findModelsUnderElement(element [, opt])
Find all the elements (instances of joint.dia.Element
) that are located below element
.
opt.searchBy
parameter optionally determines what it means for an element to be below another element.
Possible values are 'bbox'
(default), 'center'
, 'origin'
, 'corner'
, 'topRight'
,
and 'bottomLeft'
.
graph.fromJSON(jsonObject, [options])
Load a graph from a JSON object (not string). Used in conjunction with the graph.toJSON()
function.
The options
object may contain additional data that is passed over to graph change event listeners.
Note that this method does not expect a JSON string but rather an object in the JSON format. Use JSON.parse(jsonString)
if you need to convert a JSON string into the object form:
graph.fromJSON(JSON.parse(jsonString));
Example of storing stringified JSON objects:
var jsonString = JSON.stringify(graph.toJSON());
// ... send jsonString to the server
// store jsonString to localStorage or do whatever you want
// later on ...
graph.fromJSON(JSON.parse(jsonString));
Example of storing JSON objects directly:
var jsonObject = graph.toJSON();
// ... send jsonObject to the server
// store jsonObject (e.g. in a non-relational database)
// later on ...
graph.fromJSON(jsonObject)
graph.getBBox(cells[, opt])
Returns the bounding box that surrounds all the given cells. Links are ignored. An example:
var bbox = graph.getBBox(graph.getElements());
// { x: Number, y: Number, width: Number, height: Number }
graph.getCell(id)
Get a cell from the graph by its id
.
graph.getCells()
Get all the elements and links in the graph.
graph.getCommonAncestor(...cells)
Return the common ancestor of all the cells passed as arguments. For example, if an element B
is embedded in an element A
and an element C
is also embedded in the element A
, graph.getCommonAncestor(B, C)
returns the element A
. This also works on an arbitrary deep hierarchy.
graph.getConnectedLinks(element [, opt])
Get all links connected with element
.
If opt.inbound === true
, return only inbound connected links. Conversely, if opt.outbound === true
, return only outbound connected links. If both of these options were left undefined, or if both of them were set to true
, return inbound as well as outbound links.
By default, this function returns only immediate (shallow
) inbound and outbound links - no recursion. (Note that connections from element
to embedded child elements, and connections to element
from embedding parent elements count as shallow
, too - they too are returned.)
If opt.deep === true
, return all outside links that connect with element
or any of its descendants (descendants
meaning elements that are embedded or deeply embedded within element
). The inbound
and outbound
options can still be applied on top of this option.
Note that the specification of opt.deep
excludes links that connect two descendants of element
(enclosed
links). If you do need to find all links connected with and/or enclosed within element
, you should use opt.deep === true
alongside an additional option: opt.includeEnclosed === true
.
Example use:
var links = graph.getConnectedLinks(element); // inbound and outbound
var links = graph.getConnectedLinks(element, { outbound: true });
var links = graph.getConnectedLinks(element, { deep: true }); // inbound and outbound
var links = graph.getConnectedLinks(element, { inbound: true, deep: true });
var links = graph.getConnectedLinks(element, { outbound: true, deep: true, includeEnclosed: true });
graph.getElements()
Get all the elements in the graph (i.e. omit links).
graph.getFirstCell()
Get the first cell (element or link) in the graph. The first cell is defined as the cell
with the lowest z
property (the cell most in the back, see the Presentation section of joint.dia.Element).
graph.getLastCell()
Get the last cell (element or link) in the graph. The last cell is defined as the cell
with the highest z
property (the cell most in the front, see the Presentation section of joint.dia.Element).
graph.getLinks()
Get all the links in the graph (i.e. omit elements).
graph.getNeighbors(element [, opt])
Get all the neighbors of element
in the graph. Neighbors are all the elements connected
to element
via either an inbound or an outbound link. If opt.inbound
is true
,
only inbound neighbords (all neighbors connected with a link who's target
is the element
) will be returned. Similarly, if opt.outbound
is true
, only
outbound neighbors will be returned. If opt.deep
is true
,
return also all the neighbors of all the elements embedded inside element
.
graph.getPredecessors(element [, opt])
Return an array of all the predecessors of element
. By default, Depth-first search algorithm is used (important for the order of returned elements).
If opt.breadthFirst
is set to true
, use Breadth-first search algorithm instead.
If opt.deep
is set to true
, take into account embedded elements too (see dfs() for details).
graph.getSinks()
Return an array of all the leafs of the graph.
Time complexity: O(|V|)
.
graph.getSources()
Return an array of all the roots of the graph.
Time complexity: O(|V|)
.
graph.getSubgraph(cells [, opt])
Return an array of cells that result from finding elements/links that are connected to any of the cells in the cells
array.
This function loops over cells
and if the current cell is a link, it collects its source/target elements; if it is an element,
it collects its incoming and outgoing links if both the link ends (source/target) are in the cells
array.
For example, for a single element, the result is that very same element.
For two elements connected with a link: A --- L ---> B
, the result of getSubgraph([A, B])
is [A, L, B]
and the result of getSubgraph([L])
is also [A, L, B]
.
If opt.deep
is true
take into account all the embedded cells too when finding neighboring links/elements.
graph.getSuccessors(element [, opt])
Return an array of all the successors of element
. By default, Depth-first search algorithm is used (important for the order of returned elements).
If opt.breadthFirst
is set to true
, use Breadth-first search algorithm instead.
If opt.deep
is set to true
, take into account embedded elements too (see dfs() for details).
graph.isNeighbor(elementA, elementB [, opt])
Return true
if elementB
is a neighbor of elementA
.
If opt.deep
is set to true
, take into account embedded elements.
If opt.outbound
is set to true
, return true
only if elementB
is a successing neighbor of elementA
.
Similarly, if opt.inbound
is set to true
, return true
only if elementB
is a preceeding neighbor of elementA
.
graph.isPredecessor(elementA, elementB)
Return true
if elementB
is a predecessor of elementA
.
graph.isSink(element)
Return true
if element
is a leaf, i.e. there is no link coming out of the element.
Time complexity: O(1)
.
graph.isSource(element)
Return true
if element
is a root, i.e. there is no link that targets the element.
Time complexity: O(1)
.
graph.isSuccessor(elementA, elementB)
Return true
if elementB
is a successor of elementA
.
graph.maxZIndex()
Get the highest Z value in the graph (the value of the cell on front).
graph.minZIndex()
Get the lowest Z value in the graph (the value of the cell on the back).
graph.removeCells(cells[, opt])
graph.removeCells(cell, cell, ..[, opt])
Removes the given cells from the graph.
graph.removeLinks(element)
Remove all the associated links with the element
.
graph.resetCells(cells[, opt])
graph.resetCells(cell, cell, ..[, opt])
Reset cells in the graph. Update all the cells in the graph in one bulk. This is a more efficient method of adding cells to the graph if you ou want to replace all the cells in one go. options
object can optionally contain additional data that is passed over to the event listeners of the graph reset event.
graph.toJSON()
Return an object representation of the graph, which can be used for persistence or serialization. Use the graph.fromJSON()
function to load a previously converted graph.
Note that this method does not return a JSON string but rather an object that can then be serialized to JSON with JSON.stringify(jsonObject)
:
var jsonString = JSON.stringify(graph.toJSON());
graph.translate(tx, ty [, opt])
Translate all cells in the graph by tx
and ty
pixels. It uses the dia.Element.translate()
and dia.Link.translate()
methods internally.
The basic model for diagram links. It inherits from joint.dia.Cell with a few additional properties and methods specific to links.
Links have two crucial attributes: source
and target
. They define the starting point and the end point of the link. They can be defined as an element id or as a Point:
var link1 = new joint.dia.Link({
source: { id: sourceId },
target: { id: targetId, port: portId }
});
var link2 = new joint.dia.Link({
source: { id: sourceId },
target: { x: 100, y: 100 }
});
These are not the only attributes that may be specified for a newly-created joint.dia.Link
, however. An individual link instance may provide a value for these attributes:
markup
- provide custom link markup. May be specified as an XML string or JSON array.attrs
- provide custom link attributes. These allow you to change the style and size of SVG elements, identified by their selectors.vertices
- provide an array of vertices.vertexMarkup
- provide custom vertex markup (on hover).toolMarkup
- provide custom tool markup (on hover).doubleToolMarkup
- provide custom markup for second set of tools (on hover, if linkView.doubleLinkTools
is true
).arrowheadMarkup
- provide custom arrowhead markup (on hover).labels
- provide an array of labels. Each can have its own markup, position, and attrs specified.It is also possible to pass custom attributes to the link. These may be useful to identify an individual link model for the purposes of linkView interaction (see LinkView
documentation for more information). For example, to only enable custom contextmenu interaction for link1
but not link2
:
var CustomLinkView = joint.dia.LinkView.extend({
contextmenu: function(evt, x, y) {
if (this.model.get('customLinkInteractions')) {
// only links with `customLinkInteractions: true`
this.addLabel(x, y);
}
}
});
var paper = new joint.dia.Paper({
//...
linkView: CustomLinkView,
interactive: function(cellView) {
if (cellView.model.get('customLinkInteractions')) {
// only links with `customLinkInteractions: true`
return { vertexAdd: false };
}
return true; // otherwise
}
});
var link1 = new joint.dia.Link({
//...
customLinkInteractions: true // right-click adds a label
});
var link2 = new joint.dia.Link({
//...
customLinkInteractions: false // or omit completely
});
It is possible to extend the joint.dia.Link
class to create a custom link. A custom link may override Link properties to assign its own defaults. These values override builtin defaults, if provided, and are applied to all instances of the new Link type, unless an individual instance overrides them with its own values. The following Link attributes are applicable in this context:
markup
- provide default link markup for all instances of this Link type. May be specified as an XML string or JSON array.attrs
- provide default link attributes for all instances of this Link type. These allow you to change the style and size of SVG elements, identified by their selectors.vertexMarkup
- provide default vertex markup for all vertices created on an instance of this Link type (on hover).toolMarkup
- provide custom tool markup for all instances of this Link type (on hover).doubleToolMarkup
- provide custom markup for second set of tools for all instances of this Link type (on hover, if linkView.doubleLinkTools
is true
).arrowheadMarkup
- provide custom arrowhead markup for all instances of this Link type (on hover).defaultLabel
- provide default properties (markup, attrs, position) for all labels created on an instance of this Link type.The values of these defaults may be important; the linkView.addLabel()
shortcut function is only capable of adding default labels to the link.
Example:
var CustomLink = joint.dia.Link.define('examples.CustomLink', {
defaultLabel: {
markup: [
{
tagName: 'circle',
selector: 'body'
}, {
tagName: 'text',
selector: 'label'
}
],
attrs: {
label: {
text: '%', // default label text
fill: '#ff0000', // default text color
fontSize: 14,
textAnchor: 'middle',
yAlignment: 'middle',
pointerEvents: 'none'
},
body: {
ref: 'label',
fill: '#ffffff',
stroke: '#000000',
strokeWidth: 1,
refR: 1,
refCx: 0,
refCy: 0
}
},
position: {
distance: 0.5, // place label at midpoint by default
offset: {
y: -20 // offset label by 20px upwards by default
},
args: {
absoluteOffset: true // keep offset absolute when moving by default
}
}
}
});
var link = new CustomLink({
//...
});
To ensure backwards compatibility, the joint.dia.Link
class comes with a private builtin defaultLabel
attribute. It is reproduced here for reference:
defaultLabel: {
// builtin default markup:
// used if neither defaultLabel.markup
// nor label.markup is set
markup: [
{
tagName: 'rect',
selector: 'rect'
}, {
tagName: 'text',
selector: 'text'
}
],
// builtin default attributes:
// applied only if builtin default markup is used
attrs: {
text: {
fill: '#000000',
fontSize: 14,
textAnchor: 'middle',
yAlignment: 'middle',
pointerEvents: 'none'
},
rect: {
ref: 'text',
fill: '#ffffff',
rx: 3,
ry: 3,
refWidth: 1,
refHeight: 1,
refX: 0,
refY: 0
}
},
// builtin default position:
// used if neither defaultLabel.position
// nor label.position is set
position: {
distance: 0.5
}
}
If custom position
object is not provided (neither as a type default nor as an instance value), builtin default label position is applied instead ({ distance: 0.5 }
).
Furthermore, if custom markup
is not provided (neither as a type default nor as an instance value), builtin default label markup is applied, alongside the builtin default label attrs object. However, it is very highly recommended that you provide both your own markup
and your own attrs
- unless you want to use the builtin default precisely as-is.
change
- generic event triggered for any change on the linkchange:source
- triggered when the link changes its sourcechange:target
- triggered when the link changes its targetchange:attrs
- triggered when the link changes its attributeschange:smooth
- triggered when the link toggled interpolation change:manhattan
- triggered when the link toggled orthogonal routingchange:vertices
- triggered when the link changes its vertices array change:z
- triggered when the link is moved in the z-level (toFront and toBack)transition:start
- triggered when a transition starts.transition:end
- triggered when a transition ends.link.on('change:source', function() { alert('source of the link changed') })
JointJS supports adding labels on links. One link can have multiple labels, and each label can have different properties.
Properties recognized by JointJS are summarized in the following TypeScript-like schema:
{
markup?: string | Array<{
tagName: SVGElement,
selector?: string
}>,
attrs?: {
[key: selector]: {
[key: SVG attribute | JointJS attribute]: any
} | null
},
position?: number | {
distance?: number,
offset?: number | { x: number, y: number },
args?: {
absoluteDistance?: boolean,
reverseDistance?: boolean,
absoluteOffset?: boolean
}
}
}
The markup
property specifies the markup of the label. It can be provided either as a parsable SVG (e.g. '<rect /><text />'
), or as a JSON array (e.g.[{ tagName: 'rect' }, { tagName: 'text' }]
). The JSON allows the user to specify custom selectors for the SVGElements; these can then be used for targeting elements from within the attrs
property.
If markup
is not provided on the label, markup is taken from the Link type's defaultLabel.markup
property. A custom Link type can be created by the user, providing a defaultLabel
(see the Link
documentation for more information). However, if the used link type does not provide defaultLabel.markup
(this includes joint.dia.Link
and joint.shapes.standard.Link
), the builtin default Link markup is used, which defines markup as a JSON array with a 'body'
(a <rect>
SVGElement) under a 'label'
(a <text>
SVGElement).
The attrs
property is an object where the keys are CSS selectors (referring to custom selectors or SVGElements specified in markup
, e.g. body
in the above example). They are expected to contain objects that specify native SVG and/or JointJS special attributes (e.g. fill
), alongside the value to be assigned (e.g. 'white'
).
If the Link type provides defaultLabel.attrs
, these attrs are merged with label.attrs
. This allows you to reference selectors from defaultLabel.markup
in label.attrs
and, for example, simply add an attribute (attrs: { body: { stroke: 'black' } }
).
If the builtin default markup is used (i.e. no custom label.markup
was provided, and no defaultLabel.markup
), several builtin default attrs
are applied for reasons of backwards compatibility. These are merged with defaultLabel.attrs
(if present on the Link prototype) and then label.attrs
(if provided). See Link
documentation for more information.
Finally, the position
property specifies the position of the label, relative to the SVG path of the link. It may be defined as a number or as an object with distance
and optionally offset
and args
properties. If no position
is provided, the builtin default ({ distance: 0.5 }
) is used to maintain backwards compatibility.
number |
|
||||||||||||||||||||||
object |
If
|
The shape of a link is determined by five properties - source
, target
, vertices
, connector
and router
.
The source
and target
properties have to be provided when creating a Link. Either an Element can be provided (either directly or via an id
property) or a Point (with x
and y
properties).
link.source(rect);
link.source({ id: rect.id });
link.source(new g.Point(100, 100));
link.source({ x: 100, y: 100 });
If the end is specified as an Element, a specific subelement on that element may be identified for use as the link end. The selector
property allows specifying the subelement with a selector string, while the magnet
property uses magnet id, and the port
property uses the port id.
For the purposes of link geometry, however, the most important are the anchor
and connectionPoint
properties of link end elements. The connectionStrategy
paper option is also relevant to mention in this context.
If the link end (source/target) is specified as an Element (whether or not one of the subelement specifications is in effect), the precise position of the link end's anchor may be specified by the anchor
property. (If the link end is specified as a Point, its coordinates are used as its anchor directly.) Every link has two anchors; one at the source end and one at the target end.
A link end anchor is a point inside a given (sub)element that the link path wants to connect to at that source/target end - if it were not obstructed by the body of the element itself (it is the role of connectionPoints to take the end element into account). Alongside link vertices, source and target anchors determine the basic link path. Then, it is the job of connectionPoints, routers, and connectors to modify that path to make it look good.
The anchor functions reference the end element to find the anchor point - e.g. the center of the end element, or its top-right corner. Notably, anchor functions also allow you to offset found anchor points by a custom distance in both dimensions from the standard position (e.g. 10 pixels to the right and 20 pixels below the center of an end element). Several pre-made anchors are provided inside the JointJS library in the joint.anchors
namespace.
link.source(rect, {
anchor: {
name: 'bottomLeft',
args: {
dx: 20,
dy: -10
}
}
});
If an anchor function is not provided, the defaultAnchor
paper option is used instead. The joint.anchors.center
function is used by default.
The link end's connection point may be specified by the connectionPoint
property. Every link has two connection points; one at the source end and one at the target end.
A link connection point is the point the the link path actually ends at, taking the end element into account. This point will always lie on the link path (the line connecting link anchors and vertices together, in order).
The connectionPoints are found by considering intersections between the link path and a desired feature of the end element (e.g. bounding box, shape boundary, anchor). Although connectionPoints are not capable of being offset off the link path (anchors should be used to modify the link path if this is required), they can be offset along the path - e.g. to form a gap between the element and the actual link. Several pre-made connectionPoints are provided in the JointJS library in the joint.connectionPoints
namespace.
link.source(rect, {
connectionPoint: {
name: 'boundary',
args: {
offset: 5
}
}
});
If a connection point function is not provided, the defaultConnectionPoint
paper option is used instead. The joint.connectionPoints.bbox
function is used by default.
Related to anchors and connectionPoints is the connectionStrategy
paper option. It allows you to specify which anchor
and connectionPoint
properties should be assigned to end elements in response to user interaction (e.g. in response to dragging a link arrowhead onto a new element). This setting is necessary because assigned anchor
and connectionPoint
are not preserved when the end element is reassigned by the user - and the paper's defaultAnchor
and defaultConnectionPoint
are used instead.
Several pre-made connectionStrategies are provided inside the JointJS library in the joint.connectionStrategies
namespace, but you may find it necessary to create your own custom connection strategies. This is a paper-level setting; connectionStrategies not assigned on a link-by-link basis.
paper.options.connectionStrategy = joint.connectionStrategies.pinAbsolute;
If a connection strategy is not provided, the joint.connectionStrategies.useDefaults
function is used by default.
The vertices
array is an array of user-defined points for the link to pass through. Alongside the source and target anchors, the link vertices determine the basic link path. This skeleton path is then used for determining the link route. The vertices can be accessed with the link.vertices()
function and related functions.
link.vertices();
link.vertices([{ x: 100, y: 120 }, { x: 150, y: 60 }]);
Routers take an array of link vertices and transform them into an array of route points that the link should go through. This route is then used for generating the connection SVG path commands. The router
property of a link can be accessed with the link.router()
function.
A collection of pre-made routers is provided inside the JointJS library in the joint.routers
namespace. This includes smart routers
that are able to automatically avoid obstacles (elements) in their way.
link.router('manhattan', {
excludeEnds: ['source'],
excludeTypes: ['myNamespace.MyCommentElement'],
startDirections: ['top'],
endDirections: ['bottom']
});
If a router is not provided, the defaultRouter
paper option is used instead. The joint.routers.normal
function is used by default.
Connectors take an array of link route points and generate SVG path commands so that the link can be rendered. The connector
property of a link can be accessed with the link.connector()
function.
A collection of pre-made connectors is provided inside the JointJS library in the joint.connectors
namespace.
link.connector('rounded', {
raw: true,
radius: 20
});
If a connector is not provided, the defaultConnector
paper option is used instead. The joint.connectors.normal
function is used by default.
Note that the modular architecture of JointJS allows mixing-and-matching connectors with routers as desired; for example, a link may be specified to use the jumpover
connector on top of the manhattan
router:
var link = new joint.shapes.standard.Link();
link.source(rect);
link.target(rect2);
link.router('manhattan');
link.connector('jumpover');
Styling of the link is contained in the attrs
property which has exactly the same structure as the attrs
property of elements. Please refer to the joint.dia.Element and joint.dia.Link sections of this page for more information.
Links also have the z
property which specifies the z-level of the link. It has exactly the same meaning as the z
property of elements.
link.addTo(graph)
Add the link to the graph
(an instance of joint.dia.Graph
). This is equivalent to calling graph.addCell(link)
.
link.appendLabel(label [, opt])
Add a new label
at the end of the labels
array.
link.attr(attrs)
Set SVG attributes on subelements. This is a method analogous to attr method of Joint.dia.Element
. The keys of the attrs
object are CSS selectors matching the SVG element the link consists of. The values are objects containing SVG attributes and their values. attrs
object will be mixined with attrs
property of the link
model. This is a convenient way of rewriting only some of the attributes of the SVG elements. For overwritting all attributes of all SVG elements, use link.set('attrs', attrs)
. Here it is important to mention how the markup of a link looks like:
<path class="connection"/>
<path class="marker-source"/>
<path class="marker-target"/>
<path class="connection-wrap"/>
<g class="labels" />
<g class="marker-vertices"/>
<g class="marker-arrowheads"/>
<g class="link-tools" />
As you can see, the link consists of a couple of SVG path elements and couple of SVG group elements:
.connection
is the actual line of the link..connection-wrap
is an SVG path element that covers the .connection
element and is usually thicker so that the link is able to
handle pointer events (mousedown, mousemove, mouseup) that didn't target the thin .connection
path exactly. This makes it easy
to "grab" the link even though the mouse cursor didn't point exactly at the (usually thin) .connection
path element..marker-source
and .marker-target
are the arrowheads of the link.link.attr({
'.connection': { stroke: 'blue' },
'.marker-source': { fill: 'red', d: 'M 10 0 L 0 5 L 10 10 z' },
'.marker-target': { fill: 'yellow', d: 'M 10 0 L 0 5 L 10 10 z' }
});
An alternative call using a string path and a value:
link.attr('.marker-source/fill', 'green');
link.clone()
Returns a new instance of the link with identical attributes.
link.connector()
Return a shallow copy of the connector
property of the link.
For backwards compatibility, if there is no connector, the function also checks whether the legacy smooth
property is set on the link and returns { name: smooth }
if it is.
link.connector(connector [, opt])
Set the connector
of the link.
If the connector
argument is an object, it is expected to have the form { name: connectorName, args?: connectorArgs }
. Here connectorName
is expected to match either the name of a built-in connector or the name of a custom connector.
If the connector
argument is a function, it is expected to define a custom connector with the signature function(sourcePoint, targetPoint, vertices, connectorArgs, linkView)
that returns a string representing the SVG path data that will be used to render the link.
link.connector(connectorName [, connectorArgs, opt])
Set the connector
of the link to have the value { name: connectorName, args: connectorArgs }
.
The connectorName
string is expected to match either the name of a built-in connector or the name of a custom connector. The connectorArgs
parameter is optional.
link.disconnect()
Disconnect the link from its source
and target
elements. The source
and target
then become a point at [0,0]
.
link.findView(paper)
Find view (joint.dia.LinkView
) for the link model in the paper
. This is a shortcut to the equivalent call paper.findViewByModel(link)
.
link.getAncestors()
Return an array of all the ancestors of this link starting from the immediate parent all the way up to the most distant ancestor.
link.getSourceElement()
Return the source element of the link or null
if there is none.
link.getTargetElement()
Return the target element of the link or null
if there is none.
link.getTransitions()
Return an array of all active transitions (their paths).
link.hasLoop([opt])
Return true
if this link is a loop link
. In a loop link
source
and target
are equal.
If opt.deep
is true
, the notion of a loop link
is extended to a deep hierarchy. For example, if the link connects a parent element with one of its embedded elements, the link is considered a loop link
, as well.
link.insertLabel(index, label [, opt])
Add a new label
at index
. Pass index -1
to add the label at the end of the labels array.
link.insertVertex(index, vertex [, opt])
Add a new vertex
at index
. Pass index -1
to add the vertex at the end of the vertices array.
link.isElement()
Always returns false
. The reason the method is here is that both joint.dia.Element
and joint.dia.Link
inherit from joint.dia.Cell
. This method is useful if you don't know what the cell is. Calling cell.isElement()
is equivalent to cell instanceof joint.dia.Element
. Example:
var cell = graph.getCell(myId)
if (cell.isElement()) {
// Do something if the cell is an element.
}
link.isEmbeddedIn(element [, opt])
Return true
if the link is embedded in an element element
.
If opt.deep
is false
, only direct parentage will be checked. opt.deep
is true
by default.
link.isLink()
Always returns true
. The reason the method is here is that both joint.dia.Element
and joint.dia.Link
inherit from joint.dia.Cell
. This method is useful if you don't know what the cell is. Calling cell.isLink()
is equivalent to cell instanceof joint.dia.Link
. Example:
var cell = graph.getCell(myId)
if (cell.isLink()) {
// Do something if the cell is a link.
}
link.label(index)
Return the label at index
.
link.label(index, properties [, opt])
Update properties
of the label at index
. By default, the new properties are merged into the old ones; pass the { rewrite: true }
option along to disregard old properties.
Example usage:
link.label(0, {
markup: [
{
tagName: 'rect',
selector: 'body'
}, {
tagName: 'text',
selector: 'label'
}
],
attrs: {
body: {
fill: 'white' // white background
},
label: {
text: 'my label', // text to show
fill: 'blue' // blue text
}
},
position: {
distance: 0.5, // midway on the connection path
offset: {
x: 10, // 10 local x units to the right
y: -5 // 5 local y units above
}
}
});
Note that all labels are stored in an array on the link model under the attribute labels
. Use the link.labels
function to access the array.
link.labels()
Return a shallow copy of labels array.
link.labels(labelsArray [, opt])
Set array of labels on the link.
link.prop(properties)
Set properties, possibly nested, on the element model. This is equivalent to the attr() method but this time for custom data properties.
link.prop('name/first', 'John')
link.prop('name/first') // 'John'
link.prop({ name: { first: 'John' } })
// Nested arrays are supported too:
link.prop('mylist/0/data/0/value', 50)
link.prop({ mylist: [ { data: [ { value: 50 } ] } ] })
As you can see, this is the exact same method as the joint.dia.Element.prop() method.
link.remove()
Remove the link from the graph.
link.removeAttr(path [, opt])
Remove a previously set attribute from the link. path
can either be a string that specifies the path to the (possibly nested) attribute to be removed, or an array of more paths. The associated link view makes sure the link gets re-rendered properly.
If opt
is passed, it can contain data that is passed over to the event listeners for the change:attrs
event triggered on the link itself and also on the graph the link is in.
link.removeLabel(index [, opt])
Remove label
at index
. Pass index -1
to remove the last label of the labels array.
link.removeVertex(index [, opt])
Remove vertex
at index
. Pass index -1
to remove the last vertex of the vertices array.
link.reparent()
Automatically find and set the best parent element for the link so that when the parent element is moved, the link and all its vertices are moved too. The best parent is determined as the common ancestor of the source and target elements of the link. Useful for hierarchical diagrams. See the DEVS demo on how this can be used.
link.router()
Return a shallow copy of the router
property of the link.
For backwards compatibility, if there is no router, the function also checks whether the legacy manhattan
property is set on the link and returns { name: orthogonal }
if it is.
link.router(router [, opt])
Set the router
of the link.
If the router
argument is an object, it is expected to have the form { name: routerName, args?: routerArgs }
. Here routerName
is expected to match either the name of a built-in router or the name of a custom router.
If the router
argument is a function, it is expected to define a custom router with the signature function(vertices, routerArgs, linkView)
that returns an array of route points.
link.router(routerName [, routerArgs, opt])
Set the router
of the link to have the value { name: routerName, args: routerArgs }
.
The routerName
string is expected to match either the name of a built-in router or the name of a custom router. The routerArgs
parameter is optional.
link.scale(sx, sy, origin [, opt])
Scales the link's points (vertices) relative to the given origin.
link.source()
Return a shallow copy of the source
property of the link.
If the beginning of the link is connected to an element, an object in the format { id: elementID }
is returned. If the beginning of the link is specified as a point instead (the link is pinned
to the paper at that point), an object in the format { x: sourceX, y: sourceY }
is returned. Furthermore, any additional arguments of the source are returned alongside those properties.
If you need to be sure that an Element is returned (and not a Point), use the link.getSourceElement
function instead.
link.source(source [, opt])
Set the source
of the link.
If the link is to be connected to an element, send an object in the format { id: element.id }
(or a joint.dia.Element
object). If the link is to be pinned to the paper, send an object in the format { x: sourceX, y: sourceY }
(or a g.Point
object).
link.source(rect);
link.source({ id: rect.id });
link.source(new g.Point(100, 100));
link.source({ x: 100, y: 100 });
Additional options may by provided to further specify the behavior of link at the source:
link.source(rect, {
selector: 'body',
anchor: {
name: 'bottomLeft',
args: {
dx: 20,
dy: -10
}
}
});
More information can be found in dia.Link
documentation.
link.stopTransitions([path])
Stops all running transitions. If parameter path
is provided, it will stop only transitions specified by this path.
link.target()
Return a shallow copy of the target
property of the link.
If the ending of the link is connected to an element, an object in the format { id: elementID }
is returned. If the ending of the link is specified as a point instead (the link is pinned
to the paper at that point), an object in the format { x: targetX, y: targetY }
is returned. Furthermore, any additional arguments of the target are returned alongside those properties.
If you need to be sure that an Element is returned (and not a Point), use the link.getTargetElement
function instead.
link.target(target [, opt])
Set the target
of the link.
If the link is to be connected to an element, send an object in the format { id: element.id }
(or a joint.dia.Element
object). If the link is to be pinned to the paper, send an object in the format { x: targetX, y: targetY }
(or a g.Point
object).
link.target(rect);
link.target({ id: rect.id });
link.target(new g.Point(100, 100));
link.target({ x: 100, y: 100 });
Additional options may by provided to further specify the behavior of link at the target:
link.target(rect, {
selector: 'body',
anchor: {
name: 'bottomLeft',
args: {
dx: 20,
dy: -10
}
}
});
More information can be found in dia.Link
documentation.
link.toBack()
Move the link so it is behind all other cells (elements/links). This is a method analogous to toBack method of Joint.dia.Element
.
link.toFront()
Move the element so it is on top of all other cells (elements/links). This is a method analogous to toFront method of Joint.dia.Element
.
link.toJSON()
Return a copy of the link's attributes for JSON serialization. This is a method analogous to toJSON method of Joint.dia.Element
.
link.transition(path, value [, opt])
Allows changing of the link properties gradually over a period of time. This is method is analogous to the transition method of joint.dia.Element
.
link.transition('target', { x: 250, y: 250 }, {
delay: 100,
duration: 500,
timingFunction: joint.util.timing.bounce,
valueFunction: joint.util.interpolate.object
});
// will start changing the link target coordinates in 100ms, for period of 500ms and performing a bounce effect.
link.translate(tx, ty [, opt])
Translate the link vertices (and source and target if they are points) by tx
pixels in the x-axis and ty
pixels in the y-axis.
If opt
object is passed, it can contain data that is passed over the the event listeners for the change event on the link or graph.
link.vertex(index)
Return the vertex at index
.
link.vertex(index, vertex [, opt])
Update the vertex at index
with value of vertex
. By default the new value is merged into the old value. Pass the { rewrite: true }
option along to disregard the old value.
A vertex has only two properties, x
and y
. It may be defined as a g.Point object.
Example vertex:
link.vertex(0, {
x: 100,
y: 200
});
Note that all vertices are stored in an array on the link model under the attribute vertices
. Use the link.vertices
function to access the array.
link.vertices()
Return a shallow copy of vertices array.
link.vertices(verticesArray [, opt])
Set array of vertices on the link.
The view for the joint.dia.Link model. It inherits from joint.dia.CellView and is responsible for:
To find the view associated with a specific link model, use the paper.findViewByModel()
method:
var linkView = paper.findViewByModel(link);
It is possible to use a custom default link view for all your links in a paper. This can be set up via the linkView
option on the paper object. Several options in joint.dia.LinkView
may be overridden in a custom LinkView:
105
.longLinkLength
). Defaults to false
.doubleLinkTools: true
, render link tools on both ends of the link. Defaults to 155
.40
.longLinkLength
and doubleLinkTools: true
. Defaults to 65
.A custom LinkView type may also override default LinkView event handlers, or provide new ones. It may be necessary to modify the interactive
paper option to prevent interference from builtin event handlers (most notably vertexAdd
which listens for pointerdown events).
Example:
var CustomLinkView = joint.dia.LinkView.extend({
// custom interactions:
pointerdblclick: function(evt, x, y) {
this.addVertex(x, y);
},
contextmenu: function(evt, x, y) {
this.addLabel(x, y);
},
// custom options:
options: joint.util.defaults({
doubleLinkTools: true,
}, joint.dia.LinkView.prototype.options)
});
var paper = new joint.dia.Paper({
//...
linkView: CustomLinkView,
interactive: { vertexAdd: false } // disable default vertexAdd interaction
});
linkView.addLabel(x, y [, opt])
Add a new default label to the link at the coordinates provided. If you need to add a label with custom markup or properties, use the link.addLabel()
function instead.
This method uses the linkView.getLabelPosition()
function to determine the new label's position
. By default, position.distance
is recorded relative to connection length (as a number in the [0,1]
range), and position.offset
is set relative to the connection (as a number). This behavior may be changed by providing an opt
object with some of the accepted boolean flags:
absoluteDistance: true
records distance
absolutely (as distance from beginning of link)reverseDistance: true
switches distance
to be calculated from end of link, if absoluteDistance
absoluteOffset: true
records offset
absolutely (as x
and y
from connection)The opt
object passed to the label is recorded as label.position.args
. The label uses these options during subsequent labelMove interactions.
This function is useful within custom linkView
event listener definitions:
var CustomLinkView = joint.dia.LinkView.extend({
contextmenu: function(evt, x, y) {
this.addLabel(x, y, {
absoluteDistance: true,
reverseDistance: true,
absoluteOffset: true
});
}
});
var paper = new joint.dia.Paper({
// ...
linkView: CustomLinkView,
interactive: { vertexAdd: false } // disable default vertexAdd interaction
});
linkView.addTools(toolsView)
Add the provided toolsView
(of the joint.dia.ToolsView
type) to the link view.
Adding a tools view to a link view is the last (third) step in the process of setting up link tools on a link view:
// 1) creating link tools
var verticesTool = new joint.linkTools.Vertices();
var segmentsTool = new joint.linkTools.Segments();
var boundaryTool = new joint.linkTools.Boundary();
// 2) creating a tools view
var toolsView = new joint.dia.ToolsView({
name: 'basic-tools',
tools: [verticesTool, segmentsTool, boundaryTool]
});
// 3) attaching to a link view
var linkView = link.findView(paper);
linkView.addTools(toolsView);
Every link view we want to attach to requires its own tools view object (ToolsView
objects are automatically reassigned to the last link view they are added to). Similarly, every tools view we create requires its own set of tools (ToolView
objects are automatically reassigned to the last toolsView.tools
array they were made part of).
The link tools are added in the visible state. Use the linkView.hideTools
function if this behavior is not desirable (e.g. if you want the link tools to appear in response to user interaction). Example:
linkView.addTools(toolsView);
linkView.hideTools();
paper.on('link:mouseenter', function(linkView) {
linkView.showTools();
});
paper.on('link:mouseleave', function(linkView) {
linkView.hideTools();
});
linkView.addVertex(x, y)
Add a new default vertex to the link at the coordinates provided, and let the linkView automatically determine the index of the new vertex in the vertices array. If you need to add the vertex at a custom index, use the link.addVertex()
function instead.
This method uses the linkView.getVertexIndex()
function to determine the index of the new vertex in the vertices
array. The linkView checks the distance of vertices in the link.vertices
array from the beginning of path and compares it to the distance of the added vertex. The new vertex is inserted before the first farther vertex in the vertices
array.
This function is useful within custom linkView
event listener definitions. The following example adds a new vertex on a double click event, instead of a pointerdown event (which is the default behavior):
var CustomLinkView = joint.dia.LinkView.extend({
pointerdblclick: function(evt, x, y) {
this.addVertex(x, y);
}
});
var paper = new joint.dia.Paper({
// ...
linkView: CustomLinkView,
interactive: { vertexAdd: false } // disable default vertexAdd interaction
});
linkView.getBBox()
Return the bounding box of the linkView.
linkView.getClosestPoint(point)
Return the point on the connection that lies closest to point
.
linkView.getClosestPointLength(point)
Return the length of the connection up to the point that lies closest to point
.
linkView.getClosestPointRatio(point)
Return the ratio (normalized length) of the connection up to the point that lies closest to point
. The returned value lies in the interval [0,1]
(inclusive).
linkView.getConnection()
Return a geometric representation of the connection (instance of g.Path).
linkView.getConnectionLength()
Return a cached total length of the connection in pixels.
linkView.getConnectionSubdivisions()
Return a cached array of segment subdivision arrays of the connection. (See g.Path.prototype.getSegmentSubdivisons()
documentation for more information.)
linkView.getLabelCoordinates(labelPosition)
Return the x
and y
coordinates based on the provided labelPosition
object.
See link.label()
documentation for more information about the position
object.
An object in the format { x: number, y: number }
is returned.
linkView.getLabelPosition(x, y [, opt])
Return a label position
object based on the x
and y
coordinates provided.
The function translates the provided coordinates into an object with two fields:
distance
- the distance (following the line) of the point on the line that is closest to point x,y
.offset
- the distance between the closest point and the point x,y
.By default, position.distance
is set relative to connection length (as a number in the [0,1]
range that records the length ratio), and position.offset
is set relative to the connection (as a number recording the perpendicular distance). The user may change this behavior by providing an opt
object with some of the following accepted boolean flags:
absoluteDistance: true
- record distance
absolutely (as absolute distance from beginning of link, a positive number).reverseDistance: true
- if absoluteDistance: true
, record distance
absolutely from end of link (as a negative number).absoluteOffset: true
- record offset
absolutely (as x
and y
distance from closest point).Please note that if absoluteOffset
is not set (i.e. the default option), label can only be placed/moved in the area that is reachable by lines perpendicular to the link (that is, the label cannot be moved beyond link endpoints).
The opt
object passed to the label is recorded as label.position.args
. The label uses these options during subsequent labelMove interactions.
An object in the following format is returned:
{
distance: number,
offset: number | { x: number, y: number },
args?: {
absoluteDistance?: boolean,
reverseDistance?: boolean,
absoluteOffset?: boolean
}
}
See link.label()
documentation for more information about the position
object.
This function can be used to add a custom label to the link.labels
array, in situations when the linkView.addLabel()
function is not sufficient. For example:
var CustomLinkView = joint.dia.LinkView.extend({
contextmenu: function(evt, x, y) {
var idx = -1; // add at end of `labels`
var label = {
markup: '<g class="label"><circle /><path /></g>',
position: this.getLabelPosition(x, y, { absoluteOffset: true }),
attrs: {
circle: {
r: 15,
fill: 'lightgray',
stroke: 'black',
strokeWidth: 2
},
path: {
d: 'M 0 -15 0 -35 20 -35',
stroke: 'black',
strokeWidth: 2,
fill: 'none'
}
}
}
this.model.addLabel(idx, label);
}
});
var paper = new joint.dia.Paper({
//...
linkView: CustomLinkView,
interactive: { vertexAdd: false }
});
linkView.getPointAtLength(length)
Return the point on the path that lies length
away from the beginning of the connection.
linkView.getPointAtRatio(ratio)
Return the point on the path that lies ratio
(normalized length) away from the beginning of the connection.
linkView.getSerializedConnection()
Return a cached path data of the connection (the value of the 'd'
SVGPathElement attribute).
linkView.getTangentAtLength(length)
Return a line tangent to the path at point that lies length
away from the beginning of the connection.
linkView.getTangentAtRatio(ratio)
Return a line tangent to the path at point that lies ratio
(normalized length) away from the beginning of the connection.
linkView.getVertexIndex(x, y)
Return the vertices
array index at which to insert a new vertex with the provided x
and y
coordinates.
The linkView finds the point on the connection that lies closest to the point x,y
. Then, the linkView iterates over the vertices in the link.vertices
array until one is found that lies farther than the identified closest point. The index of the farther point is returned.
The returned index can be used as the first argument of the link.addVertex
function.
linkView.hasTools()
Return true
if this link view has a tools view attached.
linkView.hasTools(name)
Return true
if this link view has a tools view of the provided name
attached.
linkView.hideTools()
Hide all tools attached to this link view.
linkView.removeRedundantLinearVertices([opt])
Remove any redundant vertices from the model's vertices
array. Return the number of removed vertices.
A vertex is considered redundant
if it lies on the straight line formed by the vertex that immediately precedes it and the vertex that immediately follows it. (Intuitively speaking, a vertex is considered redundant
if its removal from the link does not change the shape of the link.)
linkView.removeTools()
Remove the tools view attached to this link view.
linkView.sendToken(token [, opt, callback])
Send a token along the link. token
is an SVG element (or Vectorizer element) that will be animated along the link path for opt.duration
milliseconds (default is 1000ms). The callback
function will be called once the token reaches the end of the link path.
opt.direction
specifies whether the animation should be played forwards ('normal'
- from the link source to target, the default) or backwards ('reverse'
).
Use opt.connection
to specify the SVGPathElement for the token to follow. It expects a string selector, e.g. '.connection'
.
// Send an SVG circle token along the link.
var vCircle = V('circle', { r: 7, fill: 'green' });
link.findView(paper).sendToken(vCircle, { duration: 500, direction: 'reverse' }, function() {
console.log('animation end');
});
Note that in the code above, we use the Vectorizer mini-library to create the SVG circle
element.
See the Petri Net simulator demo for a full working example.
linkView.showTools()
Show all tools attached to this link view.
linkView.sourceAnchor
A prototype variable. Contains a g.Point that records the position of the source anchor of the link, as determined by the anchor function specified on the link's source.
linkView.sourceBBox
A prototype variable. Contains a g.Rect that records the position and dimensions of the bounding box of the source magnet (element/subelement/port), as determined by the link's source definition.
If the source is defined as a point, a g.Rect is returned that records the position of the point and has the dimensions (1,1).
linkView.sourcePoint
A prototype variable. Contains a g.Point that records the position of the source connection point of the link, as determined by the connection point function specified on the link's source.
linkView.targetAnchor
A prototype variable. Contains a g.Point that records the position of the target anchor of the link, as determined by the anchor function specified on the link's target.
linkView.targetBBox
A prototype variable. Contains a g.Rect that records the position and dimensions of the bounding box of the target magnet (element/subelement/port), as determined by the link's target definition.
If the target is defined as a point, a g.Rect is returned that records the position of the point and has the dimensions (1,1).
linkView.targetPoint
A prototype variable. Contains a g.Point that records the position of the target connection point of the link, as determined by the connection point function specified on the link's target.
joint.dia.Paper is the view for the joint.dia.Graph
model. It inherits from Backbone View. Accepts an options object in its constructor with numerous settings.
When a paper is associated with a graph, the paper makes sure that all the cells added to the graph are automatically rendered.
var graph = new joint.dia.Graph
var paper = new joint.dia.Paper({
el: $('#paper'),
width: 600,
height: 400,
gridSize: 10,
model: graph
});
var rect = new joint.shapes.basic.Rect({
position: { x: 50, y: 70 },
size: { width: 100, height: 40 }
});
graph.addCell(rect);
Paper automatically handles this change and renders the rectangle to the SVG document that it internally holds.
The following list contains events that you can react on in a paper:
pointerdblclick |
Triggered when pointer is double-clicked on a target (a The callback function is passed
|
||||||||
---|---|---|---|---|---|---|---|---|---|
pointerclick |
Triggered when pointer is clicked on a target without pointer movement (a The callback function is passed
|
||||||||
contextmenu |
Triggered when pointer is right-clicked on a target (a The callback function is passed
|
||||||||
pointerdown |
Triggered when pointer is pressed down on a target (a The callback function is passed
|
||||||||
pointermove |
Triggered when pointer is moved over a target while pressed down (a The callback function is passed
|
||||||||
pointerup |
Triggered when pointer is released on a target after being pressed down (a The callback function is passed
Calling |
||||||||
mouseover |
Triggered when pointer begins to hover directly over a target. The callback function is passed
|
||||||||
mouseout |
Triggered when pointer ceases to hover directly over a target. The callback function is passed
|
||||||||
mouseenter |
Triggered when pointer enters the area above a target. The callback function is passed
|
||||||||
mouseleave |
Triggered when pointer leaves the area above a target. The callback function is passed
|
||||||||
mousewheel |
Triggered when mouse wheel is rotated while pointer is on a target. The callback function is passed
|
||||||||
magnet |
Triggered when interacting with a magnet target. The callback function is passed
|
||||||||
cell:highlight |
Triggered when the The callback function is passed The default handler method adds the This method is also called automatically, in two situations. First, if the user reconnects a link and the connection is valid as determined by the |
||||||||
cell:unhighlight |
Triggered when the The callback function is passed The default handler method removes the It is important to note that if a cell was highlighted using custom options, those exact same options must be provided to the unhighlight handler. |
||||||||
link:connect |
Triggered when a link is connected to a cell. The callback function is passed |
||||||||
link:disconnect |
Triggered when a link is disconnected from a cell. The callback function is passed |
||||||||
rendered:done | Triggered when the paper has finished rendering all cell views in case async rendering is enabled. | ||||||||
[custom] | Custom cell event can be triggered on pointerdown with Event attribute. Calling evt.stopPropagation() prevents triggering all subsequent events. |
An example of a simple blank:pointerdown
event listener:
paper.on('blank:pointerdown', function(evt, x, y) {
alert('pointerdown on a blank area in the paper.')
})
Consecutive pointerdown
, pointermove
and pointerup
events can share information through the evt.data
object:
// Create a new link by dragging
paper.on({
'blank:pointerdown': function(evt, x, y) {
var link = new joint.dia.Link();
link.set('source', { x: x, y: y });
link.set('target', { x: x, y: y });
link.addTo(this.model);
evt.data = { link: link, x: x, y: y };
},
'blank:pointermove': function(evt, x, y) {
evt.data.link.set('target', { x: x, y: y });
},
'blank:pointerup': function(evt) {
var target = evt.data.link.get('target');
if (evt.data.x === target.x && evt.data.y === target.y) {
// remove zero-length links
evt.data.link.remove();
}
}
});
paper.cancelRenderViews()
When the method is called any asynchronous rendering in progress is canceled.
paper.clearGrid()
Hide the current grid.
paper.clientOffset()
Returns coordinates of the paper viewport, relative to the application's client area.
paper.clientToLocalPoint(p)
Transform client coordinates represented by point p
to the paper local coordinates.
This is especially useful when you have a mouse event object and want coordinates
inside the paper that correspond to event clientX
and clientY
point.
var localPoint1 = paper.clientToLocalPoint({ x: evt.clientX, y: evt.clientY });
// alternative method signature
var localPoint2 = paper.clientToLocalPoint(evt.clientX, evt.clientY);
paper.clientToLocalRect(rect)
Transform the rectangle rect
defined in the client coordinate system to the local coordinate system.
var bcr = paper.svg.getBoundingClientRect();
var localRect1 = paper.clientToLocalRect({ x: bcr.left, y: bcr.top, width: bcr.width, height: bcr.height });
// alternative method signature
var localRect2 = paper.clientToLocalRect(bcr.left, bcr.top, bcr.width, bcr.height);
// Move the element to the center of the paper viewport.
var localCenter = localRect1.center();
var elSize = element.size();
element.position(localCenter.x - elSize.width, localCenter.y - elSize.height);
paper.defineFilter(filterDefinition)
Define an SVG filter for later reuse within the paper. The method returns the filter id and the filterDefinition
must have the following form:
{
name: <name of the filter>,
args: <filter arguments>
}
Where name
is the name of the filter. See below for the list of built-in filters. args
is an object containing filter parameters. These parameters are dependent on the filter used and are described in the list below as well. Example usage:
var filterId = paper.defineFilter({
name: 'dropShadow',
args: {
dx: 2,
dy: 2,
blur: 3
}
});
svgNode.setAttribute('filter', 'url(#' + filterId + ');
The following is the list of built-in filters. All these filters are defined in the joint.util.filter
namespace. This namespace can be extended simply by adding a new method to it with one argument, an object with filter parameters, returning a string representing the SVG filter definition.
blur
x
- horizontal blury
- vertical blur [optional, if not defined y
is the same as x
]dropShadow
dx
- horizontal shiftdy
- vertical shiftblur
- blurcolor
- coloropacity
- opacitygrayscale
amount
- the proportion of the conversion. 1
is completely grayscale. 0
leaves the element unchanged.sepia
amount
- the proportion of the conversion. 1
is completely sepia. 0
leaves the element unchanged.saturate
amount
- the proportion of the conversion. 0
is completely un-saturated. 1
leaves the element unchanged.hueRotate
angle
- the number of degrees around the color circle the input samples will be adjustedinvert
amount
- the proportion of the conversion. 1
is completely inverted. 0
leaves the element unchanged.brightness
amount
- the proportion of the conversion. 0
makes the element completely black. 1
leaves the element unchanged.contrast
amount
- the proportion of the conversion. 0
makes the element completely black. 1
leaves the element unchanged.paper.defineGradient(gradientDefinition)
Define an SVG gradient for later reuse within the paper. The method returns the gradient id and the gradientDefinition
must have the following form:
{
type: <type of gradient>,
stops: <stop colors>,
attrs: <additional attributes>
}
Where type
is either 'linearGradient'
or 'radialGradient'
, attrs
is an object containing additional SVG attributes for the SVG gradient element and stops
is an array of the ramps of color on the gradient. Each stop object is of the form:
{
offset: <offset>,
color: <color>,
opacity: <opacity>
}
Where offset
is a string representing the offset of the gradient stop, color
indicates what
color to use at that gradient stop and opacity
is a number in the [0..1] range representing the
transparency of the stop color.
Example use:
var gradientId = paper.defineGradient({
type: 'linearGradient',
stops: [
{ offset: '0%', color: '#E67E22' },
{ offset: '20%', color: '#D35400' },
{ offset: '40%', color: '#E74C3C' },
{ offset: '60%', color: '#C0392B' },
{ offset: '80%', color: '#F39C12' }
]
});
svgNode.setAttribute('fill', 'url(#' + gradientId + ')');
For an introduction to gradients, please refer to the tutorial on Filters and Gradients.
paper.defineMarker(markerDefinition)
Define an SVG marker for later reuse within the paper. The method returns the marker id and the markerDefinition
is an object with type
property and any other visual attributes. The valid values for type
are 'path'
, 'circle'
, 'ellipse'
, 'rect'
, 'polyline'
and 'polygon'
.
var markerId = paper.defineMarker({
type: 'path', // SVG Path
fill: '#666',
stroke: '#333',
// The coordinate system for defining the path data
// ------------------------------------------------
// 0,0: marker-start, marker-end or marker-mid
// n,0: n > 0 in path direction
// n < 0 opposite path direction
// 0,m: m > 0 left to the path direction
// m < 0 right to the path direction
d: 'M 10 -10 0 0 10 10 z'
});
// Draw an arrow at the start and the end of a path
svgPath.setAttribute('marker-start', 'url(#' + markerId + ')');
svgPath.setAttribute('marker-end', 'url(#' + markerId + ')');
paper.drawBackground(opt);
Sets the paper background defined by the opt
object. Please see the background paper option for available configuration.
paper.drawGrid([opt])
Draw visual grid lines on the paper. Possible options:
paper.findView(element)
Find a view (instance of joint.dia.ElementView
or joint.dia.LinkView
) associated with a DOM element in the paper. element
can either be a DOM element, jQuery object or a CSS selector.
Sometimes, it is useful to find a view object for an element in the DOM. This method finds the closest view for any subelement of a view element.
paper.findViewByModel(model)
Find a view (instance of joint.dia.ElementView
or joint.dia.LinkView
) associated with a model. model
can either be an instance of joint.dia.Element
or joint.dia.Link
.
paper.findViewsFromPoint(point)
Find views (instance of joint.dia.ElementView
) under a certain point in the paper. point
is an object with x
and y
properties. Returns an
array of views whose bounding box contains point
. Note that there can be more then one views as views might overlap. Note there is a difference between
this method and the joint.dia.Graph:findModelsFromPoint. A bounding box of a view can be different than the area computed by an element model position
and size
.
For example, if a <text>
SVG element in the shape is positioned relatively and shifted down below the normal shape area (e.g. using the JointJS special attributes), the bounding box
of the view will be bigger than that of the model.
paper.findViewsInArea(rect [, opt])
Find views (instance of joint.dia.ElementView
) in a certain area in the paper.
rect
is an object with x
, y
, width
and height
properties.
Return an array of views whose bounding box intersects the rect
rectangle.
If opt.strict
is true
, return an array of views whose bounding box is contained within the rect
rectangle (i.e. not only intersects it).
paper.fitToContent([opt])
Expand/shrink the paper to fit the content inside it. Snap the resulting width/height to the grid defined by opt.gridWidth
/ opt.gridHeight
.
opt.padding
adds to the resulting width/height of the paper. The opt.padding
can either be a number in which case it represents the padding
on all the sides or it can be an object of the form { top: Number, right: Number, bottom: Number, left: Number }
. By default the method fits the paper to a content with positive coordinates only and sets the origin to (0,0) for the resulting paper.
To change this behaviour use the allowNewOrigin: ['negative'|'positive'|'any']
option.
Set allowNewOrigin
to 'negative'
to account for content with negative coordinates.
Set allowNewOrigin
to 'positive'
to allow origin to be set to the top-left coordinate of the content.
Set allowNewOrigin
to 'any'
to apply both. This method might internally trigger the "resize"
and "translate"
events that can be handled by listening on the paper object (paper.on('resize', myHandler)
).
opt.minWidth
and opt.minHeight
define the minium width and height of the paper
and opt.maxWidth
and opt.maxHeight
define the maximum width and height of the paper
after fitting it to the content.
You can try many of these options interactively in the paper demo.
Depracated usage: paper.fitToContent(gridWidth, gridHeight, padding, opt)
paper.getComputedSize()
Return an object containing width
and height
properties. It resolves any computation these property values may contain (e.g resolves "100%"
to the actual client width).
paper.getContentArea()
Return a rectangle representing the area occupied by paper content, in local units (without transformations).
paper.getContentBBox()
Return the bounding box of the content inside the paper, in client units (as it appears on the screen).
paper.hideTools()
Hide all tools attached to all link views on this paper.
paper.isDefined(graphicalObjectId)
Return true
if there is a graphical object (gradient, filter, marker) with graphicalObjectId
already defined within the paper. Return false
otherwise.
paper.localToClientPoint(p)
Transform the point p
defined in the local coordinate system to the client coordinate system.
var rightMidPoint = element.getBBox().rightMiddle();
var clientPoint1 = paper.localToClientPoint(rightMidPoint);
// alternative method signature
var clientPoint2 = paper.localToClientPoint(rightMidPoint.x, rightMidPoint.y);
// Draw an HTML rectangle next to the element.
var div = document.createElement('div');
div.style.position = 'fixed';
div.style.background = 'red';
div.style.left = clientPoint1.x + 'px';
div.style.top = clientPoint1.y + 'px';
div.style.width = '40px';
div.style.height = '40px';
div.style.marginLeft = '10px';
div.style.marginTop = '-20px';
document.body.appendChild(div);
paper.localToClientRect(rect)
Transform the rectangle rect
defined in local coordinate system to the client coordinate system.
var bbox = element.getBBox();
var clientRect1 = paper.localToClientRect(bbox);
// alternative method signature
var clientRect2 = paper.localToClientRect(bbox.x, bbox.y, bbox.width, bbox.height);
// Draw an HTML rectangle above the element.
var div = document.createElement('div');
div.style.position = 'fixed';
div.style.background = 'red';
div.style.left = clientRect1.x + 'px';
div.style.top = clientRect1.y + 'px';
div.style.width = clientRect1.width + 'px';
div.style.height = clientRect1.height + 'px';
paper.el.appendChild(div);
paper.localToPagePoint(p)
Transform the point p
defined in the local coordinate system to the page coordinate system.
var rightMidPoint = element.getBBox().rightMiddle();
var pagePoint1 = paper.localToPagePoint(rightMidPoint);
// alternative method signature
var pagePoint2 = paper.localToPagePoint(rightMidPoint.x, rightMidPoint.y);
// Draw an HTML rectangle next to the element.
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.background = 'red';
div.style.left = pagePoint1.x + 'px';
div.style.top = pagePoint1.y + 'px';
div.style.width = '40px';
div.style.height = '40px';
div.style.marginLeft = '10px';
div.style.marginTop = '-20px';
document.body.appendChild(div);
paper.localToPageRect(rect)
Transform the rectangle rect
defined in local coordinate system to the page coordinate system.
var bbox = element.getBBox();
var pageRect1 = paper.localToPageRect(bbox);
// alternative method signature
var pageRect2 = paper.localToPageRect(bbox.x, bbox.y, bbox.width, bbox.height);
// Draw an HTML rectangle above the element.
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.background = 'red';
div.style.left = pageRect1.x + 'px';
div.style.top = pageRect1.y + 'px';
div.style.width = pageRect1.width + 'px';
div.style.height = pageRect1.height + 'px';
document.body.appendChild(div);
paper.localToPaperPoint(p)
Transform the point p
defined in the local coordinate system to the paper coordinate system.
var rightMidPoint = element.getBBox().rightMiddle();
var paperPoint1 = paper.localToPaperPoint(rightMidPoint);
// alternative method signature
var paperPoint2 = paper.localToPaperPoint(rightMidPoint.x, rightMidPoint.y);
// Draw an HTML rectangle next to the element.
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.background = 'red';
div.style.left = paperPoint1.x + 'px';
div.style.top = paperPoint1.y + 'px';
div.style.width = '40px';
div.style.height = '40px';
div.style.marginLeft = '10px';
div.style.marginTop = '-20px';
paper.el.appendChild(div);
paper.localToPaperRect(rect)
Transform the rectangle rect
defined in the local coordinate system to the paper coordinate system.
var bbox = element.getBBox();
var paperRect1 = paper.localToPaperRect(bbox);
// alternative method signature
var paperRect2 = paper.localToPaperRect(bbox.x, bbox.y, bbox.width, bbox.height);
// Draw an HTML rectangle above the element.
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.background = 'red';
div.style.left = paperRect1.x + 'px';
div.style.top = paperRect1.y + 'px';
div.style.width = paperRect1.width + 'px';
div.style.height = paperRect1.height + 'px';
paper.el.appendChild(div);
paper.matrix([SVGMatrix])
When called with no parameter, the method returns the current transformation matrix (instance of SVGMatrix) of the paper. It sets the new viewport transformation based on the SVGMatrix
otherwise.
paper.matrix({ a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 }); // scale the paper twice
paper.pageOffset()
Returns coordinates of the paper viewport, relative to the document.
paper.pageToLocalPoint(p)
Transform the point p
defined in the page coordinate system to the local coordinate system.
paper.on('blank:pointerup', function(evt) {
var pagePoint = g.Point(evt.pageX, evt.pageY);
var localPoint1 = this.pageToLocalPoint(pagePoint);
// alternative method signature
var localPoint2 = this.pageToLocalPoint(evt.pageX, evt.pageY);
// Move the element to the point, where the user just clicks.
element.position(localPoint1.x, localPoint1.y);
});
paper.pageToLocalRect(rect)
Transform the rectangle rect
defined in the page coordinate system to the local coordinate system.
var x, y;
paper.on('blank:pointerdown', function(evt) {
x = evt.pageX;
y = evt.pageY;
});
paper.on('blank:pointerup', function(evt) {
var pageRect = g.Rect(x, y, evt.pageX - x, evt.pageY - y).normalize();
var localRect1 = this.pageToLocalRect(pageRect);
// alternative method signature
var localRect2 = this.pageToLocalRect(x, y, evt.pageX - x, evt.pageY - y).normalize();
// Move and resize the element to cover the area, that the user just selected.
element.position(localRect1.x, localRect1.y);
element.resize(localRect1.width, localRect1.height);
});
paper.paperToLocalPoint(p)
Transform the point p
defined in the paper coordinate system to the local coordinate system.
var paperCenter = g.Point(paper.options.width / 2, paper.options.height / 2);
var localPoint1 = paper.paperToLocalPoint(paperCenter);
// alternative method signature
var localPoint2 = paper.paperToLocalPoint(paper.options.width / 2, paper.options.height / 2);
// Move the element to the center of the paper viewport.
var elSize = element.size();
element.position(localPoint1.x - elSize.width, localPoint1.y - elSize.height);
paper.paperToLocalRect(rect)
Transform the rectangle rect
defined in the paper coordinate system to the local coordinate system.
var paperRect = g.Rect(0, 0, paper.options.width, paper.options.height);
var localRect1 = paper.paperToLocalRect(paperRect);
// alternative method signature
var localRect2 = paper.paperToLocalRect(0, 0, paper.options.width, paper.options.height);
// Move and resize the element to cover the entire paper viewport.
element.position(localRect1.x , localRect1.y);
element.size(localRect1.width, localRect1.height);
The following list contains properties exposed by the paper object:
svg
- a reference to the SVG document object the paper uses to render all the graphics.viewport
- a reference to the SVG group <g>
element the paper wraps all the rendered elements and links into. Paper transformations
such as scale is performed on this element.defs
- a reference to the SVG <defs> element used to define SVG elements for later reuse. This is also a good place to put SVG masks, patterns, filters and gradients.Normally, you do not need to access these properties directly but in some (advanced) situations, it is handy to have access to them.
paper.removeTools()
Remove all tools view objects attached to all link views on this paper.
paper.scale([sx, sy, ox, oy])
Scale a paper by sx
factor in x axis and sy
factor in y axis.
ox
and oy
are optional and determine the origin of the scale transformation. This method effectively implements a paper zoom in/out. If the method is called a "scale"
event is triggered on the paper. When the method is called with no parameter the current paper scale
transformation is returned.
paper.scale(2) // scale 2x (uniformly)
paper.scale(2,3) // scale 2x in `x` axis 3x in `y` axis (non-uniformly)
paper.scale(2,2,100,100) // scale with the origin of the transformation at point `x=100` and `y=100`
paper.scale() // returns e.g. { sx: 2, sy: 2 }
paper.scaleContentToFit([opt])
Scale the paper content so that it fits the paper dimensions. If opt.padding
is set (default is 0
), there will be an additional padding in the resulting, scaled, paper content.
If opt.preserveAspectRatio
is defined (default is true
), the aspect ratio of the scaled paper content will be preserved.
opt.minScaleX
, opt.minScaleY
, opt.maxScaleX
and opt.maxScaleY
can be optionally used to set the minimum and maximum
allowed scale factor for both axis.
opt.scaleGrid
is a number that will be used to as a rounding factor for the resulting scale. For example,
if the resulting scale factor is calculated to be 1.15
and your opt.scaleGrid
is set to 0.2
,
then the resulting scale factor will be rounded to 1.2
. Last option is opt.fittingBBox
which can be an object of the form
{ x: [number], y: [number], width: [number], height: [number] }
and is the area of the paper
that should be scaled. By default opt.fittingBBox
is { x: 0, y: y, width: paper.options.width, height: paper.options.height }
,
i.e. the whole paper area. If the method called a "scale"
event can be triggered on the paper.
To try it yourself see paper demo.
paper.setDimensions(width, height)
Change dimensions of a paper. Dimensions should always be passed to the options object of the joint.dia.Paper
constructor. Use setDimensions()
to change dimensions of the paper later on if needed. If the method is called a "resize"
event is triggered on the paper.
Type | Description |
---|---|
Number | Dimension in pixels (e.g 800 ). |
String |
Dimension as CSS property value (e.g "100%" ). Make sure the paper container element has size defined.
|
null | No dimension set. Useful when size of the paper controlled in CSS. |
paper.setGridSize(gridSize)
Set the grid size of the paper.
paper.setInteractivity(interactive)
Set the interactivity of the paper. For example, to disable interactivity:
paper.setInteractivity(false);
paper.setOrigin(x, y)
Deprecated in favor of translate()
. Lets you modify the origin (zero coordinates) of a paper. An origin can also be passed to the options object of the joint.dia.Paper
constructor. If the method is called a "translate"
event is triggered on the paper.
paper.showTools()
Show all tools attached to all link views on this paper.
paper.translate(x, y)
Lets you modify the origin (zero coordinates) of a paper. An origin can also be passed to the options object of the joint.dia.Paper
constructor. If the method is called a "translate"
event is triggered on the paper. If the method is called with no paramater the current paper translate
transformation is returned.
paper.translate(100, 200) // set origin to `x=100` and `y=200`
paper.translate(100) // same as calling `translate(100,0)`
paper.translate() // returns e.g. { tx: 100, ty: 100 }
allowLink
- expects a function returning a boolean. The function is run when the user stops interacting with a linkView's arrowhead (source or target).
If the function returns false
, the link is either removed (for links which are created during the interaction) or reverted to the state before the interaction.
// Return `false` if a graph cycle is detected (`graphlib` refers to a dependency of the DirectedGraph plugin).
paper.options.allowLink = function(linkView, paper) {
var graph = paper.model;
return graphlib.alg.findCycles(graph.toGraphLib()).length === 0;
}
async
- when enabled, the paper renders cells added to the graph through graph.resetCells()
or graph.addCells()
asynchronously.
This is very useful when you want to add a large number of cells into the graph. The rendering performance boost is significant and doesn't block the UI.
The option accepts either true
in which case default values are used or an object of the form
{ batchSize: <value> }
where you can specify the number of cells rendered in each animation frame (default is 50). Normally, the default batchSize
works great
but you might want to experiment with different values in case you encounter performance issues.
It is important to note that when asynchronous rendering is used, some of the cell views might not yet
be in the paper when you try to access them via the paper.findViewByModel()
, element.findView()
or link.findView()
methods.
What you should do in case you use async rendering is to wait for when the paper triggers the render:done
event.
An object defining the paper background color and image. It defaults to false
meaning there is no background set. The configuration object can have the following properties.
background-color
property.
e.g 'red'
, 'rgba(255, 255, 0, 0.5)'
, 'radial-gradient(ellipse at center, red, green);'
'/my-background.png'
.{ x: Number, y: Number }
defining the background image position. It also allows to use all the CSS background-position
property values.
In that case all the paper transformations have no impact on the background image position. It defaults to center
.{ width: Number, height: Number }
defining the background image size. It also allows to use all the CSS background-size
property values. In that case all the paper transformations have no impact on the background size. It defaults to auto auto
.background-repeat
property and few more defined by JointJS. Those are flip-x
, flip-y
, flip-xy
and watermark
. It defaults to no-repeat
.0.5
uses only 50% the image size for creating a pattern). Applicable only for the JointJS repeat
option values. It defaults to 1
.[0,1]
specifying the transparency of the background image (0
is fully transparent and 1
is fully opaque). It defaults to 1
.'watermark'
repeat
option. It defaults to 20
deg.background: {
color: '#6764A7',
image: 'jointjs-logo.png',
repeat: 'watermark',
opacity: 0.3
}
cellViewNamespace
- this option can be used to change the default behavior of JointJS which by default reads cell view definitions from the joint.shapes
namespace.
For example, if a cell is of type 'myshapes.MyElement'
, then the paper looks up joint.shapes.myshapes.MyElementView
object type when rendering the cell onto the screen. If cellViewNamespace
is set,
the paper will read the view definition from the myShapesNamespace.myshapes.MyElementView
object instead. This is useful in situations where you - for any reason - don't want to
use the joint.shapes
namespace for defining your own custom shapes. This option is often used in combination with
cellNamespace
option on the joint.dia.Graph
object.
clickThreshold
- When number of mousemove events exceeds the clickThreshold
there is no pointerclick
event triggered after mouseup. It defaults to 0
.
connectionStrategy
- the connection strategy to use on this paper. It can either be a function or null
. JointJS provides a collection of built-in connection strategies in the joint.connectionStrategies
namespace; alternatively, a custom function may be provided. See the Presentation section of joint.dia.Link
for more information about connection strategies.
defaultAnchor
- an anchor function that is used by links if no anchor
property is defined for a link end. It can either be an object (with a name
and optional args
) or a function. JointJS provides a collection of built-in anchor functions in the joint.anchors
namespace; alternatively, a custom function may be provided. See the Presentation section of joint.dia.Link
for more information about anchors.
defaultConnectionPoint
- a connection point function that is used by links if no connectionPoint
property is defined for a link end. It can either be an object or a function. JointJS provides a collection of built-in connection point functions in the joint.connectionPoints
namespace; alternatively, a custom function may be provided. See the Presentation section of joint.dia.Link
for more information about connection points.
defaultConnector
- a connector that is used by links if no connector
property is defined on them. It can either be an object or a function. JointJS provides a collection of built-in connectors in the joint.connectors
namespace; alternatively, a custom function may be provided. See the Presentation section of joint.dia.Link
for more information about connectors.
defaultLink
- link that should be created when the user clicks and drags and active magnet (when creating a link from a port via the UI). Defaults to new joint.dia.Link
. It can also be a function with signature function(cellView, magnet) {}
that must return an object of type joint.dia.Link
.
defaultRouter
- a router that is used by links if no router
property is defined on them. It can either be an object or a function. JointJS provides a collection of built-in routers in the joint.routers
namespace; alternatively, a custom function may be provided. See the Presentation section of joint.dia.Link
for more information about routers.
drawGrid
- option whether the paper grid should be drawn or not. It could be a boolean
or an object
. It defaults to false
.
Define color
and thickness
to adjust the default grid pattern:
color | string | color of the default grid pattern. |
---|---|---|
thickness | number | thickness of the default grid pattern. |
There are also some pre-defined grid patterns: dot
, fixedDot
, mesh
, doubleMesh
. If you'd like to use these patterns, define drawGrid
options as follows:
name | string | name of the pre-defined pattern. Can be either dot , fixedDot , mesh , doubleMesh |
---|---|---|
args | object | array | an extra arguments for the pre-defined grid patterns. It can be either an object (e.g. dot , mesh ) or an array (e.g. doubleMesh ) |
Pre-defined grids with default settings:
The paper from the images below has been scaled 2 times and has gridSize set to 10.
drawGrid: true // default pattern (dot) with default settings
drawGrid: 'mesh' // pre-defined pattern with default settings
drawGrid: { name: 'mesh', args: { color: 'black' }}
drawGrid: {
name: 'doubleMesh',
args: [
{ color: 'red', thickness: 1 }, // settings for the primary mesh
{ color: 'green', scaleFactor: 5, thickness: 5 } //settings for the secondary mesh
]}
el
- CSS selector, jQuery object or a DOM element holding the container for the paper
elementView
- object that is responsible for rendering an element model into the paper. Defaults to joint.dia.ElementView
. It can also be a function of the form function(element)
that takes an element model and should return an object responsible for rendering that model onto the screen (in most cases a subtype of joint.dia.ElementView
)
embeddingMode
- when set to true
, the paper is set to embedding mode. In this mode,
when you drag an element and drop into another element, the element below becomes a parent
of the dropped element (the dropped element gets automatically embedded into the parent element). Similarly, when you drag an
element out of its parent, the element gets automatically unembedded from its parent. The embedding mode
also makes sure all the connected links and child elements have proper z
index set so that they stay visible.
To control what elements can be embedded into what other elements, use the validateEmbedding()
function
on the paper (see below).
This is useful for hierarchical diagrams. See the DEVS demo on how this can be used.
findParentBy
- determines the way how a cell finds a suitable parent when it's dragged over the paper. The cell with the highest z-index (visually on the top) will be chosen.
findParentBy
option comes to play when the paper is in embedding mode. All possible values are
'bbox'
(default), 'center'
, 'origin'
, 'corner'
, 'topRight'
, 'bottomLeft'
and it also can be a function
. The function accepts an element
and it returns array of possible candidates.
findParentBy: function(element) {
var bBox = element.getBBox();
return this.getElements().filter(function(el) {
return bBox.intersect(el.getBBox());
});
}
gridSize
- size of the grid in pixels
guard
- guard paper from handling a browser UI event. This function is of the form
function(evt, view)
and should return true
if you want to prevent the paper from handling the event evt
,
false
otherwise. This is an advanced option that can be useful if you have your own logic for handling events.
height
- height of the paper (see setDimensions()).
highlighting
- Configure which highlighter to use (and with which options) for each type of interaction.
Example usage:
new joint.dia.Paper({
highlighting: {
'default': {
name: 'stroke',
options: {
padding: 3
}
},
connecting: {
name: 'addClass',
options: {
className: 'highlight-connecting'
}
}
}
})
interactive
- Configure which of the default interactions with elements and links should be enabled.
The property value defaults to { labelMove: false }
. This can be overwritten in three ways: with a boolean value, with an object specifying interaction keys, or with a function.
If set to false
, all interactions with elements and links are disabled. If set to true
, all interactions are enabled.
// disable all interaction
var paper = new joint.dia.Paper({
// ...
interactive: false,
});
// enable all interaction (including labelMove)
var paper = new joint.dia.Paper({
// ...
interactive: true,
});
Using an object, specific interactions may be disabled by assigning false
to their corresponding property name. It is not necessary to pass true
values; all omitted properties are assigned true
by default. (Note that the passed object is not merged with the default; unless labelMove
is explicitly excluded, it becomes enabled.) A full list of recognized interaction keys is provided below.
// disable arrowheadMove
var paper = new joint.dia.Paper({
// ...
interactive: { arrowheadMove: false }
});
// disable all element interactions
var paper = new joint.dia.Paper({
// ...
interactive: { elementMove: false, addLinkFromMagnet: false }
});
If defined as a function, the function is passed cellView
(the elementView/linkView the user is about to interact with) as the first parameter, followed by the name of the event ('pointerdown'
, 'pointermove'
, ...) that triggered the interaction. The return value of the function is then interpreted in the way specified above (false
causes all interaction to be disabled, an object disables specific interactions, etc.).
// disable link interactions for cellViews when a custom property is set
var paper = new joint.dia.Paper({
// ...
interactive: function(cellView) {
if (cellView.model.get('disableLinkInteractions')) {
return {
linkMove: false,
labelMove: false,
arrowheadMove: false,
vertexMove: false,
vertexAdd: false,
vertexRemove: false,
useLinkTools: false,
};
}
// otherwise
return true;
}
});
The example below has all interactions on the link and on the elements enabled. This is the default behavior:
The following tables present a list of all recognized interaction keys, followed by an example of a paper with only the related interactive property set to true
(and all other properties set to false
).
Links:
linkMove |
Is the user allowed to move the link? |
---|---|
labelMove |
Is the user allowed to move the link label? |
arrowheadMove |
Deprecated. Use a link tool instead. (Is the user allowed to move the arrowheads?) |
vertexMove |
Deprecated. Use a link tool instead. (Is the user allowed to move the vertices?) |
vertexAdd |
Deprecated. Use a link tool instead. (Is the user allowed to add vertices by clicking along the link path?) |
vertexRemove |
Deprecated. Use a link tool instead. (Is the user allowed to remove vertices?) |
useLinkTools |
Deprecated. (Is the user allowed to use the default link buttons?) |
Elements:
elementMove |
Is the user allowed to move the element? |
---|---|
addLinkFromMagnet |
Is the user allowed to add connections from magnets/ports? |
The stopDelegation
option is special. If it is true
(default), the element's elementMove
option determines whether the element responds to user drag.
However, if stopDelegation
is false
and the element is embedded within a parent, the user's dragging is delegated to the embedding parent. The parent's elementMove
option then determines whether both elements respond to user drag. The behavior is recursive. If the embedding parent has stopDelegation: false
, it delegates to its own embedding parent's elementMove
option and so on. If all children within an embedding have stopDelegation
set to false
, then no matter which element is dragged by the user, the whole embedding is dragged.
If the element is not embedded within an element, the stopDelegation
option is ignored (treated as true
). There is no other element to delegate to. Then elementMove
determines whether the element responds to user drag.
In the following example, both embedded elements have stopDelegation: false
. Thus, when the embedded element is dragged by the user, the parent ancestor (Movable
) is dragged instead. When the parent ancestor has elementMove
disabled (Not movable
), nothing happens.
stopDelegation |
---|
linkConnectionPoint(linkView, view, magnet, reference)
- this function allows you to customize what are the sticky points of links. The function must return a point (with x
and y
properties) where the link sticks to the element.
The function takes the link view, element view, the magnet (SVG element) the link should stick to and a reference point (either the closest vertex or the sticky point on the other side of the link).
Note that there is a utility function shapePerimeterConnectionPoint that can
be directly passed to the linkConnectionPoint
parameter. This function tries to find
the best possible connection point right on the perimeter of the connected shapes. See the function
documentation for details.
linkPinning
- when set to true
(the default), links can be pinnedto the paper meaning a source or target of a link can be a point. If you do not want to let the user drag a link and drop it somewhere in a blank paper area, set this to
false
. The effect is
that the link will be returned to its original position whenever the user drops it somewhere in a blank paper area.
linkView
- object that is responsible for rendering a link model into the paper. Defaults to joint.dia.LinkView
. It can also be a function of the form function(link)
that takes a link model and should return an object responsible for rendering that model onto the screen (in most cases a subtype of joint.dia.LinkView
).
magnetThreshold
- When defined as a number, it denotes the required mousemove events before a new link is created from a magnet. When defined as keyword 'onleave'
, the link is created when the pointer leaves the magnet DOM element. It defaults to 0
.
markAvailable
- marks all the available magnets or elements when a link is dragged (being reconnected). Default is false
. This gives a hint to the user to what other elements/ports this link can be connected.
What magnets/cells are available is determined by the validateConnection
function.
Internally, available magnets (SVG elements) are given the 'available-magnet'
class name and all the available cells the 'available-cell'
class name. This allows you to change the
styling of the highlight effect.
model
- joint.dia.Graph
object
moveThreshold
- Number of required mousemove events before the first pointermove event is triggered. It defaults to 0
.
multiLinks
- when set to false
, an element may not have
more than one link with the same source and target element.
origin
- position of zero coordinates of the paper in pixels (default is { x: 0, y: 0 }
i.e. top-left corner)
perpendicularLinks
- if true
, links will tend to get perpendicular to their associated objects. Default is false
preventContextMenu
- Prevents default context menu action (when right button of the mouse is clicked). It defaults to true
.
preventDefaultBlankAction
- Prevents default action when an empty paper area is clicked. Setting the option to false
will make the paper pannable inside a container on touch devices. It defaults to true
.
restrictTranslate
- restrict the translation (movement) of elements by a given bounding box. If set to true
, the user will not be able to move elements outside the boundary of the paper area. It's set to false
by default. This option also accepts a function with signature function(elementView)
in which case it must return a bounding box (an object of the form { x: Number, y: Number, width: Number, height: Number }
) that defines the area in which the element represented by elementView
can be moved. For example, to restrict translation of embedded elements by the bounding box defined by their parent element, you can do:
restrictTranslate: function(elementView) {
var parentId = elementView.model.get('parent');
return parentId && this.model.getCell(parentId).getBBox();
}
snapLinks
- when enabled, force a dragged link to snap to the closest element/port in the given radius. The option accepts true
in which case default values are used or an object of the form
{ radius: <value> }
where you can specify the radius (default is 50).
validateConnection(cellViewS, magnetS, cellViewT, magnetT, end, linkView)
-
decide whether to allow or disallow a connection between the source view/magnet (cellViewS/magnetS
)
and target view/magnet (cellViewT/magnetT
). end
is either "source"
or "target"
and tells which end of
the link is being dragged. This is useful for defining whether, for example, a link starting in a port POut of element A can lead to a port PIn of elmement B. By default, all linkings are allowed.
validateEmbedding
- a function that allows you to control what elements can be embedded to
what other elements when the paper is put into the embeddingMode
(see above).
The function signature is: function(childView, parentView)
and should return
true
if the childView
element can be embedded into the parentView
element.
By default, all elements can be embedded into all other elements (the function returns true
no matter what).
validateMagnet(cellView, magnet)
- decide whether to create a link if the user clicks a magnet. magnet
is the DOM element representing the magnet. By default, this function returns true
for magnets that are not explicitely set to "passive" (which is usually the case of input ports).
width
- width of the paper (see setDimensions()).
The joint.dia.ToolsView
class works as a container for one set of link tools (an array of joint.dia.ToolView
objects). It is responsible for rendering the tools as a group when the tools view is attached to a joint.dia.LinkView.
To create a new tools view object, we call its constructor. Two optional arguments are accepted:
name | string | The name of this tools view. Default is null (no name). |
---|---|---|
tools | Array<dia.ToolView> | An array of tools that should be a part of the tools view. Default is [] (no tools). |
Creating a tools view is the second step in the process of setting up link tools on a link view:
// 1) creating link tools
var verticesTool = new joint.linkTools.Vertices();
var segmentsTool = new joint.linkTools.Segments();
var boundaryTool = new joint.linkTools.Boundary();
// 2) creating a tools view
var toolsView = new joint.dia.ToolsView({
name: 'basic-tools',
tools: [verticesTool, segmentsTool, boundaryTool]
});
// 3) attaching to a link view
var linkView = link.findView(paper);
linkView.addTools(toolsView);
Every link view we want to attach to requires its own tools view object (ToolsView
objects are automatically reassigned to the last link view they are added to). Similarly, every tools view we create requires its own set of tools (ToolView
objects are automatically reassigned to the last toolsView.tools
array they were made part of).
toolsView.focusTool(tool)
Focus the specified tool
(of the joint.dia.ToolView
type) within this tools view.
When a tool is focused
, all other tools within this tools view are hidden and the tool's opacity is changed according to the tool's focusOpacity
option. Only one tool can be focused at a time; the focus passes to the last tool within this tools view with which the focusTool
function was called.
The effect of this function can be reversed by the toolsView.blurTool
function.
toolsView.getName()
Return the name of this tools view. If no name was set during the construction of the tools view, null
is returned.
toolsView.hide()
Hide all tools within this tools view.
toolsView.show()
Show all tools within this tools view.
The joint.dia.ToolView
class is the parent class of all link tool views included in the joint.linkTools
namespace. It is responsible for rendering the tool within a joint.dia.ToolsView, when the tools view is attached to a joint.dia.LinkView.
Creating link tools objects is the first step in the process of setting up link tools on a link view:
// 1) creating link tools
var verticesTool = new joint.linkTools.Vertices();
var segmentsTool = new joint.linkTools.Segments();
var boundaryTool = new joint.linkTools.Boundary();
// 2) creating a tools view
var toolsView = new joint.dia.ToolsView({
name: 'basic-tools',
tools: [verticesTool, segmentsTool, boundaryTool]
});
// 3) attaching to a link view
var linkView = link.findView(paper);
linkView.addTools(toolsView);
Every link view we want to attach to requires its own tools view object (ToolsView
objects are automatically reassigned to the last link view they are added to). Similarly, every tools view we create requires its own set of tools (ToolView
objects are automatically reassigned to the last toolsView.tools
array they were made part of).
toolView.blur()
Stop focusing the tool within its containing toolsView
.
This function reverses the effect of the toolView.focus
function.
toolView.focus()
Focus the tool within its containing toolsView
.
When a tool is focused
, all other tools within the toolsView
are hidden and the tool's opacity is changed according to the tool's focusOpacity
option. Only one tool can be focused at a time; the focus passes to the last tool within a tools view on which the focus
function was called.
The effect of this function can be reversed by the toolView.blur
function.
toolView.getName()
Return the name of the tool. The names of built-in link tools are kebab-case versions of their class names (e.g. the name of joint.linkTools.SourceAnchor
is 'source-anchor'
).
When creating a custom tool (e.g. by extending the joint.linkTools.Button
class), it is recommended that you provide a custom name
prototype property, as well:
joint.linkTools.InfoButton = joint.linkTools.Button.extend({
name: 'info-button',
options: {
markup: [{
tagName: 'circle',
selector: 'button',
attributes: {
'r': 7,
'fill': '#001DFF',
'cursor': 'pointer'
}
}, {
tagName: 'path',
selector: 'icon',
attributes: {
'd': 'M -2 4 2 4 M 0 3 0 0 M -2 -1 1 -1 M -1 -4 1 -4',
'fill': 'none',
'stroke': '#FFFFFF',
'stroke-width': 2,
'pointer-events': 'none'
}
}],
distance: 60,
offset: 0,
action: function(evt) {
alert('View id: ' + this.id + '\n' + 'Model id: ' + this.model.id);
}
}
});
toolView.hide()
Hide the tool.
The effect of this function can be reversed by the toolView.show
function.
toolView.show()
Show the tool.
The effect of this function can be reversed by the toolView.hide
function.
env.addTest(name, fn)
Add a custom feature-detection test where name
is a string which uniquely identifies your feature test and fn
is a function that returns true
if the browser supports the feature, and false
if it does not.
joint.env.addTest('customTest', function() {
// Just as an example, we will always return true here.
return true;
});
if (joint.env.test('customTest')) {
// Feature is supported.
}
env.test(name)
Tests whether the browsers supports the given feature or not. Returns true
if the feature is supported, otherwise it returns false
.
if (joint.env.test('someFeature')) {
// Feature is supported.
}
JointJS ships with the following tests:
Highlighters can be used to provide visual emphasis to an element; during user interactions for example.
In the above demo, we listen to the paper for the cell:pointerclick
event, then highlight the cell that was clicked.
paper.on('cell:pointerclick', function(cellView) {
cellView.highlight();
});
As you can see it is possible to highlight a cell as follows:
cellView.highlight();
Unhighlighting a cell is simple too:
cellView.unhighlight();
To highlight a cell using a specific highlighter (and options):
cellView.highlight(null/* defaults to cellView.el */, {
highlighter: {
name: 'stroke',
options: {
width: 3
}
}
});
Or you can specify just the highlighter's name (its default options will be used):
cellView.highlight(null/* defaults to cellView.el */, {
highlighter: 'stroke'
});
Toggles a class name on the cell view's $el
.
Available options:
$el
Example usage:
cellView.highlight(null/* defaults to cellView.el */, {
highlighter: {
name: 'addClass',
options: {
className: 'some-custom-class'
}
}
});
Changes the opacity of the cell view's $el
.
When a cell is highlighted with the opacity highlighter, its $el
is given the .joint-highlight-opacity
class. To customize the look of this highlighted state, you can add custom CSS rules that affect this class name.
This highlighter does not currently have any options.
Example usage:
cellView.highlight(null/* defaults to cellView.el */, {
highlighter: {
name: 'opacity'
}
});
Adds a stroke around the cell view's $el
.
Available options:
Example usage:
cellView.highlight(null/* defaults to cellView.el */, {
highlighter: {
name: 'stroke',
options: {
padding: 10,
rx: 5,
ry: 5,
attrs: {
'stroke-width': 3,
stroke: '#FF0000'
}
}
}
});
Automatic layout of directed graphs. This plugin uses the open-source (MIT license) Dagre library internally. It provides a wrapper so that you can call the layout directly on JointJS graphs.
Note that you must include both the Dagre and Graphlib libraries as dependencies if you wish to use the layout.DirectedGraph plugin.
joint.layout.DirectedGraph
plugin exposes the joint.layout.DirectedGraph.layout(graphOrElements, opt)
function.
The first parameter graphOrElements
is the joint.dia.Graph
or an array of joint.dia.Elements
we want to layout. The second parameter options
is an
object that contains various options for configuring the layout.
var graphBBox = joint.layout.DirectedGraph.layout(graph, {
nodeSep: 50,
edgeSep: 80,
rankDir: "TB"
});
console.log('x:', graphBBox.x, 'y:', graphBBox.y)
console.log('width:', graphBBox.width, 'height:', graphBBox.height);
A full blog post explaining this example in more detail can be found here.
The following table lists options that you can pass to the joint.layout.DirectedGraph.layout(graph, opt)
function:
nodeSep | a number of pixels representing the separation between adjacent nodes in the same rank |
---|---|
edgeSep | a number of pixels representing the separation between adjacent edges in the same rank |
rankSep | a number of pixels representing the separation between ranks |
rankDir | direction of the layout (one of "TB" (top-to-bottom) / "BT" (bottom-to-top) / "LR" (left-to-right) / "RL" (right-to-left)) |
marginX | number of pixels to use as a margin around the left and right of the graph. |
marginY | number of pixels to use as a margin around the top and bottom of the graph. |
ranker | Type of algorithm to assign a rank to each node in the input graph. Possible values: 'network-simplex' (default), 'tight-tree' or 'longest-path' .
number of pixels to use as a margin around the top and bottom of the graph. |
resizeClusters | set to false if you don't want parent elements to stretch in order to fit all their embedded children. Default is true . |
clusterPadding | A gap between the parent element and the boundary of its embedded children. It could be a number or an object e.g. { left: 10, right: 10, top: 30, bottom: 10 } . It defaults to 10 . |
setPosition(element, position) | a function that will be used to set the position of elements at the end of the layout. This is useful
if you don't want to use the default element.set('position', position) but want to set the position in an animated fashion via transitions. |
setVertices(link, vertices) |
If set to true the layout will adjust the links by setting their vertices. It defaults to false . If the option is defined as a function it will be used to set the vertices of links at the end of the layout. This is useful
if you don't want to use the default link.set('vertices', vertices) but want to set the vertices in an animated fashion via transitions.
|
setLabels(link, labelPosition, points) |
If set to true the layout will adjust the labels by setting their position. It defaults to false . If the option is defined as a function it will be used to set the labels of links at the end of the layout.
Note: Only the first label (link.label(0); ) is positioned by the layout.
|
Additionally, the layout engine takes into account some properties on elements/links to fine tune the layout further. These are:
size | element | An object with `width` and `height` properties representing the size of the element. |
---|---|---|
minLen | link | The number of ranks to keep between the source and target of the link. |
weight | link | The weight to assign edges. Higher weight edges are generally made shorter and straighter than lower weight edges. |
labelPosition | link | Where to place the label relative to the edge. 'l' = left, 'c' = center (default), 'r' = right.
|
labelOffset | link | How many pixels to move the label away from the edge. Applies only when labelPosition is left or right. |
labelSize | link | The width and height of the edge label in pixels. e.g. { width: 100, height: 50 } |
The layout()
function returns a bounding box (g.Rect
) of the resulting graph.
The layout.DirectedGraph
plugins extends the joint.dia.Graph
type with functions
that make it easy to convert graphs to and from the Graphlib graph format.
This allows you to easily use many of the graph algorithms provided by this library.
toGraphLib() | Convert the JointJS joint.dia.Graph object to the Graphlib graph object.
|
---|---|
fromGraphLib(glGraph, opt) | Convert the Graphlib graph representation to JointJS joint.dia.Graph object.
opt.importNode and opt.importEdge are functions that accept a Graphlib node and edge objects and should return
JointJS element/link.
|
Port layouts are functions that accept an array of port's args
and return an array of port positions. Positions are relative to the element model bounding box. For example if we have an element at position { x:10, y:20 }
with a relative port position { x:1, y:2 }
, the absolute port position will be { x:11, y:22 }
.
Port layout can be defined only at the group
level. Optionally you can pass some additional arguments into the layout function via args
. The args
is the only way to adjust port layout from the port definition perspective.
var rect = new joint.shapes.basic.Rect({
// ...
ports: {
groups: {
'a': {
position: {
name: 'layoutType',
args: {},
}
}
},
items: [
// initialize 'rect' with port in group 'a'
{
group: 'a',
args: {} // overrides `args` from the group level definition.
},
// ... other ports
]
}
});
// ....
// add another port to group 'a'.
rect.addPort({ group:'a' });
A simple layout suitable for rectangular shapes. It evenly spreads ports along a single side.
name | string | Can be either `left`, `right`, `top`, `bottom`. | |||||||||||||||
args | object |
|
{
name: 'left',
args: {
x: 10,
y: 10,
angle: 30,
dx: 1,
dy: 1
}
}
A layout which evenly spreads ports along a line defined by a start
and en end
point.
name | string | `line` | ||||||
args | object |
|
{
name: 'line',
args: {
start: { x: 10, y: 10 },
end: { x: 20, y: 50 }
}
}
It lay a port out at the given position (defined as a x
, y
coordinates or percentage of the element dimensions).
name | string | `absolute` | |||||||||
args | object |
|
{
name: 'absolute',
args: {
x: '10%',
y: 10,
angle: 45
}
}
Suitable for circular shapes. The ellipseSpreads
evenly spreads ports along an ellipse. The ellipse
spreads ports from the point at startAngle
leaving gaps between ports equal to step
.
name | string | Can be either `ellipse`, `ellipseSpread`. | ||||||||||||||||||||||||
args | object |
|
{
name: 'ellipseSpread',
args: {
dx: 1,
dy: 1,
dr: 1,
startAngle: 10,
step: 10,
compensateRotation: false
}
}
An alternative for built-in layouts is providing a function directly, where the function returns an array of port positions.
/**
* @param {Array<object>} portsArgs
* @param {g.Rect} elBBox shape's bounding box
* @param {object} opt Group options
* @returns {Array<g.Point>}
*/
function(portsArgs, elBBox, opt) {
// ports on sinusoid
return _.map(portsArgs, function(portArgs, index) {
var step = -Math.PI / 8;
var y = Math.sin(index * step) * 50;
return g.point({ x: index * 12, y: y + elBBox.height });
});
}
Port label layout functions calculate port label positions relatively to port positions.
Simple label layout suitable for rectangular shapes. It places the label on arbitrary side of a port.
name | string | Can be either `left`, `right`, `bottom`, `top`. | ||||||||||||
args | object | string |
|
label: {
position: {
name : 'right',
args: {
x: 0,
y: 0,
angle: 0,
attrs: {}
}
}
}
Places the label inside or outside of a rectangular shape. Where 'oriented' versions rotate the text towards the element center.
name | string | Can be either `inside`, `outside`, `insideOriented`, `outsideOriented`. | ||||||
args | object | string |
|
label: {
position: {
name :'outsideOriented',
args: {
offset: 10,
attrs: {}
}
}
Places the label outside of a circular shape. Where the 'oriented' version rotates the text towards the element center.
name | string | Can be either `radial`, `radialOriented`. | ||||||
args | object | string |
|
label: {
position: {
name :'radialOriented',
args: {
offset: 0,
attrs: {}
}
}
}
It allows to set a label position directly.
name | string | `manual` | ||||||||||||
args | object | string |
|
label: {
position: {
name: 'manual',
args: {
x: 10,
y: 20,
angle: 45,
attrs: {}
}
}
}
A link tool is a view that renders a certain type of control elements on top of the LinkView it is attached to; for example the Vertices tool creates an interactive handle above every vertex (these handles then allow the user to move and/or delete each vertex). Link tools all inherit from the joint.dia.ToolView
class. A collection of tools is added to a ToolsView; a tools view is then added to the linkView with the linkView.addTools()
function.
The JointJS library comes with a collection of pre-made link tool definitions in the joint.linkTools
namespace:
Vertices
- adds handles above link verticesSegments
- adds handles above link segmentsSourceArrowhead
- adds a handle above link sourceTargetArrowhead
- adds a handle above link targetSourceAnchor
- adds a handle above link source anchorTargetAnchor
- adds a handle above link target anchorBoundary
- shows link bboxRemove
- adds an interactive remove buttonTo create a new link tool, we call its constructor. Example:
var verticesTool = new joint.linkTools.Vertices({
snapRadius: 10
});
In addition, the joint.linkTools
namespace contains a customizable button class:
Button
- adds a customizable buttonExample:
var infoTool = new joint.linkTools.Button({
markup: [{
tagName: 'circle',
selector: 'button',
attributes: {
'r': 7,
'fill': '#001DFF',
'cursor': 'pointer'
}
}, {
tagName: 'path',
selector: 'icon',
attributes: {
'd': 'M -2 4 2 4 M 0 3 0 0 M -2 -1 1 -1 M -1 -4 1 -4',
'fill': 'none',
'stroke': '#FFFFFF',
'stroke-width': 2,
'pointer-events': 'none'
}
}],
distance: 60,
offset: 0,
action: function(evt) {
alert('View id: ' + this.id + '\n' + 'Model id: ' + this.model.id);
}
});
All of the built-in link tools accept the following optional argument, in addition to their own arguments:
focusOpacity | number | What should be the opacity of the tool when it is focused (e.g. with the toolView.focus function)? Default is undefined , meaning that the tool's opacity is kept unchanged. |
---|
Example:
var verticesTool = new joint.linkTools.Vertices({
focusOpacity: 0.5
});
The Boundary
link tool renders a rectangular border to show the bounding box of the link. It accepts one additional argument, which can be passed as an object to the link tool constructor:
padding | number | This option determines whether the boundary area should be visually inflated and if so, by how much. Default is 10 . |
---|
Example:
var boundaryTool = new joint.linkTools.Boundary({
focusOpacity: 0.5,
padding: 20
});
The Button
link tool allows you to have a custom button rendered at a given position along the link. It accepts five additional arguments, which can be passed as an object to the link tool constructor:
distance | number | Distance at which the button should be placed. Negative numbers are accepted; then the distance is counted from the end of the link. Default is 0 . |
---|---|---|
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
rotate | boolean | Should the button rotate according to the slope of the link at the position specified by distance ? Default is false . |
offset | number | Relative offset of the button from the link. Positive numbers mean that the button should be offset to the right of the link (relative to the direction from source to target); negative numbers mean that the button should be offset to the left of the link (relative to the direction from source to target). Default is 0 . |
action | function | What should happen when the user clicks the remove button? Default is undefined (no interaction).The callback function is expected to have the signature function(evt) where evt is a jQuery.Event object. The button view is available inside the function as this ; the button model is available as this.model . |
markup | JSONMarkup | The markup of the button, provided in the JointJS JSON format. Default is undefined (no content). |
Example of a useful custom info button:
var infoButton = new joint.linkTools.Button({
focusOpacity: 0.5,
distance: 60,
action: function(evt) {
alert('View id: ' + this.id + '\n' + 'Model id: ' + this.model.id);
},
markup: [{
tagName: 'circle',
selector: 'button',
attributes: {
'r': 7,
'fill': '#001DFF',
'cursor': 'pointer'
}
}, {
tagName: 'path',
selector: 'icon',
attributes: {
'd': 'M -2 4 2 4 M 0 3 0 0 M -2 -1 1 -1 M -1 -4 1 -4',
'fill': 'none',
'stroke': '#FFFFFF',
'stroke-width': 2,
'pointer-events': 'none'
}
}]
});
The linkTools.Button
class can also be extended, to create a reusable custom button type within the joint.linkTools
namespace. Then, a new instance of the custom button type can be obtained by calling its constructor:
joint.linkTools.InfoButton = joint.linkTools.Button.extend({
name: 'info-button',
options: {
focusOpacity: 0.5,
distance: 60,
action: function(evt) {
alert('View id: ' + this.id + '\n' + 'Model id: ' + this.model.id);
},
markup: [{
tagName: 'circle',
selector: 'button',
attributes: {
'r': 7,
'fill': '#001DFF',
'cursor': 'pointer'
}
}, {
tagName: 'path',
selector: 'icon',
attributes: {
'd': 'M -2 4 2 4 M 0 3 0 0 M -2 -1 1 -1 M -1 -4 1 -4',
'fill': 'none',
'stroke': '#FFFFFF',
'stroke-width': 2,
'pointer-events': 'none'
}
}]
}
});
var infoButton = new joint.linkTools.InfoButton();
The Remove
link tool renders a remove button at a given position along the link. It accepts five additional arguments, which can be passed as an object to the link tool constructor:
distance | number | Distance at which the button should be placed. Negative numbers are accepted; then the distance is counted from the end of the link. Default is 60 . |
---|---|---|
string | Percentage strings (e.g. '40%' ) are also accepted. |
|
rotate | boolean | Should the button rotate according to the slope of the link at the position specified by distance ? Default is false . |
offset | number | Relative offset of the button from the link. Positive numbers mean that the button should be offset to the right of the link (relative to the direction from source to target); negative numbers mean that the button should be offset to the left of the link (relative to the direction from source to target). Default is 0 . |
action | function | What should happen when the user clicks the remove button? Default:
The callback function is expected to have the signature function(evt) where evt is a jQuery.Event object. The button view is available inside the function as this ; the button model is available as this.model .
|
markup | JSONMarkup | The markup of the button, provided in the JointJS JSON format. Default:
|
Example:
var removeButton = new joint.linkTools.Remove({
focusOpacity: 0.5,
rotate: true,
distance: -20,
offset: 20
});
The Segments
link tool renders handles above all segments of the link (as determined by the link connector). It accepts four additional arguments, which can be passed as an object to the link tool constructor:
redundancyRemoval | boolean | If the user arranges two (or more) segments so that they lie on a single line, should the middle one(s) be considered redundant and removed? Default is true . Note that this setting is not applied until the user actually moves one of the segments in question; this means that segments can still be arranged in this redundantfashion, using the link.vertices function, for example. |
---|---|---|
segmentLengthThreshold | number | The minimum segment length for which to display a segment handle (to prevent the handle from overflowing its segment). Default is 40 . |
snapRadius | number | While the user is moving the segment, from how far away should the segment snap in order to arrange itself in line with another segment? Default is 10 . |
snapHandle | number | If the snapRadius option is set to true and the segment is snapped in place while the user moves the segment handle, should the handle follow the user pointer or should the handle stay snapped with the segment until it un-snaps? Default is true , meaning that the handle snaps with the segment. |
Example:
var segmentsTool = new joint.linkTools.Segments({
focusOpacity: 0.5,
redundancyRemoval: false,
segmentLengthThreshold: 50,
snapHandle: false,
snapRadius: 10
});
The SourceAnchor
link tool renders a handle above the source anchor of the link (as determined by the anchor function applied on link source). It accepts five additional arguments, which can be passed as an object to the link tool constructor:
redundancyRemoval | boolean | If the user moves the anchor so that it lies on a single line with two (or more) vertices, should the middle one(s) be considered redundant and removed? Default is true . Note that this setting is not applied until the user actually moves the anchor; this means that the anchor and vertices can still be arranged in this redundantfashion, using the link.vertices function, for example. |
||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
restrictArea | boolean | Should the user only be allowed to move the anchor in a restricted area (the area of the bounding box of the source magnet)? Default is true . |
||||||||||||||||||
areaPadding | number | If the restrictArea option is set to true , the user can only move the anchor in a restricted area (the area of the bounding box of the source magnet). JointJS shows this restriction by drawing a boundary around that area. This option determines whether this boundary area should be visually inflated and if so, by how much. Default is 10 . Note that this is a purely cosmetic setting; regardless of the provided value, the movement stays restricted to the original uninflated bounding box. |
||||||||||||||||||
snapRadius | number | While the user is moving the anchor, from how far away should the segment snap in order to arrange itself in line with the anchor reference? Default is 10 . (For link source, the anchor reference is the first vertex. If there are no vertices, it is the target anchor.) |
||||||||||||||||||
snap | function | What snap function should be applied when the user moves the anchor? Default is a simple function that emulates the snapping behavior of Vertices and Segments link tools: If the value of one of the user pointer coordinates is within snapRadius of the value of a coordinate of the anchor reference, snap to the reference value. (For link source, the anchor reference is the first vertex. If there are no vertices, it is the target anchor.)The callback function must return the anchor as a g.Point and have the signature function(coords, endView, endMagnet, endType, linkView, toolView) :
|
Example:
var sourceAnchorTool = new joint.linkTools.SourceAnchor({
focusOpacity: 0.5,
redundancyRemoval: false,
restrictArea: false,
snapRadius: 20
});
An example of a useful custom snap
function is provided below. It snaps the anchor to the center of the closest side of the restricted area.
var snapAnchor = function(coords, endView, endMagnet) {
// remove rotation of the restricted area
var bbox = endView.getNodeUnrotatedBBox(endMagnet);
var angle = endView.model.angle();
var origin = endView.model.getBBox().center();
coords.rotate(origin, angle);
// identify the side nearest to pointer coords
var anchor;
var side = bbox.sideNearestToPoint(coords);
switch (side) {
case 'left': anchor = bbox.leftMiddle(); break;
case 'right': anchor = bbox.rightMiddle(); break;
case 'top': anchor = bbox.topMiddle(); break;
case 'bottom': anchor = bbox.bottomMiddle(); break;
}
// rotate the anchor according to original rotation of restricted area
return anchor.rotate(origin, -angle);
};
var sourceAnchorTool = new joint.linkTools.SourceAnchor({
snap: snapAnchor;
});
If the user moves the anchor away from its original position, the anchor position may be reset by double-clicking the anchor handle.
The SourceArrowhead
link tool renders an arrow-like handle above the source connection point of the link (as determined by the connectionPoint function applied on link source).
Example:
var sourceArrowheadTool = new joint.linkTools.SourceArrowhead({
focusOpacity: 0.5
});
The TargetAnchor
link tool renders a handle above the target anchor of the link (as determined by the anchor function applied on link target). It accepts five additional arguments, which can be passed as an object to the link tool constructor:
redundancyRemoval | boolean | If the user moves the anchor so that it lies on a single line with two (or more) vertices, should the middle one(s) be considered redundant and removed? Default is true . Note that this setting is not applied until the user actually moves the anchor; this means that the anchor and vertices can still be arranged in this redundantfashion, using the link.vertices function, for example. |
||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
restrictArea | boolean | Should the user only be allowed to move the anchor in a restricted area (the area of the bounding box of the target magnet)? Default is true . |
||||||||||||||||||
areaPadding | number | If the restrictArea option is set to true , the user can only move the anchor in a restricted area (the area of the bounding box of the target magnet). JointJS shows this restriction by drawing a boundary around that area. This option determines whether this boundary area should be visually inflated and if so, by how much. Default is 10 . Note that this is a purely cosmetic setting; regardless of the provided value, the movement stays restricted to the original uninflated bounding box. |
||||||||||||||||||
snapRadius | number | While the user is moving the anchor, from how far away should the segment snap in order to arrange itself in line with the anchor reference? Default is 10 . (For link target, the anchor reference is the last vertex. If there are no vertices, it is the source anchor.) |
||||||||||||||||||
snap | function | What snap function should be applied when the user moves the anchor? Default is a simple function that emulates the snapping behavior of Vertices and Segments link tools: If the value of one of the user pointer coordinates is within snapRadius of the value of a coordinate of the anchor reference, snap to the reference value. (For link target, the anchor reference is the last vertex. If there are no vertices, it is the source anchor.)The callback function must return the anchor as a g.Point and have the signature function(coords, endView, endMagnet) :
|
Example:
var targetAnchorTool = new joint.linkTools.TargetAnchor({
focusOpacity: 0.5,
redundancyRemoval: false,
restrictArea: false,
snapRadius: 20
});
An example of a useful custom snap
function is provided below. It snaps the anchor to the center of the closest side of the restricted area.
var snapAnchor = function(coords, endView, endMagnet) {
// remove rotation of the restricted area
var bbox = endView.getNodeUnrotatedBBox(endMagnet);
var angle = endView.model.angle();
var origin = endView.model.getBBox().center();
coords.rotate(origin, angle);
// identify the side nearest to pointer coords
var anchor;
var side = bbox.sideNearestToPoint(coords);
switch (side) {
case 'left': anchor = bbox.leftMiddle(); break;
case 'right': anchor = bbox.rightMiddle(); break;
case 'top': anchor = bbox.topMiddle(); break;
case 'bottom': anchor = bbox.bottomMiddle(); break;
}
// rotate the anchor according to original rotation of restricted area
return anchor.rotate(origin, -angle);
};
var targetAnchorTool = new joint.linkTools.TargetAnchor({
snap: snapAnchor;
});
If the user moves the anchor away from its original position, the anchor position may be reset by double-clicking the anchor handle.
The TargetArrowhead
link tool renders an arrow-like handle above the target connection point of the link (as determined by the connectionPoint function applied on link target).
Example:
var targetArrowheadTool = new joint.linkTools.TargetArrowhead({
focusOpacity: 0.5
});
The Vertices
link tool renders handles above all vertices of the link. It accepts three additional arguments, which can be passed as an object to the link tool constructor:
redundancyRemoval | boolean | If the user arranges three (or more) vertices so that they lie on a single line, should the middle one(s) be considered redundant and removed? Default is true . Note that this setting is not applied until the user actually moves one of the vertices in question; this means that vertices can still be arranged in this redundantfashion, using of the link.vertices function, for example. |
---|---|---|
snapRadius | number | While the user is moving the vertex, from how far away should the vertex snap in order to arrange itself perpendicularly to another vertex? Default is 20 . |
vertexAdding | boolean | Can the user add new vertices (by clicking a segment of the link)? Default is true . |
Example:
var verticesTool = new joint.linkTools.Vertices({
focusOpacity: 0.5,
redundancyRemoval: false,
snapRadius: 10,
vertexAdding: false,
});
Routers take an array of link vertices and transform them into an array of route points that the link should go through. The router
property of a link can be accessed with the link.router()
function.
The difference between vertices
and the route is that the vertices are user-defined while the route is computed. The route inserts additional private vertices to complement user vertices as necessary (e.g. to make sure the route is orthogonal).
There are five built-in routers:
'manhattan'
- smart orthogonal router'metro'
- smart octolinear router'normal'
- default simple router'orthogonal'
- basic orthogonal router'oneSide'
- restricted orthogonal routerExample:
link.router('orthogonal', {
padding: 10
});
The default router is 'normal'
; this can be changed with the defaultRouter
paper option. Example:
paper.options.defaultRouter = {
name: 'orthogonal',
args: {
padding: 10
}
});
The 'manhattan'
and 'metro'
routers are our smart routers
; they automatically avoid obstacles (elements) in their way.
The 'orthogonal'
, 'manhattan'
and 'oneSide'
routers generate routes consisting exclusively of vertical and horizontal segments. The 'metro'
router generates routes consisting of orthogonal and diagonal segments.
JointJS also contains mechanisms to define one's own custom routers.
Note that the modular architecture of JointJS allows mixing-and-matching routers with connectors as desired; for example, a link may be specified to use the 'jumpover'
connector on top of the 'manhattan'
router:
var link = new joint.shapes.standard.Link();
link.source(rect);
link.target(rect2);
link.router('manhattan');
link.connector('jumpover');
New routers can be defined in the joint.routers
namespace (e.g. joint.routers.myRouter
) or passed directly as a function to the router
property of a link (or to the defaultRouter
option of a paper).
In either case, the router function must return an array of route points that the link should go through (not including the start/end connection points). The function is expected to have the form function(vertices, args, linkView)
:
vertices | Array<g.Point> | The vertices of the route. |
---|---|---|
args | object | An object with additional optional arguments passed to the router method by the user when it was called (the args property). |
linkView | dia.LinkView | The LinkView of the connection. The Link model can be accessed as the model property; this may be useful for writing conditional logic based on link attributes. |
Example of a router defined in the joint.routers
namespace:
joint.routers.randomWalk = function(vertices, args, linkView) {
var NUM_BOUNCES = args.numBounces || 20;
vertices = joint.util.toArray(vertices).map(g.Point);
for (var i = 0; i < NUM_BOUNCES; i++) {
var sourceCorner = linkView.sourceBBox.center();
var targetCorner = linkView.targetBBox.center();
var randomPoint = g.Point.random(sourceCorner.x, targetCorner.x, sourceCorner.y, targetCorner.y);
vertices.push(randomPoint)
}
return vertices;
}
var link = new joint.shapes.standard.Link();
link.source(source);
link.target(target);
link.router('randomWalk', {
numBounces: 10
});
An example of a router passed as a function is provided below. Notice that this approach does not enable passing custom args
nor can it be serialized with the graph.toJSON()
function.
var link = new joint.shapes.standard.Link();
link.source(source);
link.target(target);
link.router(function(vertices, args, linkView) {
var NUM_BOUNCES = 20;
vertices = joint.util.toArray(vertices).map(g.Point);
for (var i = 0; i < NUM_BOUNCES; i++) {
var sourceCorner = linkView.sourceBBox.center();
var targetCorner = linkView.targetBBox.center();
var randomPoint = g.Point.random(sourceCorner.x, targetCorner.x, sourceCorner.y, targetCorner.y);
vertices.push(randomPoint)
}
return vertices;
});
The 'manhattan'
router is the smart version of the 'orthogonal'
router. It connects vertices with orthogonal line segments, inserting route points when necessary, while avoiding obstacles in its way. The router has useful options that determine how the algorithm behaves. These options can be passed as the router.args
property:
step | number | Size of the imaginary grid followed by the 'manhattan' pathfinding algorithm. Lower number -> higher complexity. The 'manhattan' router performs best when step has the same value as dia.Paper.option.gridSize . Default is 10 . |
---|---|---|
padding | number | object | Padding applied around start/end elements and obstacles. Default is the step value (see above). The util.normalizeSides function is used to understand the provided value. A single number is applied as padding to all sides of the elements. An object may be provided to specify values for left , top , right , bottom , horizontal and/or vertical sides. |
maximumLoops | number | The maximum number of iterations of the pathfinding loop. If the number of iterations exceeds this maximum, pathfinding is aborted and the fallback router ('orthogonal' ) is used instead. Higher number -> higher complexity. Default is 2000 . |
maxAllowedDirectionChange | number | Maximum change of direction of the 'manhattan' route, in degrees. Default is 90 . |
perpendicular | boolean | Should the linkView.perpendicular option be in effect? This causes the router not to link precisely to the anchor of the end element but rather to a point close by that is orthogonal. This creates a clean connection between the element and the first/last vertex of the route. Default is true . |
excludeEnds | Array<string> | An array with strings 'source' and/or 'target' that tells the algorithm that the given end element(s) should not be considered as an obstacle. Default is [] (both are considered obstacles). |
excludeTypes | Array<string> | An array of element types that should not be considered obstacles when calculating the route. Default is ['basic.Text'] . |
startDirections | Array<string> | An array that specifies the possible starting directions from an element. Change this in situations where you need the link to, for example, always start at the bottom of the source element (then, the value would be ['bottom'] ). Default is ['left', 'right', 'top', 'bottom'] (all directions allowed). |
endDirections | Array<string> | An array that specifies the possible ending directions to an element. Change this in situations where you need the link to, for example, always end at the bottom of the source element (then, the value would be ['bottom'] ). Default is ['left', 'right', 'top', 'bottom'] (all directions allowed). |
Example:
link.router('manhattan', {
excludeEnds: ['source'],
excludeTypes: ['myNamespace.MyCommentElement'],
startDirections: ['top'],
endDirections: ['bottom']
});
The 'metro'
router is a modification of the 'manhattan'
router that produces an octolinear route (i.e. a route consisting of orthogonal and diagonal line segments, akin to the London Underground map design). It also avoids obstacles, and accepts the same router.args
as 'manhattan'
, with a few modifications:
maximumLoops | number | Does not use the 'orthogonal' router as fallback if path cannot to be found in the given number of iterations. Instead, a custom octolinear fallback route is used that does not avoid obstacles. |
---|---|---|
maxAllowedDirectionChange | number | Default changes to 45 . |
startDirection | Array<string> | Same as 'manhattan' (i.e. only the four orthogonal directions are accepted as start directions). |
endDirection | Array<string> | Same as 'manhattan' (i.e. only the four orthogonal directions are accepted as end directions). |
Example:
link.router('metro', {
excludeEnds: ['source'],
excludeTypes: ['myNamespace.MyCommentElement'],
startDirections: ['top'],
endDirections: ['bottom']
});
The 'normal'
router is the default router for links and it is the simplest router. It does not have any options and it does not do anything; it returns the vertices passed to it without modification as the route to be taken.
Example:
link.router('normal');
The 'oneSide'
router is a restricted version of the 'orthogonal'
router. Exactly three route segments are generated. The route leaves the start element in a specified direction (the args.side
property), transitions with a single segment towards the end element, and then enters the end element from the specified direction again. Note that this router does not support link vertices
. The router does not avoid obstacles. Two arguments are accepted, which can be passed within the router.args
property.
side | string | The direction of the route. Either 'left' , 'right' , 'top' or 'bottom' . Default is 'bottom'. |
---|---|---|
padding | number | object | The minimum distance from element at which the first/last route angle may be placed. Default is 40 . The util.normalizeSides function is used to understand the provided value. A single number is applied as padding to all sides of the elements. An object may be provided to specify values for left , top , right , bottom , horizontal and/or vertical sides. Only the side specified in the side argument is considered by the router (see above). |
Example:
link.router('oneSide', {
side: 'top',
padding: 30
});
The 'orthogonal'
router returns a route with orthogonal line segments. It generates extra route points in order to create the right angles on the way. It does not avoid obstacles. The router has one optional argument; this can be passed as the router.args.elementPadding
property:
padding | number | object | The minimum distance from element at which the first/last route angle may be placed. Default is 20 . The util.normalizeSides function is used to understand the provided value. A single number is applied as padding to all sides of the elements. An object may be provided to specify values for left , top , right , bottom , horizontal and/or vertical sides. |
---|
Example:
link.router('orthogonal', {
padding: 10
});
(Deprecated) For the purposes of backwards compatibility, the 'orthogonal'
router can also be enabled by setting the link.manhattan
property to true
. Note that the meaning of manhattan
in JointJS has changed over time.
// deprecated
link.set('manhattan', true);
The Devs plugin provides you with ready-to-use shapes with predefined input & output port groups and simplified API.
The Model shape implements simple API on top of the JointJS built-in ports. It splits ports into two semantic groups (in and out) and adds convenient methods for adding and removing ports.
inPorts | an array of all input ports |
---|---|
outPorts | an array of all output ports |
element.addInPort(port, [opt])
Add a single port into the `inPorts` array, where `port` is a name of the port.
element.addOutPort(port, [opt])
Add a single port into the `outPorts` array, where `port` is a name of the port.
element.changeInGroup(properties, [opt])
Change the settings for the input ports, where `properties` is an object with a group configuration. It extends the previous settings with the new configuration by default. Pass { rewrite: true }
via opt
to invalidate the previous settings.
element.changeOutGroup(properties, [opt])
Change the settings for the output ports, where `properties` is an object with a group configuration. It extends the previous settings with the new configuration by default. Pass { rewrite: true }
via opt
to invalidate the previous settings.
element.removeInPort(port, [opt])
Remove a port from an element from the `inPorts` array, where `port` is a name of the port.
element.removeOutPort(port, [opt])
Remove a port from an element from the `outPorts` array, where `port` is a name of the port.
The devs.Link
extends the joint.dia.Link
and changes the link appearance.
var shape = new joint.shapes.devs.Model({
position: {
x: 100,
y: 100
},
inPorts: ['in1', 'in2'],
outPorts: ['out1', 'out2']
});
shape.addTo(graph);
// adding/removing ports dynamically
shape.addInPort('in3');
shape.removeOutPort('out1').addOutPort('out3');
var link = new joint.shapes.devs.Link({
source: {
id: shape.id,
port: 'out3'
},
target: {
x: 200,
y: 300
}
});
link.addTo(graph);
// moving the input ports from `left` to `top`
shape.changeInGroup({ position: 'top' });
// moving the output ports 'right' to 'bottom'
shape.changeOutGroup({ position: 'bottom' });
There are two more shapes designed for hierarchical diagrams as part of the plugin - devs.Atomic
and devs.Coupled
. They inherit from the devs.Model
and differ only in the color and size. The purpose of these shapes is to enable you to implement a custom logic in your application based on their type.
For instance a devs.Coupled
can embed devs.Atomic
's but not the other way round as shown in the demo below.
When working with hierarchical diagrams there is a few methods, that might come in handy.
coupled.embed(atomic)
that can put the `atomic` shape into the `coupled`.
coupled.fitEmbeds()
that resizes the `coupled` shape, so it visually contains all shapes embedded in.
link.reparent()
that finds the best parent for the `link` based on the source and target element.
The Standard plugin provides you with ready-to-use, high-performance versions of the most common shapes. The shapes can be used as they are or can serve as an inspiration for creating custom shapes.
An image with a border and label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
image | SVGImageElement | Image body of the shape |
border | SVGRectElement | Border around the image |
background | SVGRectElement | Area behind the image |
label | SVGTextElement | Text below the image |
var borderedImage = new joint.shapes.standard.BorderedImage();
borderedImage.resize(150, 100);
borderedImage.position(225, 410);
borderedImage.attr('root/title', 'joint.shapes.standard.BoarderedImage');
borderedImage.attr('label/text', 'Bordered\nImage');
borderedImage.attr('border/rx', 5);
borderedImage.attr('image/xlinkHref', 'image.png');
borderedImage.addTo(graph);
A circle with a label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
body | SVGCircleElement | Circular body of the shape |
label | SVGTextElement | Text inside the body |
var circle = new joint.shapes.standard.Circle();
circle.resize(100, 100);
circle.position(250, 10);
circle.attr('root/title', 'joint.shapes.standard.Circle');
circle.attr('label/text', 'Circle');
circle.attr('body/fill', 'lightblue');
circle.addTo(graph);
A cylinder with a label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
body | SVGPathElement | Lateral area of the cylinder
The shape has a custom attribute |
top | SVGEllipseElement | Top of the cylinder (cylinder base) |
label | SVGTextElement | Text inside the body |
cylinder.topRy()
Return the vertical radius of the exposed area of the cylinder base (the value of the body/lateralArea
attribute; 10
by default).
cylinder.topRy(t, [opt])
Set the cylinder vertical radius of the exposed area of the cylinder base.
If the provided value is a percentage, it is relative to the refBBox.height
of the shape. In practice, only values between '0%'
and '50%'
make sense. If the provided value is a number, it determines the vertical radius directly. Only values between 0
and half of refBBox.height
make sense.
The function automatically sets the value of several attributes: body/lateralArea
; and top/ry
, top/cy
, top/refRy
and top/refCy
. If these arguments need to be modified further, make sure to assign them only after calling cylinder.topRy
.
Example usage:
var cylinder = new standard.Cylinder();
cylinder.resize(100, 200);
cylinder.position(525, 75);
cylinder.attr('root/title', 'joint.shapes.standard.Cylinder');
cylinder.attr('body/fill', 'lightgray');
cylinder.attr('top/fill', 'gray');
cylinder.attr('label/text', 'Cylinder');
cylinder.topRy('10%');
cylinder.addTo(graph);
A double line link.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
line | SVGPathElement | Inner connection |
outline | SVGPathElement | Outer connection |
var doubleLink = new joint.shapes.standard.DoubleLink();
doubleLink.prop('source', { x: 500, y: 600 });
doubleLink.prop('target', { x: 450, y: 750 });
doubleLink.prop('vertices', [{ x: 500, y: 700 }]);
doubleLink.attr('root/title', 'joint.shapes.standard.DoubleLink');
doubleLink.attr('line/stroke', '#30d0c6');
doubleLink.addTo(graph);
An ellipse with a label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
body | SVGEllipseElement | Elliptical body of the shape |
label | SVGTextElement | Text inside the body |
var ellipse = new joint.shapes.standard.Ellipse();
ellipse.resize(150, 100);
ellipse.position(425, 10);
ellipse.attr('root/title', 'joint.shapes.standard.Ellipse');
ellipse.attr('label/text', 'Ellipse');
ellipse.attr('body/fill', 'lightblue');
ellipse.addTo(graph);
An image embedded into a rectangle with a label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
body | SVGRectElement | Rectangular body of the shape |
image | SVGImageElement | Image inside the body |
label | SVGTextElement | Text next to the image |
var embeddedImage = new joint.shapes.standard.EmbeddedImage();
embeddedImage.resize(150, 100);
embeddedImage.position(425, 410);
embeddedImage.attr('root/title', 'joint.shapes.standard.EmbeddedImage');
embeddedImage.attr('label/text', 'Embedded\nImage');
embeddedImage.attr('image/xlinkHref', 'image.png');
embeddedImage.addTo(graph);
A rectangle with header.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
body | SVGRectElement | Rectangular body of the shape |
header | SVGRectElement | Rectangular header of the shape |
headerText | SVGTextElement | Text inside the header |
bodyText | SVGTextElement | Text inside the body |
var headeredRectangle = new joint.shapes.standard.HeaderedRectangle();
headeredRectangle.resize(150, 100);
headeredRectangle.position(25, 610);
headeredRectangle.attr('root/title', 'joint.shapes.standard.HeaderedRectangle');
headeredRectangle.attr('header/fill', 'lightgray');
headeredRectangle.attr('headerText/text', 'Header');
headeredRectangle.attr('bodyText/text', 'Headered\nRectangle');
headeredRectangle.addTo(graph);
An image with a label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
image | SVGImageElement | Image body of the shape |
label | SVGTextElement | Text below the image |
var image = new joint.shapes.standard.Image();
image.resize(150, 100);
image.position(25, 410);
image.attr('root/title', 'joint.shapes.standard.Image');
image.attr('label/text', 'Image');
image.attr('image/xlinkHref', 'image.png');
image.addTo(graph);
An image inscribed in an ellipse with a label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
image | SVGImageElement | Image inscribed in the ellipse |
border | SVGEllipseElement | Border around the ellipse |
background | SVGEllipseElement | Area of the ellipse |
label | SVGTextElement | Text below the shape |
var inscribedImage = new joint.shapes.standard.InscibedImage();
inscribedImage.resize(150, 100);
inscribedImage.position(225, 410);
inscribedImage.attr('root/title', 'joint.shapes.standard.InscribedImage');
inscribedImage.attr('label/text', 'Inscribed Image');
inscribedImage.attr('border/strokeWidth', 5);
inscribedImage.attr('background/fill', 'lightgray');
inscribedImage.attr('image/xlinkHref', 'image.png');
inscribedImage.addTo(graph);
A single line link.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
line | SVGPathElement | Visible connection of the link |
wrapper | SVGPathElement | Invisible wrapper around the connection to make the line thicker, so the user can interact with the link more easily. |
var link = new joint.shapes.standard.Link();
link.prop('source', { x: 450, y: 600 });
link.prop('target', { x: 400, y: 750 });
link.prop('vertices', [{ x: 450, y: 700 }]);
link.attr('root/title', 'joint.shapes.standard.Link');
link.attr('line/stroke', '#fe854f');
link.addTo(graph);
A path with a label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
body | SVGPathElement | Generic body of the shape |
label | SVGTextElement | Text inside the body |
var path = new joint.shapes.standard.Path();
path.resize(100, 100);
path.position(50, 210);
path.attr('root/title', 'joint.shapes.standard.Path');
path.attr('label/text', 'Path');
path.attr('body/refD', 'M 0 5 10 0 C 20 0 20 20 10 20 L 0 15 Z');
path.addTo(graph);
A polygon with a label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
body | SVGPolygonElement | Polygonal body of the shape |
label | SVGTextElement | Text inside the body |
var polygon = new joint.shapes.standard.Polygon();
polygon.resize(100, 100);
polygon.position(250, 210);
polygon.attr('root/title', 'joint.shapes.standard.Polygon');
polygon.attr('label/text', 'Polygon');
polygon.attr('body/refPoints', '0,10 10,0 20,10 10,20');
polygon.addTo(graph);
A polyline with a label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
body | SVGPolylineElement | Generic body of the shape |
label | SVGTextElement | Text inside the body |
var polyline = new joint.shapes.standard.Polyline();
polyline.resize(100, 100);
polyline.position(450, 210);
polyline.attr('root/title', 'joint.shapes.standard.Polyline');
polyline.attr('label/text', 'Polyline');
polyline.attr('body/refPoints', '0,0 0,10 10,10 10,0');
polyline.addTo(graph);
A rectangle with a label.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
body | SVGRectElement | Rectangular body of the shape |
label | SVGTextElement | Text inside the body |
var rectangle = new joint.shapes.standard.Rectangle();
rectangle.resize(100, 100);
rectangle.position(50, 10);
rectangle.attr('root/title', 'joint.shapes.standard.Rectangle');
rectangle.attr('label/text', 'Rectangle');
rectangle.attr('body/fill', 'lightblue');
rectangle.addTo(graph);
A thicker line with shadow.
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
line | SVGPathElement | Visible connection of the link |
shadow | SVGPathElement | Shadow of the connection |
var shadowLink = new joint.shapes.standard.ShadowLink();
shadowLink.prop('source', { x: 550, y: 600 });
shadowLink.prop('target', { x: 500, y: 750 });
shadowLink.prop('vertices', [{ x: 550, y: 700 }]);
shadowLink.attr('root/title', 'joint.shapes.standard.ShadowLink');
shadowLink.attr('line/stroke', '#5654a0');
shadowLink.addTo(graph);
A rectangle with an HTML label (with a fallback to SVG label for IE).
Supportedattrs
properties
Selector | Node | Description |
---|---|---|
root | SVGGElement | Container of all nodes |
body | SVGRectElement | Rectangular body of the shape |
label | HTMLDivElement | Text inside the body |
var textBlock = new joint.shapes.tandard.TextBlock();
textBlock.resize(100, 100);
textBlock.position(250, 610);
textBlock.attr('root/title', 'joint.shapes.standard.TextBlock');
textBlock.attr('body/fill', 'lightgray');
textBlock.attr('label/text', 'Hyper Text Markup Language');
// Styling of the label via `style` presentation attribute (i.e. CSS).
textBlock.attr('label/style/color', 'red');
textBlock.addTo(graph);
util.assign(destinationObject [, ...sourceObjects])
(Deprecated) An alias for _.assign
. See the Lodash documentation entry for more information.
util.bindAll(object, methodNames)
An alias for _.bindAll
. See the Lodash documentation entry for more information.
util.breakText(text, size [, attrs, opt])
Break the provided text
into lines so that it can fit into the bounding box defined by size.width
and (optionally) size.height
.
The function creates a temporary SVG <text>
element and adds words to it one by one, measuring the element's actual rendered width and height at every step. If a word causes a line to overflow size.width
, a newline character ('\n'
) is generated. If a newline causes the text to overflow size.height
, the string is cut off.
The returned string is a (possibly truncated) copy of text
with newline characters at appropriate locations.
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100 })
// 'lorem ipsum\ndolor sit amet\nconsectetur\nadipiscing elit'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 })
// 'lorem ipsum\ndolor sit amet'
The attrs
parameter is an object with SVG attributes that should be set on the temporary SVG text element while it is being measured (such as 'font-weight'
, 'font-size'
, 'font-family'
, etc.). For example, an area of fixed size can obviously fit more words of font size 12px
than it can fit words of font size 36px
. If nothing can fit, an empty string is returned. (If an attrs
object is not provided, the browser's default style is used.)
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 12 })
// 'lorem ipsum dolor\nsit amet consectetur\nadipiscing elit'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 16 })
// 'lorem ipsum\ndolor sit amet'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 36 })
// 'lorem'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 72 })
// ''
The method also accepts the following additional options:
opt.separator
- a string or a regular expression which denotes how to split the text into words. Defaults to ' '
opt.eol
- a string representing the end-of-line symbol. Defaults to '\n'
.opt.ellipsis
- a boolean that specifies whether the ellipsis symbol ('…'
, U+2026 HORIZONTAL ELLIPSIS
) should be displayed when the text overflows. Defaults to false
. If you provide a string, that string will be used as the ellipsis symbol instead.opt.svgDocument
- an SVG document to which the temporary SVG text element should be added. By default, an SVG document is created automatically for you.Examples of text with the ellipsis
option specified:
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 12 }, { ellipsis: true })
// 'lorem ipsum dolor\nsit amet consectetur\nadipiscing elit'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 16 }, { ellipsis: true })
// 'lorem ipsum\ndolor sit ame…'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 16 }, { ellipsis: '...!?' })
// 'lorem ipsum\ndolor sit a...!?'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 36 }, { ellipsis: true })
// 'lore…'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 36 }, { ellipsis: true })
// ''
If you need to wrap text inside a text
attribute of an Element, you should use the textWrap
attribute instead. It does not require you to provide explicit size measurements, and it automatically responds to element resizing.
util.camelCase(string)
An alias for _.camelCase
. See the Lodash documentation entry for more information.
util.cancelFrame(requestId)
Cancels an animation frame request identified by requestId
previously scheduled through a call to joint.util.nextFrame.
util.clone(value)
An alias for _.clone
. See the Lodash documentation entry for more information.
util.cloneDeep(value)
An alias for _.cloneDeep
. See the Lodash documentation entry for more information.
util.dataUriToBlob(dataUri)
Convert a Data URI string into a Blob object.
util.debounce(func [, wait, options])
An alias for _.debounce
. See the Lodash documentation entry for more information.
util.deepMixin(destinationObject, sourceObject, options)
(Deprecated) An alias for _.mixin
. See the Lodash documentation entry for more information.
util.deepSupplement(destinationObject [, ...sourceObjects])
(Deprecated) An alias for _.defaultsDeep
. See the Lodash documentation entry for more information.
Use the util.defaultsDeep
function instead.
util.defaults(destinationObject [, ...sourceObjects])
An alias for _.defaults
. See the Lodash documentation entry for more information.
util.defaultsDeep(destinationObject [, ...sourceObjects])
An alias for _.defaultsDeep
. See the Lodash documentation entry for more information.
util.difference(array [, ...excludedValuesArrays])
An alias for _.difference
. See the Lodash documentation entry for more information.
util.downloadBlob(blob, fileName)
Download provided Blob object as a file with given fileName
.
util.downloadDataUri(dataUri, fileName)
Download provided Data URI string as a file with given fileName
.
util.flattenDeep(array)
An alias for _.flattenDeep
. See the Lodash documentation entry for more information.
util.flattenObject(object, delim, stop)
Flatten a nested object
up until the stop
function returns true
. The stop
function takes the value of the node currently traversed. delim
is a delimiter for the combined keys in the resulting object. Example:
joint.util.flattenObject({
a: {
a1: 1,
a2: 2,
a3: {
a31: 5,
a32: {
a321: { a3211: 5 }
}
}
},
b: 6
}, '/', function(v) { return !!v.a321; });
/*
{
"a/a1": 1,
"a/a2": 2,
"a/a3/a31": 5,
"a/a3/a32": {
"a321": {
"a3211": 5
}
},
"b": 6
}
*/
util.forIn(object [, iteratee])
An alias for _.forIn
. See the Lodash documentation entry for more information.
util.getByPath(object, path, delim)
Return a value at the path
in a nested object
. delim
is the delimiter used in the path
Example:
joint.util.getByPath({ a: { aa: { aaa: 3 } } }, 'a/aa/aaa', '/');
// 3
util.getElementBBox(el)
Return a bounding box of the element el
. The advantage of this method is that it can handle
both HTML and SVG elements. The resulting object is of the form { x: Number, y: Number, width: Number, height: Number }
.
util.groupBy(collection [, iteratee])
An alias for _.groupBy
. See the Lodash documentation entry for more information.
util.guid()
Return an identifier unique for the page.
util.has(object, propertyPath)
An alias for _.has
. See the Lodash documentation entry for more information.
util.hashCode(str)
Return a simple hash code from a string.
util.imageToDataUri(url, callback)
Convert an image at url
to the Data URI scheme. The function is able to handle PNG, JPG and SVG formats. Useful if you need to embed images directly into your diagram instead of having them referenced externally.
The callback
function has the following signature: function(err, dataUri) {}
.
util.intersection([...arrays])
An alias for _.intersection
. See the Lodash documentation entry for more information.
util.invoke(collection, methodPath [, args])
util.invoke(collection, functionToInvokeForAll [, args])
An alias for _.invokeMap
. See the Lodash documentation entry for more information.
util.isBoolean(value)
Return true
when value
is a boolean.
util.isEmpty(value)
An alias for _.isEmpty
. See the Lodash documentation entry for more information.
util.isEqual(value, otherValue)
An alias for _.isEqual
. See the Lodash documentation entry for more information.
util.isFunction(value)
An alias for _.isFunction
. See the Lodash documentation entry for more information.
util.isNumber(value)
Return true
when value
is a number.
util.isObject(value)
Return true
when value
is an object (plain object or a function).
util.isPercentage(value)
Return true
when value
is a string that holds a percentage value, e.g. '10%'
.
util.isPlainObject(value)
An alias for _.isPlainObject
. See the Lodash documentation entry for more information.
util.isString(value)
Return true
when value
is a string.
util.merge(destinationObject, ...sourceObjects [, customizer])
An alias for _.mergeWith
. See the Lodash documentation entry for more information.
util.mixin(destinationObject [, ...sourceObjects])
(Deprecated) An alias for _.assign
(not _.mixin
). See the Lodash documentation entry for more information.
util.nextFrame(callback [, context])
Tell the browser to schedule the callback
function to be called before the next repaint.
This is a cross-browser version of the window.requestAnimationFrame function.
Returns an ID of the frame request. For convenience, you can pass a context
for your callback
function.
util.noop()
An empty function with no return statement (void
in Typescript).
util.normalizeEvent(evt)
Normalize the provided event.
For touch events, the normalized event receives a copy of all properties from evt.originalEvent
that are not included in evt
.
Additionally, if evt.target.correspondingUseElement
is defined (as in IE), that element is assigned as target
in the normalized event.
util.normalizeSides(box)
Return a new object of the form { top: Number, right: Number, bottom: Number, left: Number }
.
If box
is a number, the value of all four sides will be this number. If box
is an object with some/all of the top
, right
, bottom
, left
properties defined, the values of these properties will be used.
Composite properties horizontal
(for right and left side) and vertical
(for top and bottom side) can be used, as well; they will be destructured appropriately. When two properties clash (e.g. horizontal: 10
and left: 5
), the more specific one prevails (here the returned object would contain right: 10
and left: 5
).
If any property is missing, its side will be set to 0
in the resulting object.
joint.util.normalizeSides() // { top: 0, right: 0, bottom: 0, left: 0 }
joint.util.normalizeSides(5) // { top: 5, right: 5, bottom: 5, left: 5 }
joint.util.normalizeSides({ horizontal: 5 }) // { top: 0, right: 5, bottom: 0, left: 5 }
joint.util.normalizeSides({ left: 5 }) // { top: 0, right: 0, bottom: 0, left: 5 }
joint.util.normalizeSides({ horizontal: 10, left: 5 }) // { top: 0, right: 10, bottom: 0, left: 5 }
joint.util.normalizeSides({ horizontal: 0, left: 5 }) // { top: 0, left: 5, right: 0, bottom: 0 }
JointJS and Rappid use this method internally whenever there is an option object that can be specified either by a number or a (possibly incomplete) object with sides (for example, the padding
option).
util.omit(object [, ...propertyPathsToOmit])
An alias for _.omit
. See the Lodash documentation entry for more information.
util.parseCssNumeric(value)
Parse the provided value as a float and return an object with the number as the value
parameter. If the value cannot be converted into a number, return null
.
If the number is followed by a unit, assign it as the unit
parameter in the return object. If there is no unit, assign an empty string. Examples:
joint.util.parseCssNumeric('hello'); // => null
joint.util.parseCssNumeric(1.1); // => { value: 1.1, unit: '' }
joint.util.parseCssNumeric('1.1'); // => { value: 1.1, unit: '' }
joint.util.parseCssNumeric('1.1px'); // => { value: 1.1, unit: 'px' }
joint.util.parseCssNumeric('1.1em'); // => { value: 1.1, unit: 'em' }
util.parseCssNumeric(value, restrictUnits)
Parse the provided value and only accept it if its unit is part of the restrictUnits
parameter; otherwise return null
.
The restrictUnits
parameter can be a string or an array of strings. If you provide an empty string, that means you are expecting value
to have no unit. Providing an empty array always returns null
. Examples:
joint.util.parseCssNumeric(1.1, ''); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1', ''); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1px', ''); // => null
joint.util.parseCssNumeric('1.1px', 'px'); // => { value: 1.1, unit: 'px' });
joint.util.parseCssNumeric('1.1px', 'em'); // => null
joint.util.parseCssNumeric(1.1, []); // => null
joint.util.parseCssNumeric('1.1', []); // => null
joint.util.parseCssNumeric('1.1px', []); // => null
joint.util.parseCssNumeric(1.1, ['']); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1', ['']); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1px', ['px']); // => { value: 1.1, unit: 'px' });
joint.util.parseCssNumeric('1.1px', ['em']); // => null
joint.util.parseCssNumeric(1.1, ['', 'px']); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1', ['', 'px']); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1px', ['', 'px']); // => { value: 1.1, unit: 'px' })
joint.util.parseCssNumeric('1.1em', ['', 'px']); // => null
util.pick(object [, ...propertyPathsToPick])
An alias for _.pick
. See the Lodash documentation entry for more information.
util.result(object, propertyPath [, defaultValue])
An alias for _.result
. See the Lodash documentation entry for more information.
util.sanitizeHTML(html)
Sanitize the provided HTML (string) to protect against XSS attacks. The algorithm has several steps:
<div>
tag. This will remove tags that are invalid in that context (e.g. <body>
and <head>
).jQuery.parseHTML()
). This prevents inline events from firing and also prevents image GET requests from being sent.<script>
tags.on...
attributes (e.g. onload
, onerror
).javascript:
pseudo-protocol as value.The six simple steps protect against the most common XSS attacks; however, we cannot guarantee bulletproof security here. If you need stronger security, you should always keep an eye on a list XSS attacks and replace the joint.util.sanitizeHTML()
function with your own, more secure version.
Examples:
joint.util.sanitizeHTML('<html><body><p>Hello</p></body></html>'); // => '<p>Hello</p>'
joint.util.sanitizeHTML('<p>Hello</p><script>alert("Hacked");</script>'); // => '<p>Hello</p>'
joint.util.sanitizeHTML('<p>Hello</p><img onload="alert("Hacked");">'); // => '<p>Hello</p><img>'
joint.util.sanitizeHTML('<p>Hello</p><img src="javascript:alert("Hacked");">'); // => '<p>Hello</p><img>'
util.setAttributesBySelector(el, attrs)
Set attributes on the DOM element (SVG or HTML) el
and its descendants based on the selector in the attrs
object. The attrs
object is of the form: { [selector]: [attributes }
. For example:
var myEl = document.querySelector('.mydiv');
joint.util.setAttributesBySelector(myEl, {
'.myDiv': { 'data-foo': 'bar' }, // Note the reference to the myEl element itself.
'input': { 'value': 'my value' }
});
The code above sets 'data-foo'
attribute of the myEl
element to the value 'bar'
and 'value'
attribute of all the descendant inputs to the value 'my value'
. This is a convenient way of setting attributes on elements (including themselves) and their descendants. Note that 'class'
attribute is treated as a special case and its value does not override the previous value of the 'class'
attribute. Instead, it adds this new class to the list of classes for the element referenced in the selector.
util.setByPath(object, path, value, delim)
Set a value
at the path
in a nested object
. delim
is the
delimiter used in the path
. Returns the augmented object
.
joint.util.setByPath({ a: 1 }, 'b/bb/bbb', 2, '/');
/*
{
"a": 1,
"b": {
"bb": {
"bbb": 2
}
}
}
*/
util.shapePerimeterConnectionPoint(linkView, view, magnet, ref)
(Deprecated) This function can be directly used in the dia.Paper linkConnectionPoint
parameter. When used, links will try to find the best connection point right on the perimeter of the connected shape rather than only on the bounding box. See the image below.
var paper = new joint.dia.Paper({
// ...
linkConnectionPoint: joint.util.shapePerimeterConnectionPoint
// ...
})
util.sortBy(collection [, iterateesArray])
An alias for _.sortBy
. See the Lodash documentation entry for more information.
util.sortedIndex(sortedArray, valueToInsert [, iteratee])
An alias for _.sortedIndexBy
. See the Lodash documentation entry for more information.
util.sortElements(elements, comparator)
Change the order of elements
(a collection of HTML elements or a selector or jQuery object) in the DOM
according to the comparator(elementA, elementB)
function. The comparator
function has
the exact same meaning as in Array.prototype.sort(comparator)
.
util.supplement(destinationObject [, ...sourceObjects])
(Deprecated) An alias for _.defaults
. See the Lodash documentation entry for more information.
Use the util.defaults
function instead.
util.template(html)
Return a template function that returns pre-compiled html
when called.
util.toArray(value)
An alias for _.toArray
. See the Lodash documentation entry for more information.
util.toggleFullScreen([element])
Make (or cancel) an element
to be displayed full-screen. The default element is window.top.document.body
.
joint.util.toggleFullScreen(paper.el);
util.toKebabCase(str)
Convert the string to kebab-case. Example:
joint.util.toKebabCase('strokeWidth'); // => 'stroke-width'
util.union([...arrays])
An alias for _.union
. See the Lodash documentation entry for more information.
util.uniq(array [, iteratee])
An alias for _.uniqBy
. See the Lodash documentation entry for more information.
util.uniqueId([prefix])
An alias for _.uniqueId
. See the Lodash documentation entry for more information.
util.unsetByPath(object, path, delim)
Unset (delete) a property at the path
in a nested object
. delim
is the
delimiter used in the path
. Returns the augmented object
.
joint.util.unsetByPath({ a: { aa: { aaa: 3 } } }, 'a/aa/aaa', '/');
// { a: { aa: {} } }
util.without(array [, ...values])
An alias for _.without
. See the Lodash documentation entry for more information.
util.format.number(specifier, value)
Format number value
according to the specifier
defined via the Python Format Specification Mini-language.
joint.util.format.number('.2f', 5) // 5.00
joint.util.format.number('03d', 5) // 005
joint.util.format.number('.1%', .205) // 20.5%
joint.util.format.number('*^9', 5) // ****5****