Skip to main content

util

Functions

assign()

util.assign(destinationObject, [...sourceObjects])

Assigns own enumerable string keyed properties of source objects to the destination object. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

destinationObjectObjectThe destination object
[sourceObjects]Object[]The source objects

bindAll()

util.bindAll(object, methodNames)

Binds methods of an object to the object itself, overwriting the existing method.

objectObjectThe object to bind and assign the bound methods to
methodNamesstring|string[]The object method names to bind

breakText()

util.breakText(text, size [, attrs, opt])

Break the provided text into lines so that it can fit into the bounding box defined by size.width and (optionally) size.height.

The function creates a temporary SVG <text> element and adds words to it one by one, measuring the element's actual rendered width and height at every step. If a word causes a line to overflow size.width, a newline character ('\n') is generated. If a newline causes the text to overflow size.height, the string is cut off.

The returned string is a (possibly truncated) copy of text with newline characters at appropriate locations.

joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100 })
// 'lorem ipsum\ndolor sit amet\nconsectetur\nadipiscing elit'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 })
// 'lorem ipsum\ndolor sit amet'

The attrs parameter is an object with SVG attributes that should be set on the temporary SVG text element while it is being measured (such as 'font-weight', 'font-size', 'font-family', etc.). For example, an area of fixed size can obviously fit more words of font size 12px than it can fit words of font size 36px. If nothing can fit, an empty string is returned. (If an attrs object is not provided, the browser's default style is used.)

joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 12 })
// 'lorem ipsum dolor\nsit amet consectetur\nadipiscing elit'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 16 })
// 'lorem ipsum\ndolor sit amet'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 36 })
// 'lorem'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 72 })
// ''

The method also accepts the following additional options:

  • opt.separator - a string or a regular expression which denotes how to split the text into words. Defaults to ' '
  • opt.eol - a string representing the end-of-line symbol. Defaults to '\n'.
  • opt.ellipsis - a boolean that specifies whether the ellipsis symbol ('…', U+2026 HORIZONTAL ELLIPSIS) should be displayed when the text overflows. Defaults to false. If you provide a string, that string will be used as the ellipsis symbol instead.
  • opt.svgDocument - an SVG document to which the temporary SVG text element should be added. By default, an SVG document is created automatically for you.
  • opt.hyphen - a string or regex representing the hyphen symbol. If required, the method tries to break long words at hyphens first.
  • opt.maxLineCount - a number to limit the maximum number of lines.
  • opt.preserveSpaces - preserve the text spaces (avoid all consecutive spaces being deleted and replaced by one space, and preserve a space at the beginning and the end of the text).

Examples of text with the ellipsis option specified:

joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 12 }, { ellipsis: true })
// 'lorem ipsum dolor\nsit amet consectetur\nadipiscing elit'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 16 }, { ellipsis: true })
// 'lorem ipsum\ndolor sit ame…'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 16 }, { ellipsis: '...!?' })
// 'lorem ipsum\ndolor sit a...!?'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 36 }, { ellipsis: true })
// 'lore…'
joint.util.breakText('lorem ipsum dolor sit amet consectetur adipiscing elit', { width: 100, height: 50 }, { 'font-size': 36 }, { ellipsis: true })
// ''

If you need to wrap text inside a text attribute of an Element, you should use the textWrap attribute instead. It does not require you to provide explicit size measurements, and it automatically responds to element resizing.

camelCase()

util.camelCase([string=''])

Converts string to camel case.

[string='']stringThe string to convert

cancelFrame()

util.cancelFrame(requestId)

Cancels an animation frame request identified by requestId previously scheduled through a call to joint.util.nextFrame.

clone()

util.clone(value)

Creates a shallow clone of value.

valueanyThe value to clone

cloneDeep()

util.cloneDeep(value)

This method is like util.clone except that it recursively clones value.

valueanyThe value to recursively clone

dataUriToBlob()

util.dataUriToBlob(dataUri)

Convert a Data URI string into a Blob object.

debounce()

util.debounce(func, [wait=0], [options={}])

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.

funcFunctionThe function to debounce
[wait=0]numberThe number of milliseconds to delay
[options=]ObjectThe options object
[options.leading=false]booleanSpecify invoking on the leading edge of the timeout
[options.maxWait]numberThe maximum time func is allowed to be delayed before it's invoked
[options.trailing=true]booleanSpecify invoking on the trailing edge of the timeout

deepMixin()

util.deepMixin(destinationObject, [...sourceObjects])

(Deprecated) An alias for util.assign, use it instead.

deepSupplement()

util.deepSupplement(destinationObject [...sourceObjects])

(Deprecated) An alias for util.defaultsDeep, use it instead.

defaults()

util.defaults(destinationObject [...sourceObjects])

Assigns own and inherited enumerable string keyed properties of source objects to the destination object for all destination properties that resolve to undefined. Source objects are applied from left to right. Once a property is set, additional values of the same property are ignored.

destinationObjectObjectThe destination object
[sourceObjects]Object[]The source objects

defaultsDeep()

util.defaultsDeep(destinationObject [...sourceObjects])

This method is like util.defaults except that it recursively assigns default properties.

destinationObjectObjectThe destination object
[sourceObjects]Object[]The source objects

difference()

util.difference(array, [...values])

Creates an array of array values not included in the other given arrays using SameValueZero for equality comparisons. The order and references of result values are determined by the first array.

arrayany[]The array to inspect
[values]any[]The values to exclude

downloadBlob()

util.downloadBlob(blob, fileName)

Download provided Blob object as a file with given fileName.

downloadDataUri()

util.downloadDataUri(dataUri, fileName)

Download provided Data URI string as a file with given fileName.

flattenDeep()

util.flattenDeep(array)

Recursively flattens array.

arrayany[]The array to flatten

flattenObject()

util.flattenObject(object, delim, stop)

Flatten a nested object up until the stop function returns true. The stop function takes the value of the node currently traversed. delim is a delimiter for the combined keys in the resulting object. Example:

joint.util.flattenObject({
a: {
a1: 1,
a2: 2,
a3: {
a31: 5,
a32: {
a321: { a3211: 5 }
}
}
},
b: 6
}, '/', function(v) { return !!v.a321; });

/*
{
"a/a1": 1,
"a/a2": 2,
"a/a3/a31": 5,
"a/a3/a32": {
"a321": {
"a3211": 5
}
},
"b": 6
}
*/

forIn()

util.forIn(object, [iteratee])

Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

collectionany[]|ObjectThe collection to iterate over
[iteratee]FunctionThe function invoked per iteration

getByPath()

util.getByPath(object, path, delim)

Return a value at the path in a nested object. delim is the delimiter used in the path Example:

joint.util.getByPath({ a: { aa: { aaa: 3 } } }, 'a/aa/aaa', '/');
// 3

getElementBBox()

util.getElementBBox(el)

Return a bounding box of the element el. The advantage of this method is that it can handle both HTML and SVG elements. The resulting object is of the form { x: Number, y: Number, width: Number, height: Number }.

getRectPoint()

util.getRectPoint(rect, positionName)

Returns a g.Point on the rectangle specified by the keyword positionName. The rect object has the form { x: Number, y: Number, width: Number, height: Number }. The positionName keyword can be one of the following:

  • 'top-left'
  • 'top'
  • 'top-right'
  • 'bottom-left'
  • 'bottom'
  • 'bottom-right'
  • 'left'
  • 'right'
  • 'center'

groupBy()

util.groupBy(collection, [iteratee])

Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection. The corresponding value of each key is an array of elements responsible for generating the key. The iteratee is invoked with one argument: (value).

collectionany[]|ObjectThe collection to iterate over
[iteratee]FunctionThe function invoked per iteration

guid()

util.guid()

Return an identifier unique for the page.

has()

util.has(object, propertyPath)

Checks if path is a direct property of object.

objectObjectThe object to query
propertyPathstring[]|stringThe path to check

hashCode()

util.hashCode(str)

Return a simple hash code from a string.

imageToDataUri()

util.imageToDataUri(url, callback)

Convert an image at url to the Data URI scheme. The function is able to handle PNG, JPG and SVG formats. Useful if you need to embed images directly into your diagram instead of having them referenced externally.

The callback function has the following signature: function(err, dataUri) {}.

intersection()

util.intersection([...arrays])

Creates an array of unique values that are included in all given arrays using SameValueZero for equality comparisons. The order and references of result values are determined by the first array.

[arrays]any[][]The arrays to inspect

invoke()

util.invoke(collection, path, [args])

Invokes the method at path of each element in collection, returning an array of the results of each invoked method. Any additional arguments are provided to each invoked method. If path is a function, it's invoked for, and this bound to, each element in collection.

collectionany[]|ObjectThe collection to iterate over
pathstring[]|string|FunctionThe path of the method to invoke or the function invoked per iteration
[args]any[]The arguments to invoke each method with

invokeProperty()

util.invokeProperty(object, path, [args])

Invokes the method at path of object.

objectObjectThe object to query
pathstring[]|stringThe path of the method to invoke
[args]any[]The arguments to invoke the method with

isBoolean()

util.isBoolean(value)

Return true when value is a boolean.

isEmpty()

util.isEmpty(value)

Checks if value is an empty object, collection, map, or set.

Objects are considered empty if they have no own enumerable string keyed properties.

Array-like values such as arguments objects, arrays, strings, or jQuery-like collections are considered empty if they have a length of 0. Similarly, maps and sets are considered empty if they have a size of 0.

valueanyThe value to check

isEqual()

util.isEqual(value, otherValue)

Performs a deep comparison between two values to determine if they are equivalent.

valueanyThe value to compare
otherValueanyThe other value to compare

isFunction()

util.isFunction(value)

Checks if value is classified as a Function object.

valueanyThe value to check

isNumber()

util.isNumber(value)

Return true when value is a number.

isObject()

util.isObject(value)

Return true when value is an object (plain object or a function).

isPercentage()

util.isPercentage(value)

Return true when value is a string that holds a percentage value, e.g. '10%'.

isPlainObject()

util.isPlainObject(value)

Checks if value is a plain object, that is, an object created by the Object constructor or one with a [[Prototype]] of null.

valueanyThe value to check

isString()

util.isString(value)

Return true when value is a string.

merge()

util.merge(destinationObject, [...sourceObjects], [customizer])

This method is like joint.util.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources. In addition this method accepts a customizer which is invoked to produce the merged values of the destination and source properties. The customizer is invoked with six arguments: (objValue, srcValue, key, object, source, stack)

destinationObjectObjectThe destination object
[sourceObjects]Object[]The source objects
customizerFunctionThe function to customize assigned values

mixin()

util.mixin(destinationObject, [...sourceObjects])

(Deprecated) An alias for util.assign, use it instead.

nextFrame()

util.nextFrame(callback [, context, ...args])

Tell the browser to schedule the callback function to be called before the next repaint.

This is a cross-browser version of the window.requestAnimationFrame function. It returns an ID of the frame request.

You can optionally pass a context for your callback function. Any further arguments are passed as arguments to the callback function.

noop()

util.noop()

An empty function with no return statement (void in Typescript).

normalizeEvent()

util.normalizeEvent(evt)

Normalize the provided event.

For touch events, the normalized event receives a copy of all properties from evt.originalEvent that are not included in evt.

Additionally, if evt.target.correspondingUseElement is defined (as in IE), that element is assigned as target in the normalized event.

normalizeSides()

util.normalizeSides(box)

Return a new object of the form { top: Number, right: Number, bottom: Number, left: Number }.

If box is a number, the value of all four sides will be this number. If box is an object with some/all of the top, right, bottom, left properties defined, the values of these properties will be used.

Composite properties horizontal (for right and left side) and vertical (for top and bottom side) can be used, as well; they will be destructured appropriately. When two properties clash (e.g. horizontal: 10 and left: 5), the more specific one prevails (here the returned object would contain right: 10 and left: 5).

If any property is missing, its side will be set to 0 in the resulting object.

joint.util.normalizeSides() // { top: 0, right: 0, bottom: 0, left: 0 }
joint.util.normalizeSides(5) // { top: 5, right: 5, bottom: 5, left: 5 }
joint.util.normalizeSides({ horizontal: 5 }) // { top: 0, right: 5, bottom: 0, left: 5 }
joint.util.normalizeSides({ left: 5 }) // { top: 0, right: 0, bottom: 0, left: 5 }
joint.util.normalizeSides({ horizontal: 10, left: 5 }) // { top: 0, right: 10, bottom: 0, left: 5 }
joint.util.normalizeSides({ horizontal: 0, left: 5 }) // { top: 0, left: 5, right: 0, bottom: 0 }

JointJS and JointJS+ use this method internally whenever there is an option object that can be specified either by a number or a (possibly incomplete) object with sides (for example, the padding option).

omit()

util.omit(object, [...paths])

Opposite of util.pick, this method creates an object composed of the own and inherited enumerable property paths of object that are not omitted.

objectObjectThe source object
[paths]string[]|string[][]The property paths to omit

parseCssNumeric()

util.parseCssNumeric(value)

Parse the provided value as a float and return an object with the number as the value parameter. If the value cannot be converted into a number, return null.

If the number is followed by a unit, assign it as the unit parameter in the return object. If there is no unit, assign an empty string. Examples:

joint.util.parseCssNumeric('hello'); // => null

joint.util.parseCssNumeric(1.1); // => { value: 1.1, unit: '' }
joint.util.parseCssNumeric('1.1'); // => { value: 1.1, unit: '' }
joint.util.parseCssNumeric('1.1px'); // => { value: 1.1, unit: 'px' }
joint.util.parseCssNumeric('1.1em'); // => { value: 1.1, unit: 'em' }
util.parseCssNumeric(value, restrictUnits)

Parse the provided value and only accept it if its unit is part of the restrictUnits parameter; otherwise return null.

The restrictUnits parameter can be a string or an array of strings. If you provide an empty string, that means you are expecting value to have no unit. Providing an empty array always returns null. Examples:

joint.util.parseCssNumeric(1.1, ''); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1', ''); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1px', ''); // => null
joint.util.parseCssNumeric('1.1px', 'px'); // => { value: 1.1, unit: 'px' });
joint.util.parseCssNumeric('1.1px', 'em'); // => null

joint.util.parseCssNumeric(1.1, []); // => null
joint.util.parseCssNumeric('1.1', []); // => null
joint.util.parseCssNumeric('1.1px', []); // => null

joint.util.parseCssNumeric(1.1, ['']); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1', ['']); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1px', ['px']); // => { value: 1.1, unit: 'px' });
joint.util.parseCssNumeric('1.1px', ['em']); // => null

joint.util.parseCssNumeric(1.1, ['', 'px']); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1', ['', 'px']); // => { value: 1.1, unit: '' })
joint.util.parseCssNumeric('1.1px', ['', 'px']); // => { value: 1.1, unit: 'px' })
joint.util.parseCssNumeric('1.1em', ['', 'px']); // => null

pick()

util.pick(object, [...paths])

Creates an object composed of the picked object properties.

objectObjectThe source object
[paths]string[]|string[][]The property paths to pick

result()

util.result(object, path, [defaultValue])

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. If the resolved value is a function it's invoked with the this binding of its parent object and its result is returned.

objectObjectThe source object
pathstring|string[]The path of the property to get
[defaultValue]anyThe value returned for undefined resolved values

sanitizeHTML()

util.sanitizeHTML(html)

Sanitize the provided HTML (string) to protect against XSS attacks. The algorithm has several steps:

  • Wrap the provided HTML inside a <div> tag. This will remove tags that are invalid in that context (e.g. <body> and <head>).
  • Parse the provided HTML in a new document context. This prevents inline events from firing and also prevents image GET requests from being sent.
  • Discard all <script> tags.
  • Iterate through all DOM nodes and remove all on... attributes (e.g. onload, onerror).
  • Iterate through all attributes of the nodes and remove all that use the javascript: pseudo-protocol as value.
  • Return the sanitized HTML back as a string.

The six simple steps protect against the most common XSS attacks; however, we cannot guarantee bulletproof security here. If you need stronger security, you should always keep an eye on a list XSS attacks and replace the joint.util.sanitizeHTML() function with your own, more secure version.

Examples:

joint.util.sanitizeHTML('<html><body><p>Hello</p></body></html>'); // => '<p>Hello</p>'
joint.util.sanitizeHTML('<p>Hello</p><script>alert("Hacked");</script>'); // => '<p>Hello</p>'
joint.util.sanitizeHTML('<p>Hello</p><img onload="alert(&quot;Hacked&quot;);"/>'); // => '<p>Hello</p><img/>'
joint.util.sanitizeHTML('<p>Hello</p><img src="javascript:alert(&quot;Hacked&quot;);"/>'); // => '<p>Hello</p><img/>'

setAttributesBySelector()

util.setAttributesBySelector(el, attrs)

Set attributes on the DOM element (SVG or HTML) el and its descendants based on the selector in the attrs object. The attrs object is of the form: { [selector]: [attributes }. For example:

var myEl = document.querySelector('.mydiv');
joint.util.setAttributesBySelector(myEl, {
'.myDiv': { 'data-foo': 'bar' }, // Note the reference to the myEl element itself.
'input': { 'value': 'my value' }
});

The code above sets 'data-foo' attribute of the myEl element to the value 'bar' and 'value' attribute of all the descendant inputs to the value 'my value'. This is a convenient way of setting attributes on elements (including themselves) and their descendants. Note that 'class' attribute is treated as a special case and its value does not override the previous value of the 'class' attribute. Instead, it adds this new class to the list of classes for the element referenced in the selector.

setByPath()

util.setByPath(object, path, value, delim)

Set a value at the path in a nested object. delim is the delimiter used in the path. Returns the augmented object.

joint.util.setByPath({ a: 1 }, 'b/bb/bbb', 2, '/');
/*
{
"a": 1,
"b": {
"bb": {
"bbb": 2
}
}
}
*/

sortBy()

util.sortBy(collection, [iteratees])

Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).

collectionany[]|ObjectThe collection to iterate over
[iteratees]Funtion|Funtion[]The iteratees to sort by

sortElements()

util.sortElements(elements, comparator)

Change the order of elements (a collection of HTML elements or a selector) in the DOM according to the comparator(elementA, elementB) function. The comparator function has the exact same meaning as in Array.prototype.sort(comparator). The function returns the sorted array of elements.

sortedIndex()

util.sortedIndex(array, value, [iteratee])

Uses a binary search to determine the lowest index at which value should be inserted into array in order to maintain its sort order. In addition this method accepts iteratee which is invoked for value and each element of array to compute their sort ranking. The iteratee is invoked with one argument: (value)

arrayany[]The sorted array to inspect
valueanyThe value to evaluate
[iteratee]FunctionThe iteratee invoked per element

supplement()

util.supplement(destinationObject [...sourceObjects])

(Deprecated) An alias for util.defaults, use it instead.

svg()

svg(strings)

This is the tagged template which converts a string into a markup object while declaring a Cell. The resulting object contains fields which are described in this part of the documentation. SVG is converted into JSON markup as follows:

PropertyRepresentation
tagNameSVG tag name.
selector@selector attribute.
groupSelector@group-selector attribute. Accepts comma-separated lists e.g. @group-selector="group1, group2".
namespaceURIThe namespace URI of the element. It defaults to the SVG namespace "http://www.w3.org/2000/svg".
attributesAttributes of the element.
styleThe style attribute of the element parsed as key-value pairs.
classNameThe class attribute of the element.
childrenThe children of the element.

Text nodes are placed into the children array as strings. For example, the markup <span>a<span>b</span></span> is converted to { tagName: 'span', children: ['a', { tagName: 'span', children: ['b']}]}.

template()

util.template(html)

Return a template function that returns pre-compiled html when called.

toArray()

util.toArray(value)

Converts value to an array.

valueanyThe value to convert

toKebabCase()

util.toKebabCase(str)

Convert the string to kebab-case. Example:

joint.util.toKebabCase('strokeWidth'); // => 'stroke-width'

toggleFullScreen()

util.toggleFullScreen([element])

Make (or cancel) an element to be displayed full-screen. The default element is window.top.document.body.

joint.util.toggleFullScreen(paper.el);

union()

util.union([...arrays])

Creates an array of unique values, in order, from all given arrays using SameValueZero for equality comparisons.

[arrays]any[]The arrays to inspect

uniq()

util.uniq(array, [iteratee])

Creates a duplicate-free version of an array, using SameValueZero for equality comparisons, in which only the first occurrence of each element is kept. The order of result values is determined by the order they occur in the array. In addition this method accepts iteratee which is invoked for each element in array to generate the criterion by which uniqueness is computed. The order of result values is determined by the order they occur in the array. The iteratee is invoked with one argument: (value).

arrayany[]The array to inspect
[iteratee]FunctionThe iteratee invoked per element

uniqueId()

util.uniqueId([prefix])

Generates a unique ID. If prefix is given, the ID is appended to it.

[prefix]stringThe prefix of the ID

unsetByPath()

util.unsetByPath(object, path, delim)

Unset (delete) a property at the path in a nested object. delim is the delimiter used in the path. Returns the augmented object.

joint.util.unsetByPath({ a: { aa: { aaa: 3 } } }, 'a/aa/aaa', '/');
// { a: { aa: {} } }

uuid()

util.uuid()

Return a pseudo-UUID.

without()

util.without(array, [...values])

Creates an array excluding all given values using SameValueZero for equality comparisons.

arrayany[]The array to inspect
[values]any[]The values to exclude