Here you’ll find reference documentation for every JavaScript object, function, event and option in the KeyLines API. You’ll see tags and buttons attached to items:
Alpha Beta | This gives you the status of the latest features we’ve added to KeyLines. The tags link to Alpha/Beta Features. |
async | This is an asynchronous function, meaning it doesn't return a result directly to the caller. The tag links to more details about Asynchronous JavaScript. |
chart | Tags like this remind you which namespace a method, object or event belongs to. |
deprecated | We intend to end support for this item in future, and recommend that you stop using it now. The tag links to the list of current Deprecations. |
getter/setter | This tag tells you when a function is both a getter and setter. |
| graph engine only | This method is only available in the Graph Engine and is separate from the methods used to render charts. The tag links to more details about the Graph Engine. |
required | This property is mandatory. For example, |
KeyLines uses JavaScript objects for defining visual appearances.
The chart object lets you load JSON data into the chart. In this example, only the type, id, id1, id2 and subject properties are required:
let data = {
type: 'LinkChart', // this must be exactly this string
items: [
{
id: 'node1', // the identity of the node
type: 'node', // the type of the item: must be 'node'
c: 'blue' // the fill colour (optional)
},
{
id: 'node2', // the identity of the node
type: 'node', // the type of the item: must be 'node'
c: 'blue' // the fill colour (optional)
},
{
id: 'link1-2', // the identity of the link
id1: 'node1', // the identity of the node at one end
id2: 'node2', // the identity of the node at the other end
type: 'link', // the type of the item: must be 'link'
c: 'rgb(216, 30, 91)' // the link colour (optional)
},
{
id: 'annotation1', // the identity of the annotation
subject: 'node1', // the identity of the annotated item
type: 'annotation', // the type of the item: must be 'annotation'
t: { t: 'Annotation Label' }, // the annotation text (optional)
}
]
};Nodes are the basic objects that you use to build a graph.
By default, nodes don't have a defined body unless their background is specified. To create a defined body, set a background fill colour (c), a font icon (fi), or a background image (u).
let data = {
type: 'LinkChart',
items: [
{
id: 'node1',
type: 'node',
c: '#43976C',
},
],
};
Either font icons or images can also be used alongside a background fill colour as a top layer over the coloured node.
You can set the properties of nodes using setProperties.
topLeft or bottomRight.sh (shape) property set to 'circle'. If both donut and b are set then donut takes precedence.w and h specified.fontFamily setting of chart.options().e property.w: the height of the node in world coordinates. Set to 'auto' to fit the node height to any number or length of labels inside.ha0, ha1, ha2, etc., up to ha9.topLeft or bottomRight.For more details about label styling see the Advanced combo styling documentation.
chart.combo().transfer() to change it.legacyShapeNodeBehaviour is enabled.h and w, to create a scalable square node. Defaults to 'box' for nodes with h and w specified.For more details about label styling see the Advanced label styling documentation.
w and h node properties in proportion to the aspect ratio of the image.h: the width of the node in world coordinates. Set to 'auto' to fit the node width to any number or length of labels inside.In KeyLines, connections between nodes are called links. Links represent connections in your data and are used to show network structure. You can set the properties of links using setProperties.
id1 as a ratio of the total length of the link line. Value in the range 0 to 1.id2 as a ratio of the total length of the link line. Value in the range 0 to 1.The border around the link label. If set for multiline labels, merges all labels into a single label container.
topLeft or bottomRight.c at the id1 end and colour c2 at the id2 end. The transition setting of linkStyle controls the gradient's appearance.fontFamily setting of chart.options().ls property).g property within t1 or t2.name is set to 'angled' or 'curved', the direction in which the link attaches to its nodes.Overrides automatic calculation of link offsets, so can be used to force direct links to follow an arc. Increasing off increases the distance between the midpoint of the link and the straight line joining its ends. If off is set for any link in a set of links between two nodes, then it defaults to 0 for any other links in that set.
Note: When chart.layout runs with default settings, off is overriden because straighten is true. To prevent this, and preserve specified offsets, set straighten to false.
Similarly, when chart.combo().arrange() runs with default settings, off is overriden because straighten is true. To prevent this, and preserve specified offsets, set it to false.
For self links, this option specifies how far the link is offset from its default position close to the node.
border set, applies to the whole label container.parentIds for links are calculated automatically and cannot be set.id1 end. For multiline labels, use '\n' or '\r' to force a line break. String values inherit styling from the label at the link's centre.t1 / t2
inherit the styling in the border object, any unspecified values will be set to defaults.fb setting.border set, applies to the whole label container.id2 end. For multiline labels, use '\n' or '\r' to force a line break. String values inherit styling from the label at the link's centre.id1 to create a "self link" if the selfLinks chart option is enabled.Annotations are notes that can annotate the chart or the items in the chart. You can annotate nodes, links, open and closed combos, and create free-standing annotations without any subjects.
See also the Annotations documentation for more information.
Annotations are added as special type of chart item in the
items array. The subject
array is set differently for annotations with and without subjects:
let data = {
type: 'LinkChart',
items: [
{
id: 'annotation1',
type: 'annotation',
subject: 'node1', // node1 is annotation subject
t: { t: 'This is an annotation of node 1.' },
connectorStyle: { container: 'rectangle' }
},
{
id: 'annotation2',
type: 'annotation',
t: { t: 'This is an annotation without subject.' },
subject: [], // an empty array indicates no subjects
position: { x: 350, y: -50 }, // no-subject annotation requires coordinate positioning
},
{
id: 'node1',
type: 'node',
c: 'rgb(45,105,160)',
},
]
};Annotations are drawn in a separate layer on top of the chart and they do not scale during zooming.
There are two ways of positioning annotations:
Annotations with subjects are displayed if at least one of the annotated items is visible in the chart, or if none of the subjects are visible but the annotation uses world coordinates for positioning.
Annotations without subjects must use world coordinates for positioning
and require the subject array to be set to an empty array.
Notes:
topLeft or bottomRight.subjectEnd option for any annotations.container option for node and combo annotations.h and w need to be set.Labels show information on nodes. They can contain text, font icons or images.
A basic label is a text string set directly in the t property such as t: 'label 1',
but the t property also accepts an object that lets you further customise the label styling:
t:
{
t: 'Label',
b: 'rgb(45,105,160)'
}
or an array of objects that lets you add multiple labels and customise styling for each label:
let data = {
type: 'LinkChart',
items: [{
id: 'node1',
type: 'node',
c: 'rgb(45,105,160)',
t: [
{
fi: { t: 'fas fa-exclamation-circle' },
fc: 'rgb(216, 30, 91)',
fbc: 'transparent',
position: 'ne',
},
{
t: 'node label',
borderRadius: 5,
position: 's',
fbc: 'rgb(122,193,226)',
},
{
u: '/images/icons/pearlgirl.jpg',
position: { horizontal: 'centre'},
},
],
}]};
For more details, see Advanced label styling.
Closed combos accept the same node label API as nodes and have the same defaults.
Open combos accept the same node label API, but their default label position is outside and below the combo to avoid overlapping the combo content. For more details, see Advanced combo styling.
topLeft or bottomRight.fbc, if it's set. Ignored if u is set.fc, if it's set.ff if set, or from the fontFamily setting of chart.options().position and margin, and scale it using fs.
If both fi and t are specified, only fi is shown. fi is ignored if u is also specified.fs is set to 'auto'.maxWidth also set.textWrap is set to 'normal', or set the maximum text width when fs is set to 'auto'.maxHeight also set.u is set.minWidth when textWrap is set to 'normal' to increase the minimum text width before a line break. Ignored if u is set.horizontal and/or vertical properties
places labels inside the node/combo.
t: [
// label 1 has no vertical position, set label 2 to 'inherit' to place it inline
{ t: 'label 1' },
{ t: 'label 2', position: { vertical: 'inherit' } },
]
Similarly, setting two labels to the same vertical position will also put them on the same line:
t: [
// set label 2 to the same vertical position as label 1 to place it inline
{ t: 'label 1', position: { vertical: 'bottom' } },
{ t: 'label 2', position: { vertical: 'bottom' } },
]minWidth / maxWidth, or the '\n' or '\r' characters.
To set a fixed width for a wrapped label, set both minWidth and maxWidth to the same value.maxHeight and maxWidth. See Image labels for more details. Labels show information on annotations. The information can be in a format of text, font icons or images.
The t property for annotations
accepts an object to add a single styled label,
or an array of objects to add multiple styled labels.
let data = {
type: 'LinkChart',
items: [
{
id: 'annotation1',
type: 'annotation',
subject: 'node1',
t: [
{
fi: { t: 'fas fa-exclamation-circle' }, // coloured font icon label
fc: 'rgb(216, 30, 91)',
},
{
t: 'Annotation Label', // text label positioned vertically inline to the font icon
position: { vertical: 'inherit' },
},
],
},
{
id: 'node1', // node1 is the annotation subject
type: 'node',
c: 'rgb(45,105,160)',
},
],
};
For more information about annotation labels, which behave just like regular node labels, see also Advanced label styling docs.
topLeft or bottomRight.fontFamily setting of chart.options().w) and/or height (h) is also 'auto'.fs is set to 'auto' to set the maximum height of the text.maxWidth when textWrap is set to 'normal' to reduce the maximum text width before a line break, or when fs is set to 'auto' to set the maximum text width.minWidth when textWrap is set to 'normal' to increase the minimum text width before a line break.horizontal and/or vertical properties.
Places labels inside the annotation. Note that if used with negative values to place the labels outside, the connector line will not avoid the labels. { horizontal: 'centre', vertical: 'middle' }.
See also Label positioning for details.minWidth / maxWidth, or the '\n' or '\r' characters.
To set a fixed width for a wrapped label, set both minWidth and maxWidth to the same value.Bubbles are sub-items that can be used to add additional text to nodes or links. You can only show one bubble per item.
Bubbles can be shown in one of four positions:
Bubbles are added to items as follows:
let data = {
type: 'LinkChart',
items: [
{
id: 'node1', t: 'label', type: 'node', u: 'person.png', x: 100, y: 150,
bu: {
c: 'rgb(255, 0, 0)', // the bubble fill colour
p: 'ne', // bubble in NE position. use 'se', 'sw', 'nw' for the other positions
t: 'Bubble' // the bubble text
}
}
]
};fontFamily setting of chart.options().Glyphs are sub-items displayed on nodes, links, annotations or combos to convey additional information such as a status or a counter.
A glyph can be a simple coloured circle, and/or show a font icon, an image or a text. If multiple types are set in the same glyph object, only one is shown in this order:
t (highest priority) ufic (lowest priority)To move icons and images inside glyphs from their default positions, use the imageAlignment option.
Glyphs are drawn along a border of the annotation or node (incl. closed combo node). They are added as an array of objects to the g
property.
There are two styles of positioning:
Glyphs on a single node or annotation must use the same positioning method (i.e., all use compass points or all use angles). In an array, glyphs are only drawn if they use the same positioning method as the first glyph.
You can have as many glyphs as you like, but only one glyph is allowed in each position. If multiple glyphs are set in one position, only the first one is drawn.
let data = {
type: 'LinkChart',
items: [
{
id: 'node1',
type: 'node',
c: '#43976C',
t: 'node label',
g: [{
p: 'ne', // north-east corner position, position required for nodes
c: 'red', // fill colour required for text to show
t: '!', // the glyph text
border: { colour: 'orange' }, // the border around the glyph
}],
},
{
id: 'annotation1',
type: 'annotation',
subject: 'node1',
t: { t: 'annotation label' },
g: [{
p: 'ne',
c: 'blue',
t: '!'
}],
},
]};
Links can have any number of glyphs that can be added either in the centre
or at the link ends (t1 and t2).
Glyphs are added as an array of objects to the g property:
let data = {
type: 'LinkChart',
items: [
{ id: 'n1', type: 'node', c: '#43976C' },
{ id: 'n2', type: 'node', c: '#43976C' },
{
id: 'link1',
type: 'link',
id1: 'n1',
id2: 'n2',
t: 'link label',
g: [
{ c: 'red', t: '!' }, // array of glyphs in the link centre,
{ c: 'orange', t: '!' }, // shown left to right
],
t1: {
g: [
{ c: 'blue', t: '!' } // array of glyphs at the left link end, shown left to right
],
},
}]};Glyphs are drawn along an open combo's border. Depending on how the combo was created,
glyphs are added as an array of objects to the g
property of the openStyle property or the
oc property.
The positioning of glyphs on open combos is the same as the positioning of glyphs on nodes, which means that either compass points (e.g. 'n', 'e', 'se') or integers (in the range 0-359) can be used.
Glyphs on a single open combo must use the same style of positioning (i.e., all use compass points or all use angles). In an array, glyphs are only drawn if they use the same positioning method as the first glyph.
You can have as many glyphs as you like, but only one glyph is allowed in each position. If multiple glyphs are set in one position, only the first one is drawn.
Note: The r property is not supported for glyphs on open combos.
let data = {
type: 'LinkChart',
items: [
{
id: 'newcombo1',
type: 'node',
c: 'blue',
oc: {
g: [{
p: 'nw', // north-west corner position, position required for combos
c: 'rgb(255, 0, 0)', // fill colour required for text to show
t: '!', // the glyph text
border: { // the border around the glyph
colour: 'green',
width: 4,
},
}],
},
},
{ id: 'newchild1', parentId: 'newcombo1', type: 'node', c: 'red' },
{ id: 'newchild2', parentId: 'newcombo1', type: 'node', c: 'red' },
],
};fontFamily setting of chart.options().w is set to false) show a maximum of four characters.
Wide glyphs (where w is set to true) show a maximum of 25 characters.Font icons are vector-based glyphs embedded in font files, where specific character codes are mapped to icons.
In KeyLines, font icons can be used as node icons, glyph icons (on nodes, links, annotations and combos) and label icons (in node and annotation labels).
You can position and scale them using the imageAlignment chart option and dynamically change their fill colour using the c property.
To use font icons, you must install them in your application, import and load them into KeyLines and set them in the iconFontFamily option. See Fonts and Font Icons for details.
The referenced icons must be on the same domain as the KeyLines library, otherwise your browser will mark them as insecure and prevent them from loading. See Cross-Origin Images (CORS) for details.
let data = {
type: 'LinkChart',
items: [
{
id: 'user471',
type: 'node',
c: 'green', // green node
fi: { c: 'white', t: 'fas fa-user' }, // white font icon inside the node
g: [
{
fi: { c: 'red', t: 'fas fa-exclamation-triangle' }, // red glyph icon
p: 'ne', // in north-east corner position of node
},
],
t: [
{
t: 'Membership Expired: 01/2025',
position: 's',
},
{
fi: { c: 'red', t: 'fas fa-exclamation-triangle' }, // red glyph icon
position: { vertical: 'inherit' }, // placed inline following the text label
},
],
},
],
};
If an image is also specified for a node in the u property, the image takes precedence and the font icon is ignored.
Halos are circular rings that can be added to nodes. A node can have up to ten halos, on properties named ha0 to ha9.
Halos are added to nodes as follows:
let data = {
type: 'LinkChart',
items: [
{
id: 'node1', t: 'label', type: 'node', u: 'person.png', x: 100, y: 150,
ha0: {
c: 'rgb(0, 0, 255)', // the halo fill colour
r: 100, // the halo radius
w: 20 // the halo width
}
}
]
};Setting the halo object to null or undefined removes the halo.
Nodes can have donuts around their borders.
They can be split into segments to represent relative quantities, similar to the way sectors work on a pie chart.
Donuts cannot be added to nodes with sh property set to 'box'.
Donuts are added to nodes as follows:
let data = {
type: 'LinkChart',
items: [
{
id: 'node1', type: 'node', c: '#aaa', x: 100, y: 150,
donut: {
// the values for each donut segment
v: [10, 30, 25, 40, 15],
// the colour for each donut segment
c: ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00'],
w: 12, // the width of the donut segments
b: 'black', // the colour of the border between segments
bw: 1 // the width of the border between segments
}
}
]
};v array. If not supplied, a default set of colours is used.The time bar object lets you load JSON data in the following format into the time bar:
let data = {
items: [
{ id: 'id1', // 'id1' is the identity that the item relates to
dt: [...], // a timestamp or array of timestamps - either Date objects or numbers
v: [...], // an optional value or array of values for each timestamp
// values must be numbers, there must be one for each timestamp
},
{ id: 'id2',
dt: [...],
v: [...]
},
...
]
};Time bar object properties are designed so that exactly the same data object can be loaded into both the chart and the time bar.
Simply add the dt and optional v properties to the items.
Each time bar item has a dt property that holds a time bar entry or an array of time bar entries. Each entry may be one of the following:
The TimePeriod object has dt1 and dt2 properties that set the start and end of the time period.
To represent an open-ended time period, set the dt1 property only.
To represent a time period without a start time, set the dt2 property only.
Colours can be specified in several formats:
Note that the 130 extended CSS named colours are not supported.
The KeyLines namespace contains functions for loading charts and time bars into your webpage.
The components object has all the current components loaded by the KeyLines wrapper. Components are accessed via their DOM id:
KeyLines.components['canvasID'].zoom('in');
Components are not created directly, but via KeyLines.create().
Calculates the coordinates of events relative to their target.
Sets the value of the crossorigin HTML attribute whenever KeyLines is trying to load an image from a third-party domain.
The function takes a callback function that should return the value of the HTML attribute as a string depending on your criterion.
If corsAdapter() is not set or if the callback returns undefined, the crossorigin attribute defaults to 'anonymous'.
KeyLines.corsAdapter((url) => {
if (url.startsWith('https://keylines.io/')) {
return 'use-credentials';
} else {
return 'anonymous'
}
});
Creates KeyLines components in your web page.
The create() function is asynchronous, and so returns a promise. If an error occurs, the error catch function will be called, passing the error parameter to it.
Otherwise, the success function will be called with the result object as the new
component or array of components.
// Load a single chart
KeyLines.create({ container: 'div1' })
.then((result) => {
chart = result;
})
.catch((err) => {
// handle the error here
});
// Load two KeyLines components with a specific id
KeyLines.create([
{ container: 'chartDiv', type:'chart' },
{ container: 'timebarDiv', type:'timebar' }
])
.then((result) => {
[chart, timebar] = result;
})
.catch((err) => {
// handle the error here
});
style property
has display: none, width = 0 or height = 0.Checks whether the current browser can show elements full screen.
To view the current state of browser support for the Fullscreen API with desktop and mobile devices, see Can I use Fullscreen API.
Use the toggleFullScreen() call to make an element full screen.
A helper to find the right Unicode character to use for the icon based on the class name:
let data = { id: 'user', type: 'node', fi: { t: KeyLines.getFontIcon('fas fa-user') } }; // retrieves the Unicode position
The getfontIcon() function is deprecated as you can set font icons directly:
let data = { id: 'user', type: 'node', fi: { t: 'fas fa-user' } };
This applies to both the
t option on the fi property to set an icon,
and the imageAlignment option to scale and position it.
See the Font Icons documentation for details.
The Graph engine can be used to perform traversals or other graph computations within a separate context from the chart. For more information see The Graph Engine.
Defines which runtime KeyLines will use when calling KeyLines.create().
Tells KeyLines where it can find various resources on your server. This function must be called before the KeyLines.create() function.
When many chart items use images from the same directory, the images path can be used to save repeated use of the directory path within the chart object.
By default the full path to images must be passed in the u parameter of nodes, e.g.,
const item = { t: 'label', u: '/path/to/very/deep/directory/person.png' };
Alternatively, using the images path:
// in the initialization code put this:
KeyLines.paths({ images: '/path/to/very/deep/directory/' });
// and in the item creation
const item = { t: 'label', u: 'person.png' };
The images path is also used for glyph images, the logo and the background watermark.
The images path must have a trailing slash (/) character.
Allows any given HTMLElement to be put in Full Screen mode, using the browser's full screen API.
Usually a containing div is made full screen, rather than
the KeyLines component itself. You should change the sizes of any parts of the page in the handler function
– this receives a boolean parameter which is true if new status is full screen, or false if not.
Note that this function does not support Promises.
Checks if the current device supports WebGL and meets the minimum requirements.
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.
// 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.
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.
x and y options to centre the arrangement.The combo namespace has methods for combining the nodes and links of a chart to simplify it. See Combo Functions.
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:
w and h parent shape dimensions are set to 'auto', the function returns an empty array.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.
id, id1, id2, type and off).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.
The chart items to iterate over when using combos.
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' }
];
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);
}
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:
layout() function is not supported while using a Leaflet map.x and y properties when using expand() has no effect as layout() overwrites these positions.parentId of new items to add them into a combo, but cannot change the parentId of pre-existing items. See Combos for more detail.name is set to 'grid', controls the row/column dimension of the grid. Specify an object in the form { rows: number } or { columns: number }.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.
orientation.The direction of 'curved' and 'angled' links is inferred from orientation.
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.level.
When specified, nodes are ordered alphanumerically, in descending order, unless sortBy is also set.name is set to 'sequential', the orientation of the arrangement.name is set to 'sequential', the packing mode to use.name is set to 'sequential', the spacing between nodes at each level.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.name is set to 'sequential', the spacing between levels. Values must be positive.chart.filter() function except animate and time, plus an additional one: filterFn.chart.filter() function returns true for them. The default is true if type is 'link', false otherwise.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.
level or top specified.level and top options are specified, level is used.orientation.The direction of 'curved' and 'angled' links is inferred from orientation.
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.level.
When specified, nodes are ordered alphanumerically, in descending order, unless sortBy is also set.name is set to 'sequential' or 'hierarchy', the orientation of the layout.top specified are packed using 'adaptive' packing.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.name is set to 'sequential', the spacing between levels. Values must be positive.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.
level or top specified.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
Use the returned promise object to detect when the operation has completed. The return object is in the form of { url, warnings }, where:
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
});{ width: x, height: y } specifying dimensions of the output. One or both values can be specified:extents.fitTo can also be set to 'page' to scale the aspect ratio of the output to fit and fill the available page space.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.fonts: {
'Font Awesome 5 Free Regular': { src: '../fonts/fontAwesome5/fa-regular-400.woff' },
Raleway: { src: './fonts/Raleway/Raleway-Regular.ttf' },
}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:
If the type is 'all', you have fine control
over the visibility of all items and the rules above do not apply.
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.
Use the returned promise object to detect when the filter operation has completed. The return object describes items altered by the filter function:
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] }]
}
}chart.filter() returns true for them. The default is true if type is 'link', false otherwise.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:
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 );
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.
chart.combo().open() / chart.combo().close(), the option remains set.Returns aggregation information associated with the specified link(s).
An object containing the aggregation information associated with each specified link, or null if there is no link matching the id.
d property being used for aggregation.aggregateByProp. All its child links have the same value of the property.Returns a copy of the items in the chart which match the id.
Note:To update the items, use setProperties().
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().
Returns the position of the annotation relative to its subjects. Can be useful e.g. when converting world-positioned annotations to subject-relative annotations.
Returns the position of the annotation in world coordinates. Can be useful e.g. when converting subject-relative annotations to world-positioned annotations.
The graph object has methods for navigating the top level of your chart.
See KeyLines.getGraphEngine() to consider the underlying level 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.
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.
{
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:
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.
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.
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.
level or top specified.level and top properties are specified, level is used.orientation.The direction of 'curved' and 'angled' links is inferred from orientation.
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.level.
When specified, nodes are ordered alphanumerically, in descending order, unless sortBy is also set.name is set to 'sequential' or 'hierarchy', the orientation of the layout.top is used, any components without top specified are packed using 'rectangle' packing.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.name is set to 'sequential', the spacing between levels. Values must be positive.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.
level or top specified.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' } },
]};
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.
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.
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
];
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.
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.
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.
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 });Pans the chart in the direction specified.
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.
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.
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.
If an item is in a closed combo when it is pinged, the ping appears on the closed combo.
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.
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.
Sets the location of the chart in the DOM. Pass null as the argument to hide it completely.
Things to note:
KeyLines.create() to use setContainer().
chart.setContainer('chartContainer');
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.
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:
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.
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:
fit mode is 'exact'.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.
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.
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).
Zooms the chart in the manner specified.
chart.viewOptions({ zoom: 1 }).Events let you customise your application by responding to user actions on the chart surface. To attach handlers to events, use chart.on().
The 'all' event fires when any event occurs on the chart.
It returns an object containing both the name of the event and the object returned by that event.
The click event fires on a click or tap.
Default action:
The context-menu event fires on a right click or long press for touch devices.
Default action: Suppresses the click event
The double-click event fires on a double click or double tap.
Default actions:
The drag-end event fires when the drag is finished and pointer is released, or when the drag is cancelled. On touch devices this fires when the finger or pointing device is lifted from the surface.
Default actions:
The drag-move event fires continuously as the cursor moves during a drag.
Default action: None
Use debouncing or throttling to limit the number of times the event handler is called:
let timer;
function throttle(func, delay) {
if (timer) return;
timer = setTimeout(() => {
func();
timer = undefined;
}, delay);
}
// throttle eventHandlerFunction to only run once every 100ms
chart.on('drag-move',() => {
throttle(eventHandlerFunction, 100);
});The drag-over event fires when the cursor dragging a node or an annotation moves over another item during a drag.
Default action: None
The drag-start event fires when a drag is started.
Default action: Creates a dragger. Use setDragOptions to set the drag behaviour:
// pan the chart with the right mouse button
chart.on('drag-start', ({ setDragOptions, button }) => {
if (button === 2) {
setDragOptions({ type: 'pan' });
}
});The hover event fires when the cursor hovers over an item or the chart background. The event only fires once when the hover id changes.
Pass the hover property to chart.options() to configure the hover delay.
Default action: None
The key-down event fires when the user presses a key.
Default actions:
The key-up event fires when the user releases a key.
Default action: None
The link-aggregation event fires each time an aggregate link is created, deleted or updated.
The update occurs when a child link is added, removed, hidden or unhidden, a child link's arrow changes, or when the custom property in d object used for aggregating links is changed.
You can use the event to style aggregate links. The default styling is the same as for a regular link, i.e. a grey link with a width of 1.
To style an aggregate link, use chart.setProperties() in the event handler, providing the id of the aggregate link from the event props:
chart.on('link-aggregation', ({ id }) => {
chart.setProperties({ id, c: 'blue' })
});
Aggregate links do not inherit any styling from their child links with the exception of arrows.
Note that you must call chart.on before loading the chart data (so that the handler is called when the data is first loaded).
Default action: None
id of the node/combo
at one end of the aggregate link that comes first in alphanumeric order.
This order may be relevant when using aggregate links with sequential layout
without top or
level specified,
or when setting arrows or flow
on aggregate links. See Enabling aggregate links.id of the node/combo
at the other end of the aggregate link that comes second in alphanumeric order.
This order may be relevant when using aggregate links with sequential layout
without top or
level specified,
or when setting arrows or flow
on aggregate links. See Enabling aggregate links.The map event fires at the start and end of transitions to and from a Leaflet map.
Default action: None
The pointer-down event fires when a pointer presses down on the chart.
Default action: None
The pointer-move event fires continuously as the pointer moves on the chart.
Default action: None
Use debouncing or throttling to limit the number of times the event handler is called:
let timer;
function throttle(func, delay) {
if (timer) return;
timer = setTimeout(() => {
func();
timer = undefined;
}, delay);
}
// throttle eventHandlerFunction to only run once every 100ms
chart.on('pointer-move',() => {
throttle(eventHandlerFunction, 100);
});The pointer-up event fires when the pointer is released.
Default action: None
The prechange event fires whenever the chart changes by either a user action, such as dragging items, or programmatically by calling API methods.
Note that prechange fires before the chart changes. This allows control over state which is useful for adding features like undo/redo.
Default action: None
The progress event fires during longer tasks such as layouts and centrality calculations.
Default action: None
chart.on('progress', ({ task, progress }) => {
if (task === 'layout') {
// use progress value for something
}
});How near the task is to completion on a scale of 0 to 1, where 0 is just started and 1 is finished. A progress of 1 indicates that the layout has finished computing, but not that the nodes have finished repositioning themselves. Layouts report progress differently depending on the layout used:
The selection-change event fires when the chart selection changes from a click event or marquee drag. Note that it does not fire if the selection changes programmatically.
Use chart.selection() to find any changes.
Default action: None
Use debouncing or throttling to limit the number of times the event handler is called:
let timer;
function throttle(func, delay) {
if (timer) return;
timer = setTimeout(() => {
func();
timer = undefined;
}, delay);
}
// throttle eventHandlerFunction to only run once every 100ms
chart.on('selection-change',() => {
throttle(eventHandlerFunction, 100);
});The view-change event fires continuously during any change to the view such as zoom or pan. It also fires when the view state is changed programmatically.
Use viewOptions to find any changes.
Default action: None
Use debouncing or throttling to limit the number of times the event handler is called:
let timer;
function throttle(func, delay) {
if (timer) return;
timer = setTimeout(() => {
func();
timer = undefined;
}, delay);
}
// throttle eventHandlerFunction to only run once every 100ms
chart.on('view-change',() => {
throttle(eventHandlerFunction, 100);
});The wheel event fires continuously while the user is rotating a mouse wheel or scrolling using a trackpad.
Default action:
Options to control the dragging behaviour. This function is returned by the drag-start event and is not available in the main chart namespace.
Pass in options as a single object:
// set dragger to marquee when started on a link
function dragStartHandler({ type, setDragOptions }) {
if (type === 'link') {
setDragOptions({ type: 'marquee' });
}
};
chart.on('drag-start', dragStartHandler);
See the Custom Dragging demo for more examples of use.
type of sub-item is 'label', 'glyph' or 'donut', specifies which label, glyph or donut segment in the array to access, e.g. node.t[index], link.g[index] or node.donut.v[index] respectively.
Note that 'index' is not required when there is only one 'label' sub-item.type is 'arrowhead', 'glyph' or 'label'.type is 'connection' or 'container', tells you which annotation subjects the connector line points to, or which subjects are present in the annotation container.These are the options you can pass to the first argument of chart.options().
For an example of how these options work, see Styling Charts.
Controls whether one or more links between a pair of nodes are displayed as an
aggregate link.
Set to true to aggregate all the links between each pair of nodes or set the options below to specify how links should be aggregated.
Also note that:
d property to be used to aggregate links together.
One aggregate link is created between two nodes for each value of the data.
Remove the d property or set it to undefined to prevent the link from being aggregated.w.Set to give the chart a set of labelled vertical background bands.
Note that bands on a Leaflet map are not supported.
const options = { bands: { top: true, bottom: true, bands: [{ x: 100, w: 100, c: '#F0F0F0', t: 'Band 1' }, { x: 200, w: 100, c: '#F8F8F8', t: 'Band 2' }] } };
chart.options(options);FontFamily setting of chart.options().chart.combo().combine(),
or by adding new links. Any unspecified properties are inherited from the styling of a link contained in the combo.
See Link for default values.id1 as a ratio of the total length of the link line. Value in the range 0 to 1.id2 as a ratio of the total length of the link line. Value in the range 0 to 1.t option.Set to give the chart a background gradient fill that runs from top to bottom of the chart. Note that backColour property takes precedence over the gradient property.
const options = { gradient: { stops: [{ r: 0, c: 'rgb(250, 250, 250)' }, { r: 1, c: 'rgb(200, 200, 200)' }] } };
chart.options(options);r value.navigation:
Sets the position and scale for images and font icons on nodes. The object accepts properties where property names are image or font icon paths and property values are the values to be adjusted:
chart.options({
imageAlignment: {
'fas fa-user': { e: 0.8, dx: 5 },
'/images/icons/person4.png': { dx: -20, dy: 5, e: 2.5 }
}
});
When using images and font icons in label objects for node and annotation labels, image alignment is handled differently. See Image labels and Text-based labels.
w and h specified are drawn behind other chart items as legacy shape nodes.positions object.glyphs option.Controls the shape of links. Most effective with sequential layouts. Deprecated as we recommend using the linkShape option instead.
The 'horizontal' and 'vertical' shapes will not apply to links within combos.
c2 property set). Controls the size of the fraction at the midpoint of the link where the colour transition occurs. Must be between 0 and 1, with 0 providing an immediate transition between colours. The rest of the link is drawn with solid colours.const options = { logo: { u: 'path/to/images/myAwesomeLogo.png', p: 'se', x: 20, y: 20 } };
chart.options(options);path/to/images/[email protected]minZoom to 4. Using the default value is suggested for optimal result.Settings for the navigation controls.
const options = { navigation: { p: 'ne', shown: true, x: 10, y: 15 } };
chart.options(options);
If you don't want navigation controls on your chart, or you'd prefer to add custom controls, use:
const options = { navigation: false };
chart.options(options);
See the Social Network Analysis demo for examples how to customise navigation controls.
Settings for the overview window. To hide the overview window, you can set it to false. Overview window is not supported on a Leaflet map.
The background colour of the overview window. If an rgba colour is used, the alpha channel is ignored.
shown is false hides the overview window.selectedLink is null or undefined -
Selected links have a coloured selection circle and font background fbc
set by selectionColour
and a font colour fc set by
selectionFontColour.
selectedLink
and selectionColour /
selectionFontColour have different values -
selectedLink takes precedence.
selectedLink is partially set -
any values unset are inherited from the unselected link styling.
t1 and/or t2
set, their styling is the first specified of:
Note that if t1 / t2
inherit the styling from the border object from any of the above, any unspecified values will be set to defaults.
id1 as a ratio of the total length of the link line. Must be between 0 and 1.id2 as a ratio of the total length of the link line. Must be between 0 and 1.c at the id1 end
and colour c2 at the id2 end.
The transition setting of
linkStyle
controls the gradient's appearance.fontFamily setting of chart.options().ls property).border set, applies to the whole label container.id1 end. For multiline labels, use '\n' or '\r' to force a line break. Strings inherit properties from the label at the centre of the link.id2 end. For multiline labels, use '\n' or '\r' to force a line break. Strings inherit properties from the label at the centre of the link.selectedNode is null or undefined -
Selected nodes have a default border b and
font background fbc set by
selectionColour
and a font colour fc set by
selectionFontColour.
selectedNode
and selectionColour /
selectionFontColour -
selectedNode values take precedence.
If selectedNode is only partially set,
any values unset are inherited from the unselected node's styling. See
Node for default values.
fbc property was set on the top node level or to those labels that don't have a set fbc property.
The default is inherited from selectionColour.
fc property was set on the top node level or to those labels that don't have a set fc property.
The default is inherited from selectionFontColour.
e property.ha0, ha1, ha2, etc., up to ha9.legacyShapeNodeBehaviour is enabled.selectedNode and/or selectedLink are null or undefined.selectedNode and/or selectedLink are null or undefined.....An object whose properties are the settings for a watermark on the chart.
Note that watermarks on a Leaflet map are not supported.
const options = { watermark: { a: 'top', fb: true, fs: 15, fc: 'black', t: 'A custom watermark' } };
chart.options(options);Adapts the chart at low zoom levels to improve the visual appearance. For example, small nodes are enlarged to stay visible and links and text fade. For best results, set avoidLabels to false.
Combos can be used to combine nodes and links together to simplify the visualisation. To access the combo namespace, use chart.combo().
Arranges the items inside a combo.
Items are arranged automatically (default) or manually. The available automatic options are:
To stop items from being arranged automatically, set name to 'none'.
Multiple ids can be passed to the arrange() function: in this case, items inside open combos within the array will be arranged.
Use the returned promise to know when the operation is complete.
Note: You must wait for the combine promise to be fulfilled before performing another chart function.
name is set to 'grid', controls the row/column dimension of the grid. Specify an object in the form { rows: number } or { columns: number }.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.
orientation.The direction of 'curved' and 'angled' links is inferred from orientation.
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.level.
When specified, nodes are ordered alphanumerically, in descending order, unless sortBy is also set.name is set to 'sequential', the orientation of the arrangement.name is set to 'sequential', the packing mode to use.name is set to 'sequential', the spacing between nodes at each level.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.name is set to 'sequential', the spacing between levels. Values must be positive.Closes the specified open combo/s, concealing the items inside.
Combines a number of nodes into one or more 'combo nodes'. A combo definition object defines which nodes should be included in these combos and how they should be displayed.
A combo can be created in one of two states:
To open a combo, set the open property on its definition object.
Any links that connect nodes outside the combo to nodes inside it are combined into 'combo links'.
Use the returned promise to detect when the operation has completed. The fulfilled promise returns an array of the identities of the combo nodes created as the first argument.
Note: You must wait for the combine promise to be fulfilled before performing another chart function.
chart.combo().combine({ ids: [id1, id2] }).then((comboIds) => {
// do more after combine
});
To create many combos at once, use an array of combo definitions.
chart.combo().combine(
[{ ids: [id1, id2] }, { ids: [id3, id4] }]).then((comboIds) => {
// do more after combine
});
You cannot combine items that already exist inside a combo.
Closed and open combo states should not be confused with hide() and show() chart functions.
If you combine a mixture of hidden and shown nodes, the nodes inside the combo will remain hidden or shown as appropriate.
If you combine only hidden nodes, the combo itself will be hidden.
openCombos setting of defaultStyles.ids array except for the t option. If hi is not set, the combo is visible if any of its member nodes are visible.
Setting parentId in style is not supported.name and any properties associated with that arrangement.Finds the ids of the combos that contain the given nodes, links or child combos.
Finds every underlying node and link inside a combo or nest of combos, or null if the id is not a combo.
Tests node or link ids to find out whether they are combo nodes or combo links. If a list of ids is used, it returns true if any of the items are combos.
The options argument defines which items to test. For example,
to test whether a selection contains a combo node:
const selectionContainsNodeCombo = chart.combo().isCombo(chart.selection(), { type: 'node' });Tests whether an item is an open combo.
Opens the specified combo/s so the contents are visible inside a combo border on the chart.
To change the border style, set the openStyle options of chart.combo().combine.
Gets or sets the list of revealed links.
Links which connect nodes inside a combo to nodes outside it are normally combined into a single link to reduce clutter. The reveal() function shows the original underlying links.
Calling reveal() with a parameter replaces the previous list of revealed links. Pass an empty array to clear all revealed links.
Transfers the specified items into or out of a combo, increasing the size of the target combo as needed to fit its new contents.
name and any properties associated with that arrangement.Uncombines the specified combo nodes. Items inside the combo(s) are displayed on the chart. Combo links that connect nodes inside the combo to nodes outside it are also uncombined.
When nodes are uncombined, their original position is used to place them in the same shape relative to the uncombined node.
Multiple ids can be passed to the uncombine() function: in this case, all combo nodes in the array will be uncombined.
You cannot uncombine nested items (combo nodes and combo links that exist inside other combos).
Use the returned promise to know when the operation is complete.
Note: You must wait for the combine promise to be fulfilled before performing another chart function.
Graph functions let you explore the graph structure of your data.
For more information about chart levels, and using graph functions with combos, see the Running graph analysis section in Combos Concepts.
Calculates the betweenness centrality of all nodes in the graph.
The returned objects properties are the ids of the nodes in the graph. The values are the betweenness values.
chart.graph().betweenness({}).then((betweenness) => {
const sizes = Object.keys(betweenness).map((id) => {
return { id: id, e: Math.pow(1 + betweenness[id], 2) };
});
return chart.animateProperties(sizes, { time: 500 });
});
The betweenness call is asynchronous - the function will return before the betweenness has completed. To discover the progress of the betweenness use the progress event.
Use the returned promise to detect when betweenness has finished.
Calculates the closeness centrality of all nodes in the graph.
The function returns an object whose properties are the ids of the nodes in the graph. The values are the closeness values.
chart.graph().closeness({}).then((closeness) => {
Object.keys(closeness).forEach((id) => {
console.info(`node '${id}' closeness is ${closeness[id]}`);
});
});
The closeness call is asynchronous - the function will return before the closeness has completed. To discover the progress of the closeness use the progress event.
Use a promise function to detect when the closeness has finished.
Groups nodes in the graph into a set of clusters, and then returns an array describing them.
[cluster1, cluster2, ...] where cluster1, cluster2... are arrays containing ids of nodes that are all in the same cluster.Returns the separate 'connected components' of the graph.
An array of objects describing the items contained by each component:
[
{ nodes: ['node1', 'node2'], links: ['link-12']},
{ nodes: ['node3']}
]Calculates the degrees (number of links) of all nodes in the graph.
The degrees function does not count any self links (links that have the same node at both ends).
The function returns an object whose properties are the ids of the nodes in the graph. The values are the degree values.
const outDegrees = chart.graph().degrees({ direction: 'from' });
const sizes = Object.keys(outDegrees).map((id) => {
return { id: id, e: Math.sqrt(outDegrees[id]) };
});
chart.animateProperties(sizes, { time: 500 });Calculates the distances of all nodes from the node specified. The distance is the number of edges in a shortest path.
All values must be positive numbers. If there are multiple links between two nodes, the minimum distance value will be used. No results are returned for disconnected nodes.
If you do not specify a value property, the distance values of all links are set to 1.
const distances = chart.graph().distances(chart.selection()[0]);
const labels = Object.keys(distances).map((key) => {
return { id: key, t: distances[key] };
});
chart.setProperties(labels);d property of the links.Computes the eigenvector centrality of each node.
Eigenvector centrality is a measure of influence that takes into account the number of links each node has and the number of links their connections have, and so on throughout the network.
All values must be positive numbers. If there are multiple links between two nodes, the sum of the values of each link will be used.
If you do not specify a value property, the values of all links are set to 1.
The results are normalised so that the sum of the eigenvector centrality values in each component equals the number of nodes in that component. For example, an isolated node will always have an eigenvector centrality of 1.
Link direction does not affect the eigenvector centrality calculation.
Calculates subgraphs of the graph where each node has a degree of at least k. It works by successively removing nodes of degree less than k until no further nodes can be removed.
The function returns an object with all kCores values and the maximum k found in the chart. With a given k it is possible to find all cores components:
const kCores = chart.graph().kCores();
const hidden = Object.keys(kCores.values).filter((id) => {
return kCores.values[id] < 5;
});
chart.hide(hidden, { time: 500 });
// the next call identifies the separate cores
chart.graph().components();Replaces the graph data with the new data specified.
Note that the data argument is a JavaScript Object, not a JSON string. It should have the
properties specified in Item Format.
Computes the PageRank of each node.
The PageRank measure identifies important nodes by assigning each node a score based on its number of incoming links (its ‘indegree’). These links are weighted depending on the relative scores of their originating nodes.
All values must be positive numbers. If there are multiple links between two nodes, the sum of the values of each link will be used.
If you do not specify a value property, the values of all links are set to 1.
Calculates all the shortest paths between the nodes specified.
const paths = chart.graph().shortestPaths('start', 'end', { direction: 'any' });
console.log('Number of hops = ' + paths.distance);
chart.selection(paths.items);
All values must be positive numbers.
If you do not specify a value property, the values of all links are set to 1.
onePath, but containing node ids only, including the start and end nodes.d property of the links.Map functions allow you to show chart items on a map. To access the map namespace, use chart.map(). See also the map event which is triggered by the chart.
Hides the Leaflet map that was displayed with the show function. Chart nodes with lat and lng
properties are repositioned as specified by the transition
setting. The speed of the transition depends on settings made with the options function.
The chart triggers a map event
at the start and end of the hide operation.
To show the Leaflet map again, call show().
Gets direct access to the underlying Leaflet map object. This allows you to use the Leaflet API directly, for example to add new layers to the map. The Leaflet map object is only returned when the map is shown. When the map is hidden, the underlying Leaflet map object is removed and this function returns null.
Refer to the relevant release version of the Leaflet API Reference for details of the Leaflet API.
Converts a set of view coordinates to the exact latitude and longitude.
Sets or gets options for the Leaflet map. See Map Options.
chart.map().options({
tiles: {
url: 'http://example.com/path/{z}/{x}/{y}.png',
attribution: 'Attribution text',
minZoom: 4,
maxZoom: 12,
noWrap: false
}
}).then(() => {
// do more after options
});
Note: If you reference a Leaflet map tile URL or object 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 of how to fix this, see Cross-Origin Images (CORS).
Displays a Leaflet map behind the chart. Chart nodes with lat and lng properties are moved to the
correct position on the map, see the
Map Position Object.
Nodes without valid lat and lng properties will be hidden.
The speed of the transition and the appearance of the Leaflet map depend on
settings made with the options function.
The chart triggers a
map event
at the start and end of the show operation.
Note:
chart.map().show(), the handMode option is automatically set to true.
To hide the map again, call chart.map().hide().
Converts a set of latitude and longitude coordinates to the exact point in the view.
These are the options you can pass to the first argument of chart.map().options().
Pass options directly into the Leaflet constructor. See the L.map options documentation in the relevant version of the Leaflet API Reference.
An option to set the url template for Leaflet map tiles.
Accepts either a string in the form of 'http://example.com/path/{z}/{x}/{y}.png',
or an object in the Leaflet L.tileLayer options format
with an additional url property:
chart.map().options({
tiles: {
url: 'http://example.com/path/{z}/{x}/{y}.png',
attribution: 'Attribution text',
minZoom: 4,
maxZoom: 12,
noWrap: false
}
}).then(() => {
// do more after options
});
If the url template isn't set, OpenStreetMap is used as a default tile provider. If set to null, the tile layer isn't created.
See the L.tileLayer options documentation in the relevant version of the Leaflet API Reference.
See the Map Layers documentation for more details about tiles and the default map tiles used by KeyLines.
Note: If you reference a map tile URL or object 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).
Time bar functions allow you to get and set the time bar's range, and display a histogram with it. To obtain a time bar object to call these functions on, use KeyLines.create.
Returns an array of the ids that have datetimes in the specified range. A datetime dt is in the specified range if it satisfies dt1 <= dt < dt2.
Determines whether the item has a datetime either within the time bar's time range, or which overlaps any part of a time period in the range. Note that the item must have been loaded into the time bar.
If the item does not have a datetime, or the item does not exist or overlap a time period in the
time bar's loaded data, then inRange() will return false.
Replaces the time bar data with the new data specified.
The data argument is a JavaScript Object, not a JSON string.
It should have the properties specified by the
Time Bar Item Properties.
If the loaded data changes the current time range, the timebar.change() event is not fired. If you don't want the range to change, first set the maxRange time bar option to take account of the data you're about to load.
To fit the time bar to the data once it has been loaded, use returned promise:
timebar.load(data).then(() => {
return timebar.zoom('fit', { animate: false });
});Sets or gets a list of dates or time periods (with both start time and end time specified) which should be marked in a different colour in the histogram.
This example shows how to mark one time as well as a range of times:
const marks = [
// mark 1 - single date
new Date('26 Jul 2010 08:00:00'),
// mark 2 - time period - both start and end time must be set
{
dt1: new Date('18 Jul 2010 14:00:00'),
dt2: new Date('21 Jul 2010 14:00:00')
}
];
timebar.mark(marks);
To clear all the marks pass an empty array as an argument.
Inserts new data into the time bar, merging it with any existing time bar data.
Incoming items that exactly match existing items in the time bar are merged with them on a one-to-one basis.
Note that the items argument is a JavaScript object or array, not a JSON string.
It should have the properties specified in the
Time Bar Object Properties.
Detaches an event handler function for one or more events attached to the time bar using the on() function.
timebar.off('change', changeEventHandler);
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.
Attaches an event handler function for one or more Time Bar Events to the time bar.
function changeEventHandler() {
// respond to change event
}
timebar.on('change', changeEventHandler);
To detach event handlers, use off().
See Events Basics for more details.
Sets or gets options for the time bar.
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.
Pans the time bar in the direction specified.
Starts a continuous animation of the time bar range. The speed of the animation can be set via the options function's playSpeed property.
Sets or gets the time range of the time bar. If called without parameters, it returns the time range of the time bar without updating it.
Setting the time range causes different visual effects according to whether the sliders are fixed, free, or not present.
sliders:'none') then the time range is displayed in the full width of the time bar.Things to note:
Removes item or items with the id(s) specified. Pass a single id to remove a single item, or an array of id strings to remove many items at once. Note that there is no event to detect items being removed from the time bar.
Sets or gets the time bar selection lines.
This example shows how to create multiple selection lines by passing an array:
const lines = [
// selection 1 - blue colour
{ id: ['id1', 'id2'], index: 0, c: 'blue' },
// selection 2 - default colour
{ id: ['id3', 'id4'], index: 1 }
];
timebar.selection(lines);
To clear all the selections pass an empty array as argument. To clear a specific selection pass a selection object with an empty array as the id and its index.
Things to note:
selection() calls will not clear all selection lines. To clear existing selection lines, pad the array with empty objects.Sets the location of the time bar in the DOM. Pass null as the argument to hide it completely.
Things to note:
KeyLines.create() to use setContainer.timebar.setContainer('timebarContainer');Zooms the time bar in the manner specified.
zoom('fit',...), the ids of items to include in the fit range. If not specified, all items are included.Events let you customise your application by responding to user actions on the time bar surface. To attach handlers to events, use timebar.on().
Fires when any event occurs on the time bar. It returns an object containing both the name of the event and the object returned by that event.
Default action: None
The change event fires when the time range is changed, either by the user or programmatically. To get the new range, use the range() function.
The event also fires when the time bar data is changed but only if the change affects the current range.
Default action: None
The click event fires on a click or tap.
Default actions:
The type of clicked item:
The context-menu event fires on a right click or long press for touch devices.
Default action: Suppresses the click event.
The type of clicked item:
The double-click event fires on a double click or double tap.
Default action: Zooms in and centres at the clicked time (animated).
The type of clicked item:
The drag-end event fires when the drag is finished and the pointer released, or when the drag is cancelled. On touch devices this fires when the finger or input device is lifted from surface.
Default action:
The type of dragged item:
The drag-start event fires when a drag is started.
Default action:
The type of dragged item:
The end event fires when the end data point is reached.
Default action: None
The hover event fires when the cursor hovers over an item. The event only fires once when the type of the hover target changes.
Default action: None
The type of hovered item:
The key-down event fires when the user presses a key.
Default actions:
The pause event fires when the time bar is paused.
The event also fires when pausing the time bar programmatically.
Default action: None
The play event fires when the time bar starts to play.
The event also fires when playing the time bar programmatically.
Default action: None
The pointer-down event fires when a pointer presses down on the surface.
Default action: None
The type of item under the pointer:
The pointer-move event fires continuously as the pointer moves on the surface.
Default action: None
The type of item under the pointer:
The pointer-up event fires when the pointer is released.
Default action: None
The type of item under the pointer:
The start event fires when the starting data point is reached.
Default action: None
The wheel event fires continuously while the user is rotating a mouse wheel or scrolling using a trackpad.
Default actions:
These are the options you can pass to the first argument of timebar.options().
For an example of how these options work, see Customise the Time Bar.
type is set to 'area'.A string controlling the order of dates:
maxRange fixed to { units: 'hour', value: 6 }
the time bar will not zoom out beyond six-hour intervals.
This is useful if your dataset spans a large time range and you want to limit the amount of data visible.
By default, KeyLines calculates the range between the data's earliest and latest dates/times and multiplies it by two.minScale fixed to { units: 'hour', value: 6 }
the time bar will not zoom in beyond six-hour intervals.
This can be useful when the data has no precise information about the hour or the minute of the event to stop zooming further.
The default behaviour scales with the range of the data.timebar.range() is called.