API Reference
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
.- string - A simple text string label.
- Beta NodeLabel - A single label object that can contain label styling properties.
- Beta NodeLabel[] - An array of objects to add multiple labels where each label can be styled individually.
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.- string - A simple text string label.
- Beta NodeLabel - A single label object that can contain label styling properties.
- Beta NodeLabel[] - An array of objects to add multiple labels where each label can be styled individually.
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; see Self Link Offsets.
border
set, applies to the whole label container.parentId
s 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 connected to items in the chart. The following chart items can be annotated:
- Nodes
- Links
- Open and closed combos
See also the Annotations documentation for more information.
Annotations are added to the chart as a special type
of an item
that contains the id or ids of the annotated item(s) in the subject
property:
let data = {
type: 'LinkChart',
items: [
{
id: 'annotation1',
type: 'annotation',
subject: 'node1',
t: { t: 'Annotation Label' },
position: { angle: 'ne' },
connectorStyle: { container: 'rectangle' }
},
{
id: 'node1', // node1 is the annotation subject
type: 'node',
c: 'rgb(45,105,160)',
},
]
};
Annotations are drawn in a separate layer on top of the chart and their position is relative to their subjects. When a layout is run or when their subjects move, annotations keep their position relative to their subjects.
Annotations that are linked to chart items are only displayed if at least one of the annotated items is present.
Notes:
- Annotations cannot be selected or backgrounded.
- Annotations are not shown on a Leaflet map.
- Annotations for time bar are not supported.
topLeft
or bottomRight
.- A line towards the subject, or multiple lines if there are multiple subjects.
- The decoration at the subject end of the line(s). Can be set in the
subjectEnd
option for any annotations. - A container around the subject(s). Can be set in the
container
option for node and combo annotations.
- 'none' - No container is drawn. When annotating links, this is the only option available.
- 'circle' - Draws a circle around the subject node(s) or combo(s).
- 'rectangle' - Draws a rectangle around the subject node(s) or combo(s).
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.
Labels on open and closed combos
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.See also Margin, padding and borders for details and accepted value formats.
- For text and font icon labels: the maximum height. Use this to limit the text height when
fs
is set to 'auto'. - For image labels: the image height if
maxWidth
also set.
- For text and font icon labels: the maximum width. Use it to reduce the text width before a line break when
textWrap
is set to 'normal', or set the maximum text width whenfs
is set to 'auto'. - For image labels: the image width if
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.See also Margin, padding and borders for details and accepted value formats.
The compass point values ( 'n', 'ne' etc.) place labels outside the node/combo.
An object with
horizontal
and/or vertical
properties
places labels inside the node/combo.
Default position for nodes and closed combos is in the middle and centre of the node.
Default position for open combos is outside and below the combo.
If there are multiple labels with completely or partially overlapping positions, the label which was processed later will be drawn over the label which was processed earlier.
See also Label positioning and Advanced combo styling for details.
The 'inherit' value puts the label on the same line as the previous label:
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'.See also Margin, padding and border for details and accepted value formats.
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.See also Margin, padding and border for details and accepted value formats.
Accepts a string with a compass point value ( 'n', 'ne' etc.) to place a label outside the annotation, or an object with
horizontal
and/or vertical
properties
to place a label inside the annotation.
Default annotation label position is
{ 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:
- North East ('ne')
- South East ('se')
- South West ('sw')
- North West ('nw')
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:
- text
t
(highest priority) - image
u
- font icon
fi
- coloured circle
c
(lowest priority)
To move icons and images inside glyphs from their default positions, use the imageAlignment option.
Glyphs on Nodes and Annotations
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:
- Compass points, e.g. 'n' for north, 'se' for south east etc.
- Integers in the range 0-359, where numbers represent the angle from the centre of the item, measured in degrees clockwise from north.
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: '!' }], }, ]};
Glyphs on Links
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 ], }, }]};
Beta Glyphs on Open Combos
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:
- a Date object or millisecond number, representing an instant in time
- a TimePeriod object, representing a period of time
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:
- One of the 17 CSS standard named colours, e.g., 'red'
- Shorthand hexadecimal colours, e.g., '#F00'
- Hexadecimal colours, e.g., '#FF0000'
- rgb or rgba formats. For example
- 'rgb(255, 0, 0)' - Red
- 'rgba(255, 0, 0, 0.5)' - Red with an alpha blend of 50%
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.
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.
- 'absolute': use the
x
andy
options 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.
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:
- If no nodes or shapes are contained within the parent shape, the function returns an empty array.
- If one or both of
w
andh
parent 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.
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.
- '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.
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:
- 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
x
andy
properties when usingexpand()
has no effect aslayout()
overwrites these positions. - You can set the
parentId
of new items to add them into a combo, but cannot change theparentId
of pre-existing items. See Combos for more detail.
- KeyLines chart object.
- A single item.
- An array of items.
- 'all': all items adapt.
- 'inCombo': items inside the parent combo adapt, top level layout stays unchanged.
- 'none': no items adapt.
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.
- '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.
The direction of 'curved' and 'angled' links is inferred from orientation.
- '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.
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.- '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.
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.
- 'radial' and 'hierarchy' must have either
level
ortop
specified. - 'sequential' assigns levels automatically if neither are specified (inferred from the nodes' links).
- If both the
level
andtop
options are specified,level
is 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.
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.- '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
top
specified 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.
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.
- 'radial' and 'hierarchy' must have either
level
ortop
specified. - 'sequential' assigns levels automatically if neither are specified (inferred from the nodes' links).
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
});
- 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.
{ width: x, height: y }
specifying dimensions of the output. One or both values can be specified:- 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,
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:
- any nodes that have only hidden links will also be hidden
- any visible links will have nodes at both ends also visible
- any annotations 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 the links and nodes 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] }]
}
}
chart.filter()
returns true for them. The default is true if type
is 'link', false otherwise.- 'underlying': iterates over items that are not combo nodes or combo links.
- 'toplevel': iterates over items, including combos, that are not inside other combos.
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 links and nodes -
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.
chart.combo().open()
/ chart.combo().close()
, the option remains set.- 'underlying': iterates over items that are not combo nodes or combo links.
- 'toplevel': iterates over items, including combos, that are not inside other combos.
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.- '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
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().
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, 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:
- '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.
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.
- 'radial' and 'hierarchy' must have either
level
ortop
specified. - 'sequential' assigns levels automatically if neither property are specified (inferred from the nodes' links).
- If both the
level
andtop
properties are specified,level
is 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.
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.- '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 withouttop
specified 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.
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.
- 'radial' and 'hierarchy' must have either
level
ortop
specified. - 'sequential' assigns levels automatically if neither are specified (inferred from the nodes' links).
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.
- KeyLines chart object.
- A single item.
- An array of items.
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.
- 'up' / 'down' / 'left' / 'right' - Pans the chart as specified.
- 'selection' - Pans the centre of the viewport to the centre of the selected items.
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.
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:
- 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');
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:
- 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.
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 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:
- 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.
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.
- '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.
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:
- On an item: Selects the item (adds to current selection if consistentCtrl is pressed)
- On the background: Deselects all items
- On the navigation controls: Performs the navigation control action
- On the overview icon: Opens or closes the overview window
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:
- On the background: Zooms in (animated)
- On a combo: Opens or closes the combo
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:
- Updates the chart selection if type is 'marquee'
- Moves selected items to their final positions if type is 'node' or 'link'
- Accepts the final viewport position if type is 'pan' or 'overview'
- Creates the link if type is 'create-link'
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:
- Escape key: Cancels a drag if present
- Delete key: Deletes selected items
- consistentCtrl + A: Selects all selectable items
- Arrow keys: Moves selected items
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:
- Organic - Reports incrementally
- Hierarchy - Only reports 0 or 1
- Sequential - Only reports 0 or 1
- Lens - Reports incrementally
- Radial - Only reports 0 or 1
- Structural - Reports incrementally
- Standard - Reports incrementally
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:
- On the background: Zooms in or out
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.- 'donut', 'halo' - node decorations
- 'bubble' - node and link decoration
- 'label', 'glyph' - node, link and annotation decoration
- 'resize' - resize handles on open combos
- 'arrowhead' - arrows on link ends
- 'container' - the container surrounding annotation subjects
- 'connection' - the line and subject end of the annotation connector
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.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.- 'along' - glyphs are drawn along the link.
- 'horizontal' - glyphs are drawn horizontally.
glyphs
option.Controls the shape of links. Most effective with sequential layouts. Deprecated as we recommend using the linkShape option instead.
- 'direct' - links are either straight or follow arcs when offset.
- 'horizontal' - link ends join to nodes horizontally, following a curved path.
- 'vertical' - link ends join to nodes vertically, following a curved path.
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. Values around 1 are suggested for an 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 backgroundfbc
set by selectionColour and a font colourfc
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.-
If
selectedNode
is null or undefined - Selected nodes have a default borderb
and font backgroundfbc
set by selectionColour and a font colourfc
set by selectionFontColour. -
If different values are set in
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:
- lens - automatic arrangement with connected nodes next to each other. The default for circular combos.
- concentric - circular 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.
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.
Return Object
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.
- 'all': all items adapt.
- 'inCombo': items inside the parent combo adapt, top level layout stays unchanged.
- 'none': no items adapt.
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.
- '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.
The direction of 'curved' and 'angled' links is inferred from orientation.
- '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.
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.
- 'all': all items adapt.
- 'inCombo': items inside the parent combo adapt, top level layout stays unchanged.
- 'none': no items adapt.
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:
- closed (default) - items inside the combo are not visible.
- open - items inside the combo are displayed inside a combo border on the chart.
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'.
Return Object
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
.- 'average': use the average position of the nodes to centre the arrangement.
- 'first': use the position of the first node in the ids array.
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
.
- 'all': all items adapt.
- 'inCombo': items inside the parent combo adapt, top level layout stays unchanged.
- 'none': no items adapt.
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.
- 'all': all items adapt.
- 'inCombo': items inside the parent combo adapt, top level layout stays unchanged.
- 'none': no items adapt.
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).
Return Object
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.
- To consider the top level of your chart, which takes combos into account but ignores their children, use the chart.graph() namespace.
- To consider the underlying level of the chart, or use graph functions without also rendering the chart, use the Graph Engine.
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.
Return Object
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.
Return Object
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.
- 'from': counts only links with arrows pointing away from nodes (out-degree).
- 'to': counts only links with arrows pointing to nodes (in-degree).
- 'any': counts all links regardless of whether they have arrows.
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).
Return Object
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 });
- 'from': counts only links with arrows pointing away from nodes (out-degree).
- 'to': counts only links with arrows pointing to nodes (in-degree).
- 'any': counts all links regardless of whether they have arrows.
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);
- 'from': counts only links with arrows pointing away from nodes (out-degree).
- 'to': counts only links with arrows pointing to nodes (in-degree).
- 'any': counts all links regardless of whether they have arrows.
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.
Return Object
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.
- 'from': counts only links with arrows pointing away from nodes (out-degree).
- 'to': counts only links with arrows pointing to nodes (in-degree).
- 'any': counts all links regardless of whether they have arrows.
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.- 'from': counts only links with arrows pointing away from nodes (out-degree).
- 'to': counts only links with arrows pointing to nodes (in-degree).
- 'any': counts all links regardless of whether they have arrows.
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.
- If the map is already hidden, or a show or hide transition is underway, this call has no effect.
- Cannot be used while the chart's container is set to null.
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).
Setter: A Promise object.
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:
- If the map is already shown, or a show or hide transition is underway, this call has no effect.
- Cannot be used while the chart's container is set to null.
-
When calling
chart.map().show()
, thehandMode
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.
Setter: A Promise object.
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.
- If the sliders are fixed then setting the time range moves and zooms the scale underneath the sliders.
- If the sliders are free then the sliders themselves move to the time range specified and scale does not change.
- If there are no sliders (
sliders:'none'
) then the time range is displayed in the full width of the time bar.
Things to note:
- There are minimum and maximum limits on the time range size, and the time range must either overlap or be adjacent to the time range of loaded data. The requested range may be adjusted to meet these constraints.
- The range function returns a JavaScript Date object. For more details see Time Zones.
- Using this promisified function as a getter still returns an object in a synchronous way. See Special Cases: getters and setters for more detail.
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:
- The maximum number of selection lines available is 3: any selection with an index greater than 2 will be ignored. The default colours for the selection lines are: 0: green; 1: orange; 2: dark red.
- The selection lines use a different scale to the histogram bars. Selection lines are scaled depending on the values within the selection range.
- Passing a smaller array in subsequent
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:
- You must specify the container parameter in
KeyLines.create()
to usesetContainer
. - While the container is set to null all drawing and animations are paused.
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:
- On a control button: Performs the button action.
The type of clicked item:
- 'area' - the area under the curve when in area mode
- 'bar' - a histogram bar
- 'selection' - a selection line point
- 'scale' - the time axis scale
- 'histo' - the histogram area between the sliders
- 'left', 'right' - sliders
- 'slider' - the areas outside the current slider range
- 'controlbar' - the control bar at the bottom of the time bar
- 'fit', 'previous', 'next', 'play', 'playextend', 'zoomin', 'zoomout' - control bar controls
- null - if there is nothing under the pointer
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:
- 'area' - the area under the curve when in area mode
- 'bar' - a histogram bar
- 'selection' - a selection line point
- 'scale' - the time axis scale
- 'histo' - the histogram area between the sliders
- 'left', 'right' - sliders
- 'slider' - the areas outside the current slider range
- 'controlbar' - the control bar at the bottom of the time bar
- 'fit', 'previous', 'next', 'play', 'playextend', 'zoomin', 'zoomout' - control bar controls
- null - if there is nothing under the pointer
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:
- 'area' - the area under the curve when in area mode
- 'bar' - a histogram bar
- 'selection' - a selection line point
- 'scale' - the time axis scale
- 'histo' - the histogram area between the sliders
- 'left', 'right' - sliders
- 'slider' - the areas outside the current slider range
- 'controlbar' - the control bar at the bottom of the time bar
- 'fit', 'previous', 'next', 'play', 'playextend', 'zoomin', 'zoomout' - control bar controls
- null - if there is nothing under the pointer
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:
- On the background: Accepts the final panned range of the time bar.
- On the slider: Accepts the final range of the time bar and zooms to fit the view.
The type of dragged item:
- 'area' - the area under the curve when in area mode
- 'bar' - a histogram bar
- 'selection' - a selection line point
- 'scale' - the time axis scale
- 'histo' - the histogram area between the sliders
- 'left', 'right' - sliders
- 'slider' - the areas outside the current slider range
- 'controlbar' - the control bar at the bottom of the time bar
- 'fit', 'previous', 'next', 'play', 'playextend', 'zoomin', 'zoomout' - control bar controls
- null - if there is nothing under the pointer
The drag-start event fires when a drag is started.
Default action:
- On the background: Starts a pan controlled by the pointer.
- On the slider: Starts dragging the slider.
The type of dragged item:
- 'area' - the area under the curve when in area mode
- 'bar' - a histogram bar
- 'selection' - a selection line point
- 'scale' - the time axis scale
- 'histo' - the histogram area between the sliders
- 'left', 'right' - sliders
- 'slider' - the areas outside the current slider range
- 'controlbar' - the control bar at the bottom of the time bar
- 'fit', 'previous', 'next', 'play', 'playextend', 'zoomin', 'zoomout' - control bar controls
- null - if there is nothing under the pointer
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:
- 'area' - the area under the curve when in area mode
- 'bar' - a histogram bar
- 'selection' - a selection line point
- 'scale' - the time axis scale
- 'histo' - the histogram area between the sliders
- 'left', 'right' - sliders
- 'slider' - the areas outside the current slider range
- 'controlbar' - the control bar at the bottom of the time bar
- 'fit', 'previous', 'next', 'play', 'playextend', 'zoomin', 'zoomout' - control bar controls
- null - if there is nothing under the pointer
The key-down event fires when the user presses a key.
Default actions:
- Space key: Toggles Play/Pause buttons
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:
- 'area' - the area under the curve when in area mode
- 'bar' - a histogram bar
- 'selection' - a selection line point
- 'scale' - the time axis scale
- 'histo' - the histogram area between the sliders
- 'left', 'right' - sliders
- 'slider' - the areas outside the current slider range
- 'controlbar' - the control bar at the bottom of the time bar
- 'fit', 'previous', 'next', 'play', 'playextend', 'zoomin', 'zoomout' - control bar controls
- null - if there is nothing 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:
- 'area' - the area under the curve when in area mode
- 'bar' - a histogram bar
- 'selection' - a selection line point
- 'scale' - the time axis scale
- 'histo' - the histogram area between the sliders
- 'left', 'right' - sliders
- 'slider' - the areas outside the current slider range
- 'controlbar' - the control bar at the bottom of the time bar
- 'fit', 'previous', 'next', 'play', 'playextend', 'zoomin', 'zoomout' - control bar controls
- null - if there is nothing under the pointer
The pointer-up event fires when the pointer is released.
Default action: None
The type of item under the pointer:
- 'area' - the area under the curve when in area mode
- 'bar' - a histogram bar
- 'selection' - a selection line point
- 'scale' - the time axis scale
- 'histo' - the histogram area between the sliders
- 'left', 'right' - sliders
- 'slider' - the areas outside the current slider range
- 'controlbar' - the control bar at the bottom of the time bar
- 'fit', 'previous', 'next', 'play', 'playextend', 'zoomin', 'zoomout' - control bar controls
- null - if there is nothing 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:
- On the surface: Zooms in or out (animated)
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:
- 'dmy' - day-month-year
- 'mdy' - month-day-year
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.