Chart
Chart functions allow you to draw content on the chart surface, zoom and pan around the chart, and perform layouts. To obtain a chart object to call these functions on, use KeyLines.create.
Allows custom animations to be made and chained together.
Pass a single item object (or an array of objects) in the form {id: id, propertyName1: value1, propertyName2: value2 }. Items with a matching id will be animated.
Animations can either be applied to numeric properties:
// first animate the node to (100, 100) in 300 milliseconds and then move another node to this position
chart.animateProperties({ id: 'id1', x: 100, y: 100 }, { time: 300 }).then(() => {
return chart.animateProperties({ id: 'id2', x: 100, y: 100 }, { time: 500 });
});
Or to colours:
// changes the link colour to blue with an alpha blend of 0.5 in an animation lasting 300 ms
chart.animateProperties({ id: 'link1', c: 'rgba(0,0,255,0.5)' }, { time: 300 });
When animating properties in the top level object, you only need to specify the properties that you want to animate. When animating properties in the nested object, you need to specify both animated and unchanged properties:
chart.setProperties({ id: 'link1', fbc: 'yellow', t: 'link', t1: 'endLabel1', t2: 'endLabel2' });
// animating the nested fbc property for t1 and t2 requires repeating the t properties as well
chart.animateProperties([{ id: 'link1', w: 15, fbc: 'orange', t1: { t: 't1', fbc: 'red' }, t2: { t: 't2', fbc:'green' } }]);
See the relevant numeric and colour properties in Item Format.
Note: Animating properties is not supported in Advanced label styling for items inside the styled node label t object.
Parameters
- items required
-
Node | Link | Annotation | (Node | Link | Annotation)[] The item/s whose properties are to be changed.
Options to control the animation.
"linear" | "cubic"
default: 'linear' The easing function for animation. If set to 'linear', the speed is constant. If set to 'cubic', the animation starts slow, speeds up and then finishes slow.
boolean
default: true If true, the animation is queued until all previous queued animations have completed. If false, the animation begins immediately.
number
default: 1000 The time the animation should take, in milliseconds.
Returns
Promise
Places a set of nodes together in close proximity.
chart.arrange('grid', ['id1', 'id2', 'id3'], { fit: true, animate: true }).then(() => {
// do more after arrange
});
The nodes are arranged in the specified shape in the order that they appear in the items array.
Parameters
Options to control the arrangement of the nodes.
- 'absolute': use the
xandyoptions to centre the arrangement. - 'average': use the average position of the nodes to centre the arrangement.
- 'tidy': the chart is rearranged to position the nodes so they do not overlap with other nodes.
boolean
default: true Whether the result should be animated.
boolean
default: false Whether to fit the chart into the window at the end of the arrangement.
"absolute" | "average" | "tidy"
default: 'average' Controls the position of the group of arranged nodes.
number
default: 5 Controls how close nodes are to each other. Must be in the range 0 to 10, with higher values being closer.
number
default: 700 If animated, the time the animation should take, in milliseconds.
number
default: 0 When position is set to 'absolute', the x coordinate of the centre of the nodes.
number
default: 0 When position is set to 'absolute', the y coordinate of the centre of the nodes.
Returns
Promise
A Promise.
Removes all items from the chart.
Returns
void
The combo namespace has methods for combining the nodes and links of a chart to simplify it. See Combo Functions.
Returns
Combo
The combo namespace which has functions for combining items together.
Returns an array of ids of all the nodes or shapes contained inside the given shape.
Shapes are legacy nodes that are drawn behind nodes and links. They are set by specifying w and h for nodes and setting the legacyShapeNodeBehaviour option to true.
Things to note:
- If no nodes or shapes are contained within the parent shape, the function returns an empty array.
- If one or both of
wandhparent shape dimensions are set to 'auto', the function returns an empty array. - Hidden items are returned.
- Open combos or their contents are not returned.
- If the shape contains other items, their ids will be returned only if they are fully contained within the shape.
Parameters
- shape required
The definition of the shape.
Returns
string[]
The ids of the items contained in the shape (if any).
Creates a special type of drag that lets a user draw a new link starting from a specified node. As a result, it should always be called from within a drag-start event handler to ensure that the user is dragging:
chart.on('drag-start', (e) => {
const { id, type } = e;
if (type === 'node') {
// override the default node dragger with create-link
chart.createLink(id, 'newLink').then(() => {
// do more after createLink
});
}
});
Note that this function allows the user to draw a new link during dragging. It does not create a new link immediately. To create a new link without user interaction, use setItem.
Parameters
Options to control the style of the link.
Returns
Promise
A Promise that resolves with the id of the linked item, or null if the user did not create a link.
Destroys the current instance of the chart, freeing any allocated resources.
Note: This action cannot be undone. Create a new chart instance with KeyLines.create() to access the chart namespace.
chart.destroy()
Returns
void
Allows easy iteration over all the items in the chart. The handler is called with one parameter: the current item.
// write all the labels for each node to the console
chart.each({ type:'node' }, (item) => {
console.log(item.id, item.t);
});
For details of using chart.each() with combos, see the Iterating over items section in Combos Concepts.
Parameters
- options required
Options controlling how to iterate over the chart items.
- 'underlying': iterates over items that are not combo nodes or combo links.
- 'toplevel': iterates over items, including combos, that are not inside other combos.
- 'all': iterates over every item.
"all" | "toplevel" | "underlying"
default: 'underlying' The chart items to iterate over when using combos.
type
required "all" | "node" | "link" | "annotation" The type of items to consider.
Returns
void
The expand() function is the easiest way to add new items to the chart. It performs a merge() followed by a layout().
const newItems = [
{ id: 'newNode', type: 'node', t: 'New Node' },
{ id: 'newLink', type: 'link', t: 'New Link', id1: 'newNode', id2: 'oldNode' }
];<br>chart.expand(newItems, { animate: true, layout: { fit: true } }).then(() => {
// do more after expand
});
If no layout is specified, expand() will use the organic layout by default.
If you have a current filter applied to the chart and want to keep the filter state consistent when new items are added to the chart, use the filter option:
function myFilter(item) {
return (item.d.value > 10);
}<br>chart.expand(newItems, {animate: true, filter: { filterFn: myFilter, type: "node" } }).then(() => {
// do more after expand
});
If there are multiple links between two nodes, expand() will automatically apply an offset to the links.
Things to note:
- The
layout()function is not supported while using a Leaflet map. - You cannot change the ends of an existing link.
- The radial layout may have non-intuitive results depending on the change of the network topology.
- Setting the
xandyproperties when usingexpand()has no effect aslayout()overwrites these positions. - You can set the
parentIdof new items to add them into a combo, but cannot change theparentIdof pre-existing items. See Combos for more detail.
Parameters
- items required
-
ChartData | Node | Link | Annotation | (Node | Link | Annotation)[] To be added to the chart, a choice of either:
- KeyLines chart object.
- A single item.
- An array of items.
Options to control the expanding action of the nodes.
- 'all': All items adapt.
- 'inCombo': Items within the parent combo(s) adapt, items at the top chart level stay unchanged.
- 'none': No items adapt.
- 'direct' - links are either straight or follow arcs when offset.
- 'curved' - link follow a curved path, and attach to nodes in the direction of
orientation. - 'angled' - links follow straight lines with corners: useful for hierarchical data sets. Currently in beta.
- 'lens' - automatic arrangement with connected nodes next to each other. The default for circular combos.
- 'concentric' - circlular arrangement with larger items at the centre.
- 'grid' - grid arrangement running from left to right, from the top down in the order in which they are added in the combo. The default for rectangular combos.
- 'sequential' - tree-like arrangement showing the sequence of links between distinct levels of nodes.
- 'none' - items are kept in their original positions.
- 'underlying': iterates over items that are not combo nodes or combo links.
- 'toplevel': iterates over items, including combos, that are not inside other combos.
- 'adaptive': fixes nodes relative to other nodes in their component, where possible.
- 'adjacent': only fixes nodes linked to new items.
- 'nonadjacent': only fixes nodes not linked to new items.
- 'all': fixes all existing nodes.
- 'none': doesn't fix any existing nodes.
- 'radial' and 'hierarchy' must have either
levelortopspecified. - 'sequential' assigns levels automatically if neither are specified (inferred from the nodes' links).
- If both the
levelandtopoptions are specified,levelis used. - 'direct' - links are either straight or follow arcs when offset.
- 'curved' - link follow a curved path, and attach to nodes in the direction of
orientation. - 'angled' - links follow straight lines with corners: useful for hierarchical data sets. Currently in beta.
- 'adaptive': components only move to make space for new items or to use space created by removed items.
- 'aligned': only for sequential, default option. Components are laid out in a single line with same level items aligned. If top is used, any components without
topspecified are packed using 'adaptive' packing. - 'circle': components are treated as circles, giving a roughly circular result.
- 'rectangle': components are treated as rectangles, giving a grid-like result.
- 'none': components are not packed.
- ‘auto’: node spacing reduces link lengths and connected components are nested together to make the most of screen space.
- ‘equal’: regular node positions with equal spacing within each connected component and a clear separation between them.
- ‘stretched’: as for ‘equal’ but each level is stretched to take up an equal amount of screen space.
- 'radial' and 'hierarchy' must have either
levelortopspecified. - 'sequential' assigns levels automatically if neither are specified (inferred from the nodes' links).
boolean
default: true Whether the result should be animated.
ExpandArrange An object specifying how the contents of any combos which have changed should be arranged.
"all" | "inCombo" | "none"
default: 'all' Controls how items (nodes and combos) outside the specified combo push away / pull towards the combo that changed during expand. This applies to items at the top chart level positioned by layout, and also to items contained in the hierarchy of one or more parent combo(s) of the specified combo. Note that if the parent combo's arrangement is set to 'grid', it always adapts.
"auto" | object
default: 'auto' When name is set to 'grid', controls the row/column dimension of the grid. Specify an object in the form { rows: number } or { columns: number }.
string When layout name is set to 'sequential', the name of the custom property on the node's or combo node's d property that defines which level the node/combo belongs to. The property must contain a numeric value, where the lowest value node is placed at the top of the hierarchy. Levels for nodes with no level data are inferred from the nodes' links.
"direct" | "curved" | "angled"
default: 'direct' The shape of the path taken by links.
The direction of 'curved' and 'angled' links is inferred from orientation.
"lens" | "concentric" | "grid" | "sequential" | "none"
default: 'lens' / 'grid' Controls how nodes are arranged inside an open combo.
string | OrderByOptions When the arrangement name is 'sequential', specifies the order of nodes/combos within the same arrangement level of a connected component in the chart. Any disconnected nodes or combos are ignored.
string The key of the custom data value on the node's d property used to order nodes alphanumerically within each level. When specified, nodes are ordered alphanumerically, in descending order, unless sortBy is also set.
"ascending" | "descending"
default: 'descending' The direction of ordering.
"left" | "right" | "up" | "down"
default: 'down' When name is set to 'sequential', the orientation of the arrangement.
"none" | "circle" | "rectangle" | "adaptive" | "aligned"
default: 'aligned' When name is set to 'sequential', the packing mode to use.
boolean
default: true If true, any combos that are arranged will be resized to fit their contents. If false, they will not be resized.
"auto" | "equal" | "stretched"
default: 'auto' When name is set to 'sequential', the spacing between nodes at each level.
StackOptions When name is set to 'sequential', stacking options for nodes sharing the same neighbours and level. If property is set in orderBy, stacking is only applied to nodes sharing the same property value.
arrange
required "none" | "grid"
default: 'none' If set to 'grid', four or more same-level nodes with identical neighbours are stacked in a grid.
boolean
default: true By default, links are drawn ignoring off. If false, link offsets are preserved.
number
default: 1 When name is set to 'sequential', the spacing between levels. Values must be positive.
"auto" | "equal"
default: 'equal' The type of spacing between levels in sequential layout. Set to 'auto' if individual levels contain unevenly sized items (nodes or combos) to optimise use of space and get more even distribution of levels.
number
default: 5 Controls how close items are to each other in open combos. Must be in the range 0 to 10, with higher values being closer.
string | string[] When name is set to 'sequential', and level isn't set, specifies the node(s) in the top level of the arrangement. Nodes without top specified are unchanged during the layout but but may be repositioned by packing.
ExpandFilter An object with the filter definition to apply to the chart items before running the layout. This object can have any option passed to the chart.filter() function except animate and time, plus an additional one: filterFn.
function A function which takes an item as its argument, returning true if the item should be visible, false otherwise.
boolean Whether isolated nodes should be hidden, even if the filter criterion passed to chart.filter() function returns true for them. The default is true if type is 'link', false otherwise.
"underlying" | "toplevel"
default: 'underlying' The chart items to iterate over when using combos.
"link" | "all" | "annotation" | "node"
default: 'all' The type of item to show or hide.
boolean
default: true When true, if items are 'underlying', updates combo nodes' glyph text to equal the number of nodes that are visible inside the combo node.
ExpandLayoutOptions An object specifying the layout to apply to the incoming items if there has been a change to the top-level structure of the chart.
boolean
default: true If true, each layout run will produce the same chart display for the same chart structure. If false, the layout will produce different results for a given network on each run. Only used by 'lens', 'organic' and 'standard'.
"linear" | "cubic"
default: 'cubic' The easing function for animation. If set to 'linear', the speed is constant. If set to 'cubic', the animation starts slow, speeds up and then finishes slow.
boolean
default: false Whether to fit the chart into the window at the end of the layout.
"all" | "none" | "adaptive" | "adjacent" | "nonadjacent"
default: 'adaptive' Specifies which nodes to fix in position when the layout is run during chart.expand(). Only used by 'organic' and 'standard'.
boolean
default: false Only applies to 'hierarchy'. If true, the hierarchy will be flattened by removing extra space between levels.
string The name of the custom property on the node's or combo node's d property that defines which level the node/combo belongs to in the 'sequential', 'hierarchy', or 'radial' layouts. The property must contain a numeric value, where the lowest value node is at the top of the 'sequential' or 'hierarchy', or in the centre of the 'radial' layout.
"direct" | "curved" | "angled"
default: 'direct' The shape of the path taken by links.
The direction of 'curved' and 'angled' links is inferred from orientation.
"organic" | "structural" | "lens" | "radial" | "sequential" | "hierarchy" | "standard"
default: 'organic' The name of the layout to apply.
string | object When the layout name is 'sequential', specifies the order of nodes/combos within the same layout level of a connected component in the chart. Any disconnected nodes or combos are ignored.
string The key of the custom data value on the node's d property used to order nodes alphanumerically within each level. When specified, nodes are ordered alphanumerically, in descending order, unless sortBy is also set.
"ascending" | "descending"
default: 'descending' The direction of ordering.
"left" | "right" | "up" | "down"
default: 'down' When name is set to 'sequential' or 'hierarchy', the orientation of the layout.
"none" | "circle" | "rectangle" | "adaptive" | "aligned"
default: 'adaptive' / 'aligned' The packing mode to use for the layout during expand. Not used by 'lens'.
"auto" | "equal" | "stretched"
default: 'auto' The spacing between nodes at each level of the sequential layout.
StackOptions When name is set to 'sequential', stacking options for nodes sharing the same neighbours and level. If property is set in orderBy, stacking is only applied to nodes sharing the same property value.
arrange
required "none" | "grid"
default: 'none' If set to 'grid', four or more same-level nodes with identical neighbours are stacked in a grid.
boolean
default: true By default, links are drawn ignoring off. If false, link offsets are preserved.
number
default: 1 When name is set to 'sequential', the spacing between levels. Values must be positive.
"auto" | "equal"
default: 'equal' The type of spacing between levels in sequential layout. Set to 'auto' if individual levels contain unevenly sized items (nodes or combos) to optimise use of space and get more even distribution of levels.
number
default: 5 Controls how close nodes are to each other. Must be in the range 0 to 10, with higher values being closer.
string | string[] A node id or an array of node ids which should be at the top of the hierarchy and sequential layouts, or in the centre of the radial layout. Components without top specified are unchanged during the layout but can be repositioned by packing. If both the level and top properties are specified, top is ignored.
number
default: 1000 The time the animation should take, in milliseconds.
Returns
Promise
A Promise object.
This function produces images of the chart in raster (PNG, JPEG) or vector (SVG, PDF) format. Raster images can be exported in high-resolution quality by setting the fitTo options to high values.
The exported image is encoded in a blob URL which is passed to the fulfilled promise.
chart.export({
type: 'pdf',
extents: 'chart',
fitTo: 'page',
heading: 'PDF Report',
doc: {
size: 'legal',
layout: 'landscape',
margin: 0.5 * 72, // 0.5 inch margin
},
fonts: {
'Font Awesome 5 Free Regular': { src: '../fonts/fontAwesome5/fa-regular-400.woff' },
Raleway: { src: './fonts/Raleway/Raleway-Regular.ttf' },
},
}).then((exportResult) => {
// do something with the image
});
SVG and PDF export may require embedding font files for fonts, font icons and special characters to display correctly. Unavailable fonts are replaced with ‘sans-serif’ and unavailable font icons are embedded as PNG images. See Font embedding in SVG and Text in PDF for details.
To export into PDF, you need to add external dependencies into your application. See the documentation for PDF Export for details.
The logo, navigation controls and overview window are not exported.
Notes
- We do not recommend running multiple exports in parallel.
- If you reference an image outside the domain of the KeyLines library, your browser will display it, but won’t let KeyLines examine it or render it to a URL. See Cross-Origin Images.
- For PNG and JPEG, the maximum resolution that can be successfully exported is determined by the combination of device/OS/browser and memory available. We do not recommend attempting to export images larger than 100 megapixels.
- Exporting charts on a Leaflet map may exclude items from some custom Leaflet layers, including markers and shadows.
Return Object
Use the returned promise object to detect when the operation has completed. The return object is in the form of { url, warnings }, where:
- url - Contains a blob URL of the exported file. This will be undefined if a custom PDFDocument has been specified in the doc option to allow adding to the document before it is finished.
- warnings - An array containing any warning objects generated during the export.
chart.export({ type: 'svg' }).then(({ url, warnings }) => {
warnings.forEach(warning => { console.log(warning.msg); }); // we can do more with these, e.g. only log a certain type of warning
const snapshotLink = document.createElement('a'); // create the link to download the image
snapshotLink.download = 'chart-export.svg';
snapshotLink.href = url;
snapshotLink.click();
URL.revokeObjectURL(url); // important - remember to revoke the url afterwards to free it from browser memory
});Parameters
- options required
An options object to configure the export.
- by passing any options available for PDFDocument from PDFKit (see examples of options below).
- by passing a custom PDFDocument created by PDFKit.
- 'view': contains only the current on-screen view of the chart, the default aspect ratio is determined by the on-screen view.
- 'chart': contains the whole chart, the default aspect ratio is determined by the whole chart.
- If one dimension is specified, the output is scaled to fit this dimension and keeps the aspect ratio determined by
extents. - If both dimensions are specified, the output is scaled within the dimension limits and if needed, additional content is added to fill the remaining aspect ratio.
- For PDF export only,
fitTocan also be set to 'page' to scale the aspect ratio of the output to fit and fill the available page space.
PDFKit.PDFDocumentOptions or PDFKit.PDFDocument Options to customise the PDF output:
"portrait" | "landscape"
default: 'portrait' The page orientation.
number
default: 72 A single margin in PDF points (72 per inch) to be applied to all page edges.
object
default: { top: 72, right: 72, bottom: 72, left: 72 } An object specifying individual margins in PDF points (72 per inch) to be applied to page edges.
string
default: 'view' Specifies the contents of the exported image:
For a Leaflet map, this option is ignored and KeyLines always generates the on-screen view of the chart.
object or string An object in the form { width: x, height: y } specifying dimensions of the output. One or both values can be specified:
For a Leaflet map, the fitTo option is ignored and the output size always corresponds to the size of the on-screen view. For PDF export of a Leaflet map, if the on-screen view is larger than the size of the generated PDF document, it is scaled down to fit the size of the generated PDF document.
object A dictionary of font files indexed by font name to embed in the output for SVG and PDF export. Accepted formats are URL or base64 encoding of .woff or .ttf font files. See Font embedding in SVG and Text in PDF for details.
fonts: {<br> 'Font Awesome 5 Free Regular': { src: '../fonts/fontAwesome5/fa-regular-400.woff' },<br> Raleway: { src: './fonts/Raleway/Raleway-Regular.ttf' },<br>} string A heading of the exported PDF document. The heading is displayed above the chart image and aligned to its centre. It uses the default PDFKit font (Helvetica) in font size that is proportional to the page size. Note that this option is ignored if a custom PDFDocument has been specified in the doc option.
type
required "jpeg" | "pdf" | "png" | "svg"
default: 'png' The file type of the output.
Returns
Promise
A Promise with the result of the export.
Allows items in the chart to be hidden or shown depending on your own criterion.
// this function filters out nodes with a value <= 10
// including those within combos.
function myFilter(item) {
return (item.d.value > 10);
}
chart.filter(myFilter, { type: 'node' }).then((filterResults) => {
// do more after filter
});
When type is set to 'node', 'link' or 'annotation', the function automatically shows or hides the connected items, so that:
- any nodes that have only hidden links will also be hidden
- any visible links will have nodes at both ends also visible
- any annotations with subjects and subject-relative positioning that have only hidden subjects will also be hidden
- any visible annotations will have their subjects also visible
If the type is 'all', you have fine control over the visibility of all items and the rules above do not apply.
Filtering with Combos
By default, the filter() function includes the contents inside the combos when considering what data should be visible in the chart.
The resolve value for the promise is an object containing a combos property, which describes the visible combos (combo links and combo nodes) which have been altered by the filtering process, as well as the visible items within the combo - i.e., those items that match the filter criteria.
A typical use for this property is to re-size, re-style, or change the glyphs of the visible combos based on their (filtered) contents.
chart.filter(timebar.inRange, {}).then((result) => {
// Resize the combo nodes based on visible items within
const nodeStyles = result.combos.nodes.map((comboInfo) => {
return { id: comboInfo.id, e: Math.sqrt(comboInfo.nodes.length) };
});
return chart.animateProperties(nodeStyles);
});
If the combo itself becomes visible, it will appear in both the shown and combos properties. If the combo itself becomes hidden, it will only appear in the hidden property.
For more details, see the Filtering and foregrounding items section of the Combos Concepts page.
Return Object
Use the returned promise object to detect when the filter operation has completed. The return object describes items altered by the filter function:
- shown items (with nodes/links/annotations properties as arrays of ids)
- hidden items (with nodes/links/annotations properties as arrays of ids)
- shown combos and items in combos (with combo ids and nodes/links properties as arrays of objects)
The form of the object is:
{
shown: { nodes: [...] , links: [...], annotations: [...] },
hidden: { nodes: [...] , links: [...], annotations: [...] }
combos: {
nodes: [{ id: comboId, nodes: [node], links: [link] }]
links: [{ id: comboId, links: [link] }]
}
}Parameters
- filterFn required
-
function A function which takes an item as argument. Returns true if the item should be visible, false otherwise.
Options to control the filtering.
- 'underlying': iterates over items that are not combo nodes or combo links.
- 'toplevel': iterates over items, including combos, that are not inside other combos.
boolean
default: true Whether the filtering operation should be animated.
boolean Whether isolated nodes should be hidden, even if the filter criterion passed to chart.filter() returns true for them. The default is true if type is 'link', false otherwise.
"underlying" | "toplevel"
default: 'underlying' The chart items to iterate over when using combos.
number
default: 1000 The time the animation should take, in milliseconds.
"link" | "all" | "annotation" | "node"
default: 'all' The type of item to show or hide.
boolean
default: true When true, if items is 'underlying', update combo nodes' glyph text to equal the number of nodes that are visible inside the combo node.
Returns
Promise
A Promise that resolves with result of the filter.
Allows nodes and links in the chart to be backgrounded or foregrounded depending on your own criteria.
// this function puts nodes with a value <=10 into the background
// including those inside of combos
function isForeground(item) {
return (item.d.value > 10);
}
chart.foreground(isForeground, {}).then(() => {
// do more after foreground
});
When using the type option 'node' or 'link', the function automatically changes the background state of connected items to keep the chart appearance clean. Backgrounded items are given an alpha value which can be set with the backgroundAlpha option.
At the end of the operation:
- any nodes that have only background links will also be in the background
- any foreground links will have both ends in the foreground
If the type is 'all', you have fine control over the background state of all the items - the rules above are not applied. This line of code will foreground all items in the chart:
chart.foreground((node) => true );
Return Object
Use the returned promise to detect when the foreground operation has completed. The return object describes exactly which items were put into the foreground or background and has the form:
{
foreground: { nodes: [...] , links: [...] },
background: { nodes: [...] , links: [...] }
}
For foreground or background objects, the nodes / links properties are arrays of ids.
For details on how to use foregrounding with combos, see the Filtering and foregrounding items and the Foregrounding open combos sections in Combos Concepts.
Parameters
- foregroundFn required
-
function A function which takes an item as its argument, returning false if the item should be in the background, true otherwise.
Options to control the foreground operation.
- 'underlying': iterates over items that are not combo nodes or combo links.
- 'toplevel': iterates over items, including combos, that are not inside other combos.
boolean
default: true Whether open combos should be foregrounded. Set to false to put all open combos in the background. When set to false, manually opening/closing any combo overrides the option and foregrounds all combos. When opening/closing programmatically using chart.combo().open() / chart.combo().close(), the option remains set.
"underlying" | "toplevel"
default: 'underlying' The chart items to iterate over when using combos.
"link" | "all" | "node"
default: 'node' The type of item to foreground/background.
Returns
Promise
A Promise that resolves with result of the foreground.
Returns aggregation information associated with the specified link(s).
Parameters
Returns
AggregateInfo | null | (AggregateInfo | null)[]
An object containing the aggregation information associated with each specified link, or null if there is no link matching the id.
aggregateByProp
required undefined | string If an aggregate link: the key of the custom data on the child link's d property being used for aggregation.
aggregateByValue
required any If an aggregate link: the value of the custom data specified by aggregateByProp. All its child links have the same value of the property.
aggregateChildren
required undefined | string[] If an aggregate link: its child links.
aggregateDirection
required undefined | "both" | "none" | "from" | "to" If an aggregate link: the direction in which its child links are aggregated:
- 'from': direction arrow points from id1 to id2
- 'to': direction arrow points from id2 to id1
- 'both': direction arrows in both directions
- 'none': link aggregation is not based on direction
isAggregate
required boolean Whether the specified link is an aggregate link.
parentAggregate
required undefined | string If the link is a child of an aggregate, specifies its parent link.
Returns a copy of the items in the chart which match the id.
Note:To update the items, use setProperties().
Parameters
- id required
-
string | string[] The id string or the array of id strings of the items to be retrieved.
Returns
Node | Link | Annotation | null | (Node | Link | Annotation | null)[]
The item or array of items matched. Returns null if there is no item matching an id.
Returns information on the item at the specified view coordinates.
Note: This function is intended for use in integration tests. For fetching items from the chart, use getItem().
Parameters
Returns
object
An object describing the id and subItem of the item at the specified coordinates.
Returns the position of the annotation relative to its subjects. Can be useful e.g. when converting world-positioned annotations to subject-relative annotations.
Parameters
Returns
object | null
The annotation position relative to its subjects as an object with angle and distance properties. Returns null if annotation is not found or if it has no subjects.
Returns the position of the annotation in world coordinates. Can be useful e.g. when converting subject-relative annotations to world-positioned annotations.
Parameters
Returns
object | null
The annotation position in world coordinates as an object with x and y properties, or null if not found.
The graph object has methods for navigating the top level of your chart.
See KeyLines.getGraphEngine() to consider the underlying level of the chart.
Returns
Graph
The graph representation of the chart.
Hides item or items with the id(s) specified.
Hiding nodes automatically hides any links that are connected only to the hidden nodes.
Hiding a combo node will hide all its child items.
Hidden links will not be considered when running a layout.
If all annotation subjects (nodes, links and combos) are hidden and the annotation has subject-relative positioning, the annotation is also hidden.
To show items, call the show() function.
Parameters
Options to control the hide operation.
Returns
Promise
A Promise.
Returns information about the label of the item with the specified id. Can be useful e.g. when overlaying text edit boxes over the chart surface. Does not return the label position for t1 or t2 labels on link ends.
Parameters
-
number If the item is styled by an array of label objects, represents the index of the specific label object.
Returns
object | null
An object containing label coordinate properties, or null if the items are hidden or don't exist. The coordinates are in view coordinates relative to the top left corner of the KeyLines HTML element.
{
x1: valueX1, // left
x2: valueX2, // right
y1: valueY1, // top
y2: valueY2, // bottom
fs: value // font size at current zoom
}The layout function positions the nodes of the chart.
The layouts are:
- 'organic': The default force-directed layout offering excellent performance and results for any type or size of data.
- 'sequential': lays out tree-like data in a traditional hierarchy structure, minimising crossed links.
- 'hierarchy': a simpler tree-like layout.
- 'lens': places the node in a circle-like grid, with connected nodes next to each other.
- 'radial': places nodes in concentric circles.
- 'structural': places nodes which are structurally similar together in the network.
- Deprecated'standard': a force-directed graph layout which tries to keep link lengths consistent.
For more detail on our layouts, see Layout Basics.
Options can be passed in the second argument. For example:
chart.layout('organic', {
mode: 'adaptive',
animate: false
}).then(() => {
// do more after layout
});
The layout is not performed on a Leaflet map.
Hidden items do not change their positions and are not considered by the layout function. When re-showing hidden items consider running a layout to ensure the chart looks good afterwards.
If you are using combos, be aware that layouts only consider nodes that are on the top-level of the chart. For more detail on chart levels, see Combos Concepts.
Return Object
The layout call is asynchronous - the function will return before the layout has completed. To discover the progress of the layout use the progress event. Use a promisified function to detect when the layout has finished.
The arrange() function is an alternative way to position nodes. It places nodes in close proximity into a specified shape.
Parameters
-
"organic" | "sequential" | "hierarchy" | "lens" | "radial" | "structural" | "standard" The name of the layout to be invoked. The default is 'organic'.
Options to control features of the layout.
- 'radial' and 'hierarchy' must have either
levelortopspecified. - 'sequential' assigns levels automatically if neither property are specified (inferred from the nodes' links).
- If both the
levelandtopproperties are specified,levelis used. - 'direct' - links are either straight or follow arcs when offset.
- 'curved' - link follow a curved path, and attach to nodes in the direction of
orientation. - 'angled' - links follow straight lines with corners: useful for hierarchical data sets. Currently in beta.
- 'adaptive': components only move to make space for new items or to use space created by removed items.
- 'aligned': only for sequential, default option. Components are laid out in a single line with same level items aligned. If
topis used, any components withouttopspecified are packed using 'rectangle' packing. - 'circle': components are treated as circles, giving a roughly circular result.
- 'rectangle': components are treated as rectangles, giving a grid-like result.
- 'none': components are not packed.
- ‘auto’: node spacing reduces link lengths and connected components are nested together to make the most of screen space.
- ‘equal’: regular node positions with equal spacing within each connected component and a clear separation between them.
- ‘stretched’: as for ‘equal’ but each level is stretched to take up an equal amount of screen space.
- 'radial' and 'hierarchy' must have either
levelortopspecified. - 'sequential' assigns levels automatically if neither are specified (inferred from the nodes' links).
boolean
default: true Whether the result should be animated.
boolean
default: false If set to true, each layout run will produce the same chart display for the same chart structure. The position of nodes in the chart may change during the layout, but their position in relation to other nodes will remain the same. If false, the layout will produce different results for a given network on each run. Only used by 'lens', 'organic', 'structural' and 'standard'.
"linear" | "cubic"
default: 'cubic' The easing function for animation. If set to 'linear', the speed is constant. If set to 'cubic', the animation starts slow, speeds up and then finishes slow.
boolean
default: true Whether to fit the chart into the window at the end of the layout.
string[] An array of node ids whose positions are fixed relative to the other nodes in the same component. Their position on the chart may change during the layout, but their position in relation to the component's other nodes will remain the same. Only used by 'organic' and 'standard'.
boolean
default: false Only used on 'hierarchy' layout. If true, the hierarchy will be flattened by removing extra space between levels.
string The name of the custom property on the node's or combo node's d property that defines which level the node/combo belongs to in the 'sequential', 'hierarchy', or 'radial' layouts. The property must contain a numeric value, where the lowest value node is at the top of the 'sequential' or 'hierarchy', or in the centre of the 'radial' layout.
"direct" | "curved" | "angled"
default: 'direct' The shape of the path taken by links.
The direction of 'curved' and 'angled' links is inferred from orientation.
"full" | "adaptive"
default: 'full' Specifies whether the layout is run in full or as a short force-directed layout that slightly adapts item positions to data changes. Available for 'organic', 'sequential' and 'standard' layouts.
string | object When the layout name is 'sequential', specifies the order of nodes/combos within the same layout level of a connected component in the chart. Any disconnected nodes or combos are ignored.
string The key of the custom data value on the node's d property used to order nodes alphanumerically within each level. When specified, nodes are ordered alphanumerically, in descending order, unless sortBy is also set.
"ascending" | "descending"
default: 'descending' The direction of ordering.
"left" | "right" | "up" | "down"
default: 'down' When name is set to 'sequential' or 'hierarchy', the orientation of the layout.
"none" | "circle" | "rectangle" | "adaptive" | "aligned"
default: 'circle' / 'aligned' The packing mode to use for the layout. Not used by 'lens'.
"auto" | "equal" | "stretched"
default: 'auto' The spacing between nodes at each level of the sequential layout.
StackOptions When name is set to 'sequential', stacking options for nodes sharing the same neighbours and level. If property is set in orderBy, stacking is only applied to nodes sharing the same property value.
arrange
required "none" | "grid"
default: 'none' If set to 'grid', four or more same-level nodes with identical neighbours are stacked in a grid.
boolean
default: true By default, links are drawn ignoring off. If false, link offsets are preserved.
number
default: 1 When name is set to 'sequential', the spacing between levels. Values must be positive.
"auto" | "equal"
default: 'equal' The type of spacing between levels in sequential layout. Set to 'auto' if individual levels contain unevenly sized items (nodes or combos) to optimise use of space and get more even distribution of levels.
number
default: 5 Controls how close nodes are to each other. Must be in the range 0 to 10, with higher values being closer.
number
default: 700 If animated, the time the animation should take, in milliseconds.
string | string[] A node id or an array of node ids which should be at the top of the hierarchy and sequential layouts, or in the centre of the radial layout. Components without top specified are unchanged during the layout but can be repositioned by packing. If both the level and top properties are specified, top is ignored.
Returns
Promise
A Promise.
Replaces the chart data with the new specified data and dereferences any existing objects in the chart.
Note that the data argument is a JavaScript Object, not a JSON string. It should have the properties specified for the relevant Item Format.
const data = { type: 'LinkChart', items: [
{ id: 'node1', type: 'node', t: 'Node 1' },
{ id: 'node2', type: 'node', t: 'Node 2' },
{ id: 'link', type: 'link', t: 'Link', id1: 'node1', id2: 'node2' },
{ id: 'annotation', type: 'annotation', subject: 'node1', t: { t: 'Annotation' } },
]};<br/>chart.load(data).then(() => {
// do something else
});
If there are multiple links between two nodes, load() will automatically apply an offset to the links.
You can set the parentId of new nodes to add them into a combo. See Combos for more details.
When using Leaflet Integration, call load() before displaying the Leaflet map. See Special behaviour for more details.
Returns
Promise
A Promise.
Locks and unlocks the chart. When the chart is locked, end-user interactions using mouse, keyboard and touch cannot alter the state of the chart.
Note that the API can continue to modify the chart while it is locked.
To determine the current state of the chart, call lock() with no arguments.
Parameters
Options to control the chart's behaviour while locked.
boolean Whether to show a 'wait' cursor while the chart is locked.
Returns
boolean
True if the chart is locked, false otherwise.
The map namespace has methods for displaying the chart on a Leaflet map. See Map Functions.
Returns
Map
The map namespace object.
Adds new items to the chart, or modifies the properties of existing items. Properties of any items matched will be replaced with the new item properties.
Merging does not lay out the chart - if you want the chart to be laid out afterwards, call chart.layout() once the promise is resolved.
const newItems = [
{ id: 'newNode', type: 'node' },
{ id: 'newLink', type: 'link', id1: 'newNode', id2: 'existingNode' }, // new link connecting a new node with existing one
{ id: 'newAnnotation', type: 'annotation', subject: 'existingNode' }, // new annotation added on an existing node
];<br>chart.merge(newItems).then(() => {
// do something else
});
You can set the parentId of new items to add them into a combo, but cannot change the parentId of pre-existing items. See Combos for more detail.
If there are multiple links between two nodes, merging will automatically apply an offset to the links. Note that you cannot change the ends of an existing link.
Parameters
- items required
-
ChartData | Node | Link | Annotation | (Node | Link | Annotation)[] To be added or modified in the chart, a choice of either:
- KeyLines chart object.
- A single item.
- An array of items.
Returns
Promise
A Promise.
Detaches an event handler function for one or more events attached to the chart using the on() function.
chart.off('progress', progressEventHandler);
If no handler is supplied, all handlers for the specified event are detached. If no event name is supplied, all event handlers for all events are detached.
Parameters
-
Chart Event The name of the event to be detached from, e.g., 'click'. Use 'all' to detach from all events.
Returns
void
Attaches an event handler function for one or more Chart Events to the chart.
function progressEventHandler(task, progress) {
// use progress to set progress bar value
}
chart.on('progress', progressEventHandler);
To detach event handlers, use off().
See Events Basics for more details.
Parameters
- name required
-
Chart Event The name of the event to listen for, e.g., 'click'. Use 'all' to listen to all events.
Returns
void
Sets or gets the current display and interaction options. See Chart Options.
Note that using this promisified function as a getter still returns an object in a synchronous way. See Special Cases: getters and setters for more detail.
chart.options({ minZoom: 0.01 });Parameters
Returns
object | Promise
Getter: The current options.
Setter: A Promise object.
Pans the chart in the direction specified.
Parameters
- direction required
-
"left" | "right" | "up" | "down" | "selection" Controls how to pan the chart:
- 'up' / 'down' / 'left' / 'right' - Pans the chart as specified.
- 'selection' - Pans the centre of the viewport to the centre of the selected items.
Options to control the pan operation.
Returns
Promise
A Promise.
Adds an animated effect to a specified node or link, and then removes it again. To animate nodes and links in other ways, use the animateProperties() function.
Ping and nodes
The function adds a halo to nodes. Animation expands the halo's radius and width to specified values while decreasing the alpha value of its specified colour, giving a fade effect.
Ping does not affect the ha0-9 properties used for displaying other halos on nodes.
Ping and links
The function adds an animated effect on links that's similar to halos on nodes. The animation expands from the outline of the link to a specified width while decreasing the alpha value of its specified colour, giving a fade effect. Note that you cannot apply halo properties to links.
Ping items in combos
If an item is in a closed combo when it is pinged, the ping appears on the closed combo.
Parameters
Options to control the animation.
number
default: 40 The maximum width of the links' animated effect.
number
default: 80 The radius of the nodes' halo at the end of the animation.
number
default: 1 The number of times the animation should be repeated.
number
default: 800 The time the animation should take, in milliseconds.
number
default: 20 The width of the nodes' halo at the end of the animation.
Returns
Promise
A Promise.
Removes item or items with the id(s) specified. Note that there is no event to detect items being removed from the chart.
Parameters
Returns
void
Sets or gets the current chart selection as an array of ids. Selected items are drawn on top of non selected ones. Any link whose end is selected will also be drawn on top.
Note that hidden items cannot be selected.
Parameters
Returns
string[]
The current selection as a list of item ids.
Returns a complete serialization of the current chart content in the form specified by the object properties section.
The serialized chart can be loaded back in by using the chart.load function. This can be used for saving the chart state in a database or for implementing features like undo or redo.
You can also load in serialized data with merge() or expand(), but be aware that when merging data with combos, only the underlying items will be loaded, and not combos or combo links. See Combos Concepts for more detail.
Calling chart.serialize() during animations, or when transitioning to and from a Leaflet map, may cause transient node positions to be saved into the serialized data.
Note: We do not recommend parsing the results of chart.serialize as a way to get items from the chart. Instead, use chart.each to iterate over items and return an array.
Returns
object
The representation of the chart state in the form of a KeyLines chart object.
Sets the location of the chart in the DOM. Pass null as the argument to hide it completely.
Things to note:
- You must specify the container parameter in
KeyLines.create()to usesetContainer(). - While the container is set to null, all drawing and animations are paused, and you cannot transition to and from a Leaflet map.
chart.setContainer('chartContainer');Parameters
-
null | string | HTMLElement The id string or DOM element of the parent container that the chart should be appended to.
Returns
void
Creates a new item in the chart with the specified properties. The item should have the properties specified in Item Format, and must include all the desired properties of the new item including its type, either 'node' or 'link'. If there is an existing item in the chart with the same id, it is replaced and none of its properties are retained.
chart.setItem({ id: 'node1', type: 'node', c: 'blue', t: 'new label' }).then(() => {
// do something else
});
Note that if the new item is a link, both of its end nodes must already be present in the chart. It is not possible to add links without ends, and you cannot change the ends of an existing link.
You can set the parentId of a new item to add it into a combo, but cannot change the parentId of a pre-existing item. See Combos for more detail.
To change some of the properties of an existing item without replacing it, use setProperties().
Note: Using setItem to add an additional link doesn't apply the automatic offset to the link. Use merge() if you want this.
Returns
Promise
A Promise.
Changes properties of items in the chart.
Use it to change properties of multiple items in a single call - see Data Manipulation for more details.
Accepts a single item object (or an array of items) in the form {id: id, propertyName1: value1, propertyName2: value2 }. Items with a matching id will take the new values.
Setting useRegEx = true treats the ids passed in as regular expressions. This is useful for global settings, for example to set the font size across the whole chart:
chart.setProperties({ id: '.', fs: 8 }, true);
Regular expressions are always evaluated with the 'i' (case-insensitive) and 'm' (multiline) modifiers set, and ids should be passed as strings (not regular expression objects).
Note that the new value will completely replace the previous one, even for Glyphs, Font Icons or properties for other item formats where the value is an object or an array.
If you want to update or merge object or array properties, the recommended way is to get the current value, modify it and set it back. For example:
const item = chart.getItem('item-id');
// now add a new property to the current one
const data = item.d;
data.myNewProperty = 'new value';
// and update the chart
chart.setProperties({ id: item.id, d: data });
When changing properties in the top level object, you only need to specify the properties that you want to change. When changing properties in the nested object, you need to specify both changing and unchanged properties:
// changing top level properties of a link
chart.setProperties({ id: 'link1', fbc:'orange', t: 'link', t1: 'endLabel1', t2: 'endLabel2', });
// changing the nested fbc property for t1 and t2 requires repeating the t properties as well
chart.setProperties([{ id: 'link1', t1: { t: 'endLabel1', fbc:'red' }, t2: { t: 'endLabel2', fbc:'green' } }]);
Notes:
- You cannot change the ends of an existing link.
- Setting hi to true to hide a combo node also hides the items inside. For more details, see the Hiding and showing items section in Combos Concepts.
Parameters
- items required
-
Node | Link | Annotation | (Node | Link | Annotation)[] The ids of items to be changed and the properties to be changed.
-
boolean Whether the ids are to be treated as regular expression strings. The default is false.
Returns
Promise
A Promise.
Shows (unhides) the items specified by the id parameter.
Calling show() on a combo will also show the items inside it. Calling show() on an item inside a hidden combo or a nest of combos will show that item and its parent(s).
Hiding nodes with chart.hide() or chart.filter() automatically hides their links, but calling show() to unhide the nodes does not automatically reinstate the hidden links. To do that for the nodes specified in the id parameter, set showLinks to true.
Hiding all annotation subjects using chart.filter() automatically hides their subject-relative positioned annotations, but calling show() to unhide at least one subject does not automatically reinstate the hidden annotations. To do that for the subjects specified in the id parameter, set showAnnotations to true.
Parameters
Options to control the show operation.
boolean
default: false Whether the transition should be animated.
If true, any hidden annotations attached to subjects that become shown will also be shown.
boolean
default: false If true, any hidden links to nodes that become shown will also be shown.
number
default: 1000 The length of the animation in milliseconds.
Returns
Promise
A Promise.
This function is deprecated. Use the chart.export() function which supports more output types.
Returns a data URL of the chart image as the first argument of the fulfilled promise: a base64 encoded PNG image string will be passed to the fulfilled promise.
chart.toDataURL(300, 200, {}).then((dataURL) => {
// do something with the image
});
The navigation controls and overview window are not drawn into the image.
If you reference an image that's on a different domain to the KeyLines library, your browser will display it, but won’t let KeyLines examine it or render it to a data URL. For details on how to fix this, see Cross-Origin Images (CORS).
toDataURL behaves slightly differently for charts on a Leaflet map:
- Only the current visible viewport will be captured in the data URL, which means the width, height and options.fit parameters will be ignored.
- Some layers within the Leaflet map, including markers and shadows, will not be included in the data URL.
Parameters
-
number The width of the required image in pixels. The default is the width of the chart element. Not supported for a Leaflet map.
-
number The height of the required image in pixels. The default is the height of the chart element. Not supported for a Leaflet map.
Options to control how the image is created.
"exact" | "view" | "chart" | "oneToOne"
default: 'exact' How the current view settings are mapped when generating the image. Note that for a Leaflet map, the only available fit mode is 'exact'.
boolean
default: true Whether the chart background gradient (if present) should be drawn.
boolean
default: true Whether the logo (if present) should be drawn.
boolean
default: false If true, the image is drawn as if it were a new component at 1-1 scale. This means that any logo or watermark will be drawn at 1-1 in the image. If false, the logo and watermark are sized to fit the image size.
boolean
default: false Whether the current selection (if present) should be drawn as selected in the image.
boolean
default: true Whether the watermark (if present) should be drawn.
Returns
Promise
A Promise that resolves to a base64 encoded PNG image string.
Converts world coordinates (positions of items within the chart) to screen coordinates in the current view. This depends on the current view settings (zoom and pan). View coordinates are relative to the top left corner of the chart.
Parameters
Returns
object
An object containing the view coordinates.
Sets or gets the current chart view options, which covers the zoom setting and viewport location.
For a Leaflet map, view options must be set through the Leaflet API.
Note that using this promisified function as a getter still returns an object in a synchronous way. See Special Cases: getters and setters for more detail.
Parameters
- options required
Controls the view options.
Options to control the transition between view states.
height
required number The height of the view (read only).
offsetX
required number
default: 0 The view offset in the X direction measured in pixels.
offsetY
required number
default: 0 The view offset in the Y direction measured in pixels.
width
required number The width of the view (read only).
zoom
required number
default: 1 The level of zoom. 1 is 1-to-1, which means that item sizes match the canvas pixel size. Note that you cannot use the zoom option on a Leaflet map. For details on controlling zoom on a Leaflet map, see the Leaflet Integration documentation.
Returns
object | Promise
Getter: The current view options.
Setter: A Promise object.
Converts screen coordinates (in the current view) to the coordinates which are used to represent the position of items within the chart. This depends on the current view settings (zoom and pan).
Parameters
Returns
object
An object containing the world coordinates.
Zooms the chart in the manner specified.
Parameters
- how required
-
"height" | "one" | "selection" | "fit" | "in" | "out" Controls how to zoom the chart:
- 'in' / 'out' - Zooms the chart in/out as specified.
- 'one'- Zooms the chart in/out so that node sizes match the canvas pixel size. Equal to
chart.viewOptions({ zoom: 1 }). - 'fit'- Fits the chart or the specified ids to window.
- 'height' - Fits the height of the chart or of the specified ids to window.
- 'selection' - Fits the selected items to window.
Options to control the zoom operation.
boolean
default: false Whether the transition should be animated.
string | string[] The id or array of ids to zoom to in 'fit' or 'height' mode. If no ids are specified 'fit' will fit the chart to the window. 'height' will fit the chart height to the window.
number
default: 1000 The length of the animation in milliseconds. Cannot be set for a Leaflet map. See Special behaviour for more information.
Returns
Promise
A Promise.