mxUtils

A singleton class that provides cross-browser helper methods.  This is a global functionality.  To access the functions in this class, use the global classname appended by the functionname.  You may have to load chrome://global/content/contentAreaUtils.js to disable certain security restrictions in Mozilla for the open, save, saveAs and copy function.

For example, the following code displays an error message

mxUtils.error('Browser is not supported!', 200, false);
Summary
mxUtilsA singleton class that provides cross-browser helper methods.
Variables
errorResourceSpecifies the resource key for the title of the error window.
closeResourceSpecifies the resource key for the label of the close button.
errorImageDefines the image used for error dialogs.
Functions
removeCursorsRemoves the cursors from the style of the given DOM node and its descendants.
getCurrentStyleReturns the current style of the specified element.
setPrefixedStyleAdds the given style with the standard name and an optional vendor prefix for the current browser.
hasScrollbarsReturns true if the overflow CSS property of the given node is either scroll or auto.
bindReturns a wrapper function that locks the execution scope of the given function to the specified scope.
evalEvaluates the given expression using eval and returns the JavaScript object that represents the expression result.
findNodeReturns the first node where attr equals value.
findNodeByAttributeReturns the first node where the given attribute matches the given value.
getFunctionNameReturns the name for the given function.
indexOfReturns the index of obj in array or -1 if the array does not contains the given object.
removeRemoves all occurrences of the given object in the given array or object.
isNodeReturns true if the given value is an XML node with the node name and if the optional attribute has the specified value.
getChildNodesReturns an array of child nodes that are of the given node type.
createXmlDocumentReturns a new, empty XML document.
parseXmlParses the specified XML string into a new XML document and returns the new document.
clearSelectionClears the current selection in the page.
getPrettyXMLReturns a pretty printed string that represents the XML tree for the given node.
removeWhitespaceRemoves the sibling text nodes for the given node that only consists of tabs, newlines and spaces.
htmlEntitiesReplaces characters (less than, greater than, newlines and quotes) with their HTML entities in the given string and returns the result.
isVmlReturns true if the given node is in the VML namespace.
getXmlReturns the XML content of the specified node.
getTextContentReturns the text content of the specified node.
getInnerHtmlReturns the inner HTML for the given node as a string or an empty string if no node was specified.
getOuterHtmlReturns the outer HTML for the given node as a string or an empty string if no node was specified.
writeCreates a text node for the given string and appends it to the given parent.
writelnCreates a text node for the given string and appends it to the given parent with an additional linefeed.
brAppends a linebreak to the given parent and returns the linebreak.
buttonReturns a new button with the given level and function as an onclick event handler.
paraAppends a new paragraph with the given text to the specified parent and returns the paragraph.
addTransparentBackgroundFilterAdds a transparent background to the filter of the given node.
linkActionAdds a hyperlink to the specified parent that invokes action on the specified editor.
linkInvokeAdds a hyperlink to the specified parent that invokes the specified function on the editor passing along the specified argument.
linkAdds a hyperlink to the specified parent and invokes the given function when the link is clicked.
fitMakes sure the given node is inside the visible area of the window.
openOpens the specified file from the local filesystem and returns the contents of the file as a string.
saveSaves the specified content in the given file on the local file system.
saveAsSaves the specified content by displaying a dialog to save the content as a file on the local filesystem.
copyCopies the specified content to the local clipboard.
loadLoads the specified URL synchronously and returns the mxXmlRequest.
getLoads the specified URL asynchronously and invokes the given functions depending on the request status.
postPosts the specified params to the given URL asynchronously and invokes the given functions depending on the request status.
submitSubmits the given parameters to the specified URL using mxXmlRequest.simulate and returns the mxXmlRequest.
loadIntoLoads the specified URL asynchronously into the specified document, invoking onload after the document has been loaded.
getValueReturns the value for the given key in the given associative array or the given default value if the value is null.
getNumberReturns the numeric value for the given key in the given associative array or the given default value (or 0) if the value is null.
getColorReturns the color value for the given key in the given associative array or the given default value if the value is null.
cloneRecursively clones the specified object ignoring all fieldnames in the given array of transient fields.
equalPointsCompares all mxPoints in the given lists.
equalEntriesReturns true if all entries of the given objects are equal.
isNaNReturns true if the given value is of type number and isNaN returns true.
extendAssigns a copy of the superclass prototype to the subclass prototype.
toStringReturns a textual representation of the specified object.
toRadiansConverts the given degree to radians.
arcToCurvesConverts the given arc to a series of curves.
getBoundingBoxReturns the bounding box for the rotated rectangle.
getRotatedPointRotates the given point by the given cos and sin.
reversePortConstraintsReverse the port constraint bitmask.
findNearestSegmentFinds the index of the nearest segment on the given cell state for the specified coordinate pair.
rectangleIntersectsSegmentReturns true if the given rectangle intersects the given segment.
containsReturns true if the specified point (x, y) is contained in the given rectangle.
intersectsReturns true if the two rectangles intersect.
intersectsReturns true if the two rectangles intersect.
getOffsetReturns the offset for the specified container as an mxPoint.
getScrollOriginReturns the top, left corner of the viewrect as an mxPoint.
convertPointConverts the specified point (x, y) using the offset of the specified container and returns a new mxPoint with the result.
ltrimStrips all whitespaces from the beginning of the string.
rtrimStrips all whitespaces from the end of the string.
trimStrips all whitespaces from both end of the string.
isNumericReturns true if the specified value is numeric, that is, if it is not null, not an empty string, not a HEX number and isNaN returns false.
modReturns the remainder of division of n by m.
intersectionReturns the intersection of two lines as an mxPoint.
ptSeqDistSqReturns the square distance between a segment and a point.
relativeCcwReturns 1 if the given point on the right side of the segment, 0 if its on the segment, and -1 if the point is on the left side of the segment.
animateChangesSee mxEffects.animateChanges.
cascadeOpacitySee mxEffects.cascadeOpacity.
fadeOutSee mxEffects.fadeOut.
setOpacitySets the opacity of the specified DOM node to the given value in %.
createImageCreates and returns an image (IMG node) or VML image (v:image) in IE6 in quirks mode.
sortCellsSorts the given cells according to the order in the cell hierarchy.
getStylenameReturns the stylename in a style of the form [(stylename|key=value);] or an empty string if the given style does not contain a stylename.
getStylenamesReturns the stylenames in a style of the form [(stylename|key=value);] or an empty array if the given style does not contain any stylenames.
indexOfStylenameReturns the index of the given stylename in the given style.
addStylenameAdds the specified stylename to the given style if it does not already contain the stylename.
removeStylenameRemoves all occurrences of the specified stylename in the given style and returns the updated style.
removeAllStylenamesRemoves all stylenames from the given style and returns the updated style.
setCellStylesAssigns the value for the given key in the styles of the given cells, or removes the key from the styles if the value is null.
setStyleAdds or removes the given key, value pair to the style and returns the new style.
setCellStyleFlagsSets or toggles the flag bit for the given key in the cell’s styles.
setStyleFlagSets or removes the given key from the specified style and returns the new style.
getAlignmentAsPointReturns an mxPoint that represents the horizontal and vertical alignment for numeric computations.
getSizeForStringReturns an mxRectangle with the size (width and height in pixels) of the given string.
getViewXml
getScaleForPageCountReturns the scale to be used for printing the graph with the given bounds across the specifies number of pages with the given format.
showCopies the styles and the markup from the graph’s container into the given document and removes all cursor styles.
printScreenPrints the specified graph using a new window and the built-in print dialog.
popupShows the specified text content in a new mxWindow or a new browser window if isInternalWindow is false.
alertDisplayss the given alert in a new dialog.
promptDisplays the given message in a prompt dialog.
confirmDisplays the given message in a confirm dialog.
errorDisplays the given error message in a new mxWindow of the given width.
makeDraggableConfigures the given DOM element to act as a drag source for the specified graph.

Variables

errorResource

Specifies the resource key for the title of the error window.  If the resource for this key does not exist then the value is used as the title.  Default is ‘error’.

closeResource

Specifies the resource key for the label of the close button.  If the resource for this key does not exist then the value is used as the label.  Default is ‘close’.

errorImage

Defines the image used for error dialogs.

Functions

removeCursors

removeCursors: function(element)

Removes the cursors from the style of the given DOM node and its descendants.

Parameters

elementDOM node to remove the cursor style from.

getCurrentStyle

getCurrentStyle: function()

Returns the current style of the specified element.

Parameters

elementDOM node whose current style should be returned.

setPrefixedStyle

setPrefixedStyle: function()

Adds the given style with the standard name and an optional vendor prefix for the current browser.

mxUtils.setPrefixedStyle(node.style, 'transformOrigin', '0% 0%');

hasScrollbars

hasScrollbars: function(node)

Returns true if the overflow CSS property of the given node is either scroll or auto.

Parameters

nodeDOM node whose style should be checked for scrollbars.

bind

bind: function(scope,
funct)

Returns a wrapper function that locks the execution scope of the given function to the specified scope.  Inside funct, the “this” keyword becomes a reference to that scope.

eval

eval: function(expr)

Evaluates the given expression using eval and returns the JavaScript object that represents the expression result.  Supports evaluation of expressions that define functions and returns the function object for these expressions.

Parameters

exprA string that represents a JavaScript expression.

findNode

findNode: function(node,
attr,
value)

Returns the first node where attr equals value.  This implementation does not use XPath.

findNodeByAttribute

findNodeByAttribute: function()

Returns the first node where the given attribute matches the given value.

Parameters

nodeRoot node where the search should start.
attrName of the attribute to be checked.
valueValue of the attribute to match.

getFunctionName

getFunctionName: function(f)

Returns the name for the given function.

Parameters

fJavaScript object that represents a function.

indexOf

indexOf: function(array,
obj)

Returns the index of obj in array or -1 if the array does not contains the given object.

Parameters

arrayArray to check for the given obj.
objObject to find in the given array.

remove

remove: function(obj,
array)

Removes all occurrences of the given object in the given array or object.  If there are multiple occurrences of the object, be they associative or as an array entry, all occurrences are removed from the array or deleted from the object.  By removing the object from the array, all elements following the removed element are shifted by one step towards the beginning of the array.

The length of arrays is not modified inside this function.

Parameters

objObject to find in the given array.
arrayArray to check for the given obj.

isNode

isNode: function(value,
nodeName,
attributeName,
attributeValue)

Returns true if the given value is an XML node with the node name and if the optional attribute has the specified value.

This implementation assumes that the given value is a DOM node if the nodeType property is numeric, that is, if isNaN returns false for value.nodeType.

Parameters

valueObject that should be examined as a node.
nodeNameString that specifies the node name.
attributeNameOptional attribute name to check.
attributeValueOptional attribute value to check.

getChildNodes

getChildNodes: function(node,
nodeType)

Returns an array of child nodes that are of the given node type.

Parameters

nodeParent DOM node to return the children from.
nodeTypeOptional node type to return.  Default is mxConstants.NODETYPE_ELEMENT.

createXmlDocument

createXmlDocument: function()

Returns a new, empty XML document.

parseXml

parseXml: function()

Parses the specified XML string into a new XML document and returns the new document.

Example

var doc = mxUtils.parseXml(
  '<mxGraphModel><root><MyDiagram id="0"><mxCell/></MyDiagram>'+
  '<MyLayer id="1"><mxCell parent="0" /></MyLayer><MyObject id="2">'+
  '<mxCell style="strokeColor=blue;fillColor=red" parent="1" vertex="1">'+
  '<mxGeometry x="10" y="10" width="80" height="30" as="geometry"/>'+
  '</mxCell></MyObject></root></mxGraphModel>');

Parameters

xmlString that contains the XML data.

clearSelection

clearSelection: function()

Clears the current selection in the page.

getPrettyXML

Returns a pretty printed string that represents the XML tree for the given node.  This method should only be used to print XML for reading, use getXml instead to obtain a string for processing.

Parameters

nodeDOM node to return the XML for.
tabOptional string that specifies the indentation for one level.  Default is two spaces.
indentOptional string that represents the current indentation.  Default is an empty string.

removeWhitespace

removeWhitespace: function(node,
before)

Removes the sibling text nodes for the given node that only consists of tabs, newlines and spaces.

Parameters

nodeDOM node whose siblings should be removed.
beforeOptional boolean that specifies the direction of the traversal.

htmlEntities

htmlEntities: function(s,
newline)

Replaces characters (less than, greater than, newlines and quotes) with their HTML entities in the given string and returns the result.

Parameters

sString that contains the characters to be converted.
newlineIf newlines should be replaced.  Default is true.

isVml

isVml: function(node)

Returns true if the given node is in the VML namespace.

Parameters

nodeDOM node whose tag urn should be checked.

getXml

getXml: function(node,
linefeed)

Returns the XML content of the specified node.  For Internet Explorer, all \r\n\t[\t]* are removed from the XML string and the remaining \r\n are replaced by \n.  All \n are then replaced with linefeed, or &#xa; if no linefeed is defined.

Parameters

nodeDOM node to return the XML for.
linefeedOptional string that linefeeds are converted into.  Default is &#xa;

getTextContent

getTextContent: function(node)

Returns the text content of the specified node.

Parameters

nodeDOM node to return the text content for.

getInnerHtml

getInnerHtml: function()

Returns the inner HTML for the given node as a string or an empty string if no node was specified.  The inner HTML is the text representing all children of the node, but not the node itself.

Parameters

nodeDOM node to return the inner HTML for.

getOuterHtml

getOuterHtml: function()

Returns the outer HTML for the given node as a string or an empty string if no node was specified.  The outer HTML is the text representing all children of the node including the node itself.

Parameters

nodeDOM node to return the outer HTML for.

write

write: function(parent,
text)

Creates a text node for the given string and appends it to the given parent.  Returns the text node.

Parameters

parentDOM node to append the text node to.
textString representing the text to be added.

writeln

writeln: function(parent,
text)

Creates a text node for the given string and appends it to the given parent with an additional linefeed.  Returns the text node.

Parameters

parentDOM node to append the text node to.
textString representing the text to be added.

br

br: function(parent,
count)

Appends a linebreak to the given parent and returns the linebreak.

Parameters

parentDOM node to append the linebreak to.

button

button: function(label,
funct,
doc)

Returns a new button with the given level and function as an onclick event handler.

document.body.appendChild(mxUtils.button('Test', function(evt)
{
  alert('Hello, World!');
}));

Parameters

labelString that represents the label of the button.
functFunction to be called if the button is pressed.
docOptional document to be used for creating the button.  Default is the current document.

para

para: function(parent,
text)

Appends a new paragraph with the given text to the specified parent and returns the paragraph.

Parameters

parentDOM node to append the text node to.
textString representing the text for the new paragraph.

addTransparentBackgroundFilter

addTransparentBackgroundFilter: function(node)

Adds a transparent background to the filter of the given node.  This background can be used in IE8 standards mode (native IE8 only) to pass events through the node.

linkAction

linkAction: function(parent,
text,
editor,
action,
pad)

Adds a hyperlink to the specified parent that invokes action on the specified editor.

Parameters

parentDOM node to contain the new link.
textString that is used as the link label.
editormxEditor that will execute the action.
actionString that defines the name of the action to be executed.
padOptional left-padding for the link.  Default is 0.

linkInvoke

linkInvoke: function(parent,
text,
editor,
functName,
arg,
pad)

Adds a hyperlink to the specified parent that invokes the specified function on the editor passing along the specified argument.  The function name is the name of a function of the editor instance, not an action name.

Parameters

parentDOM node to contain the new link.
textString that is used as the link label.
editormxEditor instance to execute the function on.
functNameString that represents the name of the function.
argObject that represents the argument to the function.
padOptional left-padding for the link.  Default is 0.

link

link: function(parent,
text,
funct,
pad)

Adds a hyperlink to the specified parent and invokes the given function when the link is clicked.

Parameters

parentDOM node to contain the new link.
textString that is used as the link label.
functFunction to execute when the link is clicked.
padOptional left-padding for the link.  Default is 0.

fit

fit: function(node)

Makes sure the given node is inside the visible area of the window.  This is done by setting the left and top in the style.

open

open: function(filename)

Opens the specified file from the local filesystem and returns the contents of the file as a string.  This implementation requires an ActiveX object in IE and special privileges in Firefox.  Relative filenames are only supported in IE and will go onto the users’ Desktop.  You may have to load chrome://global/content/contentAreaUtils.js to disable certain security restrictions in Mozilla for this to work.

See known-issues before using this function.

Example

var data = mxUtils.open('C:\\temp\\test.txt');
mxUtils.alert('Data: '+data);

Parameters

filenameString representing the local file name.

save

save: function(filename,
content)

Saves the specified content in the given file on the local file system.  This implementation requires an ActiveX object in IE and special privileges in Firefox.  Relative filenames are only supported in IE and will be loaded from the users’ Desktop.  You may have to load chrome://global/content/contentAreaUtils.js to disable certain security restrictions in Mozilla for this to work.

See known-issues before using this function.

Example

var data = 'Hello, World!';
mxUtils.save('C:\\test.txt', data);

Parameters

filenameString representing the local file name.

saveAs

saveAs: function(content)

Saves the specified content by displaying a dialog to save the content as a file on the local filesystem.  This implementation does not use an ActiveX object in IE, however, it does require special privileges in Firefox.  You may have to load chrome://global/content/contentAreaUtils.js to disable certain security restrictions in Mozilla for this to work.

See known-issues before using this function.  It is not recommended using this function in production environment as access to the filesystem cannot be guaranteed in Firefox.  The following code is used in Firefox to try and enable saving to the filesystem.

netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

Example

mxUtils.saveAs('Hello, World!');

Parameters

contentString representing the file’s content.

copy

copy: function(content)

Copies the specified content to the local clipboard.  This implementation requires special privileges in Firefox.  You may have to load chrome://global/content/contentAreaUtils.js to disable certain security restrictions in Mozilla for this to work.

Parameters

contentString to be copied to the clipboard.

load

load: function(url)

Loads the specified URL synchronously and returns the mxXmlRequest.  Throws an exception if the file cannot be loaded.  See mxUtils.get for an asynchronous implementation.

Example

try
{
  var req = mxUtils.load(filename);
  var root = req.getDocumentElement();
  // Process XML DOM...
}
catch (ex)
{
  mxUtils.alert('Cannot load '+filename+': '+ex);
}

Parameters

urlURL to get the data from.

get

get: function(url,
onload,
onerror)

Loads the specified URL asynchronously and invokes the given functions depending on the request status.  Returns the mxXmlRequest in use.  Both functions take the mxXmlRequest as the only parameter.  See mxUtils.load for a synchronous implementation.

Example

mxUtils.get(url, function(req)
{
   var node = req.getDocumentElement();
   // Process XML DOM...
});

So for example, to load a diagram into an existing graph model, the following code is used.

mxUtils.get(url, function(req)
{
  var node = req.getDocumentElement();
  var dec = new mxCodec(node.ownerDocument);
  dec.decode(node, graph.getModel());
});

Parameters

urlURL to get the data from.
onloadOptional function to execute for a successful response.
onerrorOptional function to execute on error.

post

post: function(url,
params,
onload,
onerror)

Posts the specified params to the given URL asynchronously and invokes the given functions depending on the request status.  Returns the mxXmlRequest in use.  Both functions take the mxXmlRequest as the only parameter.  Make sure to use encodeURIComponent for the parameter values.

Example

mxUtils.post(url, 'key=value', function(req)
{
 mxUtils.alert('Ready: '+req.isReady()+' Status: '+req.getStatus());
 // Process req.getDocumentElement() using DOM API if OK...
});

Parameters

urlURL to get the data from.
paramsParameters for the post request.
onloadOptional function to execute for a successful response.
onerrorOptional function to execute on error.

submit

submit: function(url,
params,
doc,
target)

Submits the given parameters to the specified URL using mxXmlRequest.simulate and returns the mxXmlRequest.  Make sure to use encodeURIComponent for the parameter values.

Parameters

urlURL to get the data from.
paramsParameters for the form.
docDocument to create the form in.
targetTarget to send the form result to.

loadInto

loadInto: function(url,
doc,
onload)

Loads the specified URL asynchronously into the specified document, invoking onload after the document has been loaded.  This implementation does not use mxXmlRequest, but the document.load method.

Parameters

urlURL to get the data from.
docThe document to load the URL into.
onloadFunction to execute when the URL has been loaded.

getValue

getValue: function(array,
key,
defaultValue)

Returns the value for the given key in the given associative array or the given default value if the value is null.

Parameters

arrayAssociative array that contains the value for the key.
keyKey whose value should be returned.
defaultValueValue to be returned if the value for the given key is null.

getNumber

getNumber: function(array,
key,
defaultValue)

Returns the numeric value for the given key in the given associative array or the given default value (or 0) if the value is null.  The value is converted to a numeric value using the Number function.

Parameters

arrayAssociative array that contains the value for the key.
keyKey whose value should be returned.
defaultValueValue to be returned if the value for the given key is null.  Default is 0.

getColor

getColor: function(array,
key,
defaultValue)

Returns the color value for the given key in the given associative array or the given default value if the value is null.  If the value is mxConstants.NONE then null is returned.

Parameters

arrayAssociative array that contains the value for the key.
keyKey whose value should be returned.
defaultValueValue to be returned if the value for the given key is null.  Default is null.

clone

clone: function(obj,
transients,
shallow)

Recursively clones the specified object ignoring all fieldnames in the given array of transient fields.  mxObjectIdentity.FIELD_NAME is always ignored by this function.

Parameters

objObject to be cloned.
transientsOptional array of strings representing the fieldname to be ignored.
shallowOptional boolean argument to specify if a shallow clone should be created, that is, one where all object references are not cloned or, in other words, one where only atomic (strings, numbers) values are cloned.  Default is false.

equalPoints

equalPoints: function(a,
b)

Compares all mxPoints in the given lists.

Parameters

aArray of mxPoints to be compared.
bArray of mxPoints to be compared.

equalEntries

equalEntries: function(a,
b)

Returns true if all entries of the given objects are equal.  Values with with Number.NaN are equal to Number.NaN and unequal to any other value.

Parameters

amxRectangle to be compared.
bmxRectangle to be compared.

isNaN

isNaN: function(value)

Returns true if the given value is of type number and isNaN returns true.

extend

extend: function(ctor,
superCtor)

Assigns a copy of the superclass prototype to the subclass prototype.  Note that this does not call the constructor of the superclass at this point, the superclass constructor should be called explicitely in the subclass constructor.  Below is an example.

MyGraph = function(container, model, renderHint, stylesheet)
{
  mxGraph.call(this, container, model, renderHint, stylesheet);
}

mxUtils.extend(MyGraph, mxGraph);

Parameters

ctorConstructor of the subclass.
superCtorConstructor of the superclass.

toString

toString: function(obj)

Returns a textual representation of the specified object.

Parameters

objObject to return the string representation for.

toRadians

toRadians: function(deg)

Converts the given degree to radians.

arcToCurves

arcToCurves: function(x0,
y0,
r1,
r2,
angle,
largeArcFlag,
sweepFlag,
x,
y)

Converts the given arc to a series of curves.

getBoundingBox

getBoundingBox: function(rect,
rotation)

Returns the bounding box for the rotated rectangle.

getRotatedPoint

getRotatedPoint: function(pt,
cos,
sin,
c)

Rotates the given point by the given cos and sin.

reversePortConstraints

reversePortConstraints: function(constraint)

Reverse the port constraint bitmask.  For example, north | east becomes south | west

findNearestSegment

findNearestSegment: function(state,
x,
y)

Finds the index of the nearest segment on the given cell state for the specified coordinate pair.

rectangleIntersectsSegment

rectangleIntersectsSegment: function(bounds,
p1,
p2)

Returns true if the given rectangle intersects the given segment.

Parameters

boundsmxRectangle that represents the rectangle.
p1mxPoint that represents the first point of the segment.
p2mxPoint that represents the second point of the segment.

contains

contains: function(bounds,
x,
y)

Returns true if the specified point (x, y) is contained in the given rectangle.

Parameters

boundsmxRectangle that represents the area.
xX-coordinate of the point.
yY-coordinate of the point.

intersects

intersects: function(a,
b)

Returns true if the two rectangles intersect.

Parameters

amxRectangle to be checked for intersection.
bmxRectangle to be checked for intersection.

intersects

intersectsHotspot: function(state,
x,
y,
hotspot,
min,
max)

Returns true if the two rectangles intersect.

Parameters

amxRectangle to be checked for intersection.
bmxRectangle to be checked for intersection.

getOffset

getOffset: function(container,
scrollOffset)

Returns the offset for the specified container as an mxPoint.  The offset is the distance from the top left corner of the container to the top left corner of the document.

Parameters

containerDOM node to return the offset for.
scollOffsetOptional boolean to add the scroll offset of the document.  Default is false.

getScrollOrigin

getScrollOrigin: function(node)

Returns the top, left corner of the viewrect as an mxPoint.

convertPoint

convertPoint: function(container,
x,
y)

Converts the specified point (x, y) using the offset of the specified container and returns a new mxPoint with the result.

var pt = mxUtils.convertPoint(graph.container,
  mxEvent.getClientX(evt), mxEvent.getClientY(evt));

Parameters

containerDOM node to use for the offset.
xX-coordinate of the point to be converted.
yY-coordinate of the point to be converted.

ltrim

ltrim: function(str,
chars)

Strips all whitespaces from the beginning of the string.  Without the second parameter, Javascript function will trim these characters:

  • ” “ (ASCII 32 (0x20)), an ordinary space
  • ”\t” (ASCII 9 (0x09)), a tab
  • ”\n” (ASCII 10 (0x0A)), a new line (line feed)
  • ”\r” (ASCII 13 (0x0D)), a carriage return
  • ”\0” (ASCII 0 (0x00)), the NUL-byte
  • ”\x0B” (ASCII 11 (0x0B)), a vertical tab

rtrim

rtrim: function(str,
chars)

Strips all whitespaces from the end of the string.  Without the second parameter, Javascript function will trim these characters:

  • ” “ (ASCII 32 (0x20)), an ordinary space
  • ”\t” (ASCII 9 (0x09)), a tab
  • ”\n” (ASCII 10 (0x0A)), a new line (line feed)
  • ”\r” (ASCII 13 (0x0D)), a carriage return
  • ”\0” (ASCII 0 (0x00)), the NUL-byte
  • ”\x0B” (ASCII 11 (0x0B)), a vertical tab

trim

trim: function(str,
chars)

Strips all whitespaces from both end of the string.  Without the second parameter, Javascript function will trim these characters:

  • ” “ (ASCII 32 (0x20)), an ordinary space
  • ”\t” (ASCII 9 (0x09)), a tab
  • ”\n” (ASCII 10 (0x0A)), a new line (line feed)
  • ”\r” (ASCII 13 (0x0D)), a carriage return
  • ”\0” (ASCII 0 (0x00)), the NUL-byte
  • ”\x0B” (ASCII 11 (0x0B)), a vertical tab

isNumeric

isNumeric: function(str)

Returns true if the specified value is numeric, that is, if it is not null, not an empty string, not a HEX number and isNaN returns false.

Parameters

strString representing the possibly numeric value.

mod

mod: function(n,
m)

Returns the remainder of division of n by m.  You should use this instead of the built-in operation as the built-in operation does not properly handle negative numbers.

intersection

intersection: function (x0,
y0,
x1,
y1,
x2,
y2,
x3,
y3)

Returns the intersection of two lines as an mxPoint.

Parameters

x0X-coordinate of the first line’s startpoint.
y0X-coordinate of the first line’s startpoint.
x1X-coordinate of the first line’s endpoint.
y1Y-coordinate of the first line’s endpoint.
x2X-coordinate of the second line’s startpoint.
y2Y-coordinate of the second line’s startpoint.
x3X-coordinate of the second line’s endpoint.
y3Y-coordinate of the second line’s endpoint.

ptSeqDistSq

Returns the square distance between a segment and a point.

Parameters

x1X-coordinate of the startpoint of the segment.
y1Y-coordinate of the startpoint of the segment.
x2X-coordinate of the endpoint of the segment.
y2Y-coordinate of the endpoint of the segment.
pxX-coordinate of the point.
pyY-coordinate of the point.

relativeCcw

relativeCcw: function(x1,
y1,
x2,
y2,
px,
py)

Returns 1 if the given point on the right side of the segment, 0 if its on the segment, and -1 if the point is on the left side of the segment.

Parameters

x1X-coordinate of the startpoint of the segment.
y1Y-coordinate of the startpoint of the segment.
x2X-coordinate of the endpoint of the segment.
y2Y-coordinate of the endpoint of the segment.
pxX-coordinate of the point.
pyY-coordinate of the point.

animateChanges

animateChanges: function(graph,
changes)

See mxEffects.animateChanges.  This is for backwards compatibility and will be removed later.

cascadeOpacity

cascadeOpacity: function(graph,
cell,
opacity)

See mxEffects.cascadeOpacity.  This is for backwards compatibility and will be removed later.

fadeOut

fadeOut: function(node,
from,
remove,
step,
delay,
isEnabled)

See mxEffects.fadeOut.  This is for backwards compatibility and will be removed later.

setOpacity

setOpacity: function(node,
value)

Sets the opacity of the specified DOM node to the given value in %.

Parameters

nodeDOM node to set the opacity for.
valueOpacity in %.  Possible values are between 0 and 100.

createImage

createImage: function(src)

Creates and returns an image (IMG node) or VML image (v:image) in IE6 in quirks mode.

Parameters

srcURL that points to the image to be displayed.

sortCells

sortCells: function(cells,
ascending)

Sorts the given cells according to the order in the cell hierarchy.  Ascending is optional and defaults to true.

getStylename

getStylename: function(style)

Returns the stylename in a style of the form [(stylename|key=value);] or an empty string if the given style does not contain a stylename.

Parameters

styleString of the form [(stylename|key=value);].

getStylenames

getStylenames: function(style)

Returns the stylenames in a style of the form [(stylename|key=value);] or an empty array if the given style does not contain any stylenames.

Parameters

styleString of the form [(stylename|key=value);].

indexOfStylename

indexOfStylename: function(style,
stylename)

Returns the index of the given stylename in the given style.  This returns -1 if the given stylename does not occur (as a stylename) in the given style, otherwise it returns the index of the first character.

addStylename

addStylename: function(style,
stylename)

Adds the specified stylename to the given style if it does not already contain the stylename.

removeStylename

removeStylename: function(style,
stylename)

Removes all occurrences of the specified stylename in the given style and returns the updated style.  Trailing semicolons are not preserved.

removeAllStylenames

removeAllStylenames: function(style)

Removes all stylenames from the given style and returns the updated style.

setCellStyles

setCellStyles: function(model,
cells,
key,
value)

Assigns the value for the given key in the styles of the given cells, or removes the key from the styles if the value is null.

Parameters

modelmxGraphModel to execute the transaction in.
cellsArray of mxCells to be updated.
keyKey of the style to be changed.
valueNew value for the given key.

setStyle

setStyle: function(style,
key,
value)

Adds or removes the given key, value pair to the style and returns the new style.  If value is null or zero length then the key is removed from the style.  This is for cell styles, not for CSS styles.

Parameters

styleString of the form [(stylename|key=value);].
keyKey of the style to be changed.
valueNew value for the given key.

setCellStyleFlags

setCellStyleFlags: function(model,
cells,
key,
flag,
value)

Sets or toggles the flag bit for the given key in the cell’s styles.  If value is null then the flag is toggled.

Example

var cells = graph.getSelectionCells();
mxUtils.setCellStyleFlags(graph.model,
         cells,
         mxConstants.STYLE_FONTSTYLE,
         mxConstants.FONT_BOLD);

Toggles the bold font style.

Parameters

modelmxGraphModel that contains the cells.
cellsArray of mxCells to change the style for.
keyKey of the style to be changed.
flagInteger for the bit to be changed.
valueOptional boolean value for the flag.

setStyleFlag

setStyleFlag: function(style,
key,
flag,
value)

Sets or removes the given key from the specified style and returns the new style.  If value is null then the flag is toggled.

Parameters

styleString of the form [(stylename|key=value);].
keyKey of the style to be changed.
flagInteger for the bit to be changed.
valueOptional boolean value for the given flag.

getAlignmentAsPoint

getAlignmentAsPoint: function(align,
valign)

Returns an mxPoint that represents the horizontal and vertical alignment for numeric computations.  X is -0.5 for center, -1 for right and 0 for left alignment.  Y is -0.5 for middle, -1 for bottom and 0 for top alignment.  Default values for missing arguments is top, left.

getSizeForString

getSizeForString: function(text,
fontSize,
fontFamily,
textWidth)

Returns an mxRectangle with the size (width and height in pixels) of the given string.  The string may contain HTML markup.  Newlines should be converted to br before calling this method.

Example

var label = graph.getLabel(cell).replace(/\n/g, "<br>");
var size = graph.getSizeForString(label);

Parameters

textString whose size should be returned.
fontSizeInteger that specifies the font size in pixels.  Default is mxConstants.DEFAULT_FONTSIZE.
fontFamilyString that specifies the name of the font family.  Default is mxConstants.DEFAULT_FONTFAMILY.
textWidthOptional width for text wrapping.

getViewXml

getViewXml: function(graph,
scale,
cells,
x0,
y0)

getScaleForPageCount

getScaleForPageCount: function(pageCount,
graph,
pageFormat,
border)

Returns the scale to be used for printing the graph with the given bounds across the specifies number of pages with the given format.  The scale is always computed such that it given the given amount or fewer pages in the print output.  See mxPrintPreview for an example.

Parameters

pageCountSpecifies the number of pages in the print output.
graphmxGraph that should be printed.
pageFormatOptional mxRectangle that specifies the page format.  Default is mxConstants.PAGE_FORMAT_A4_PORTRAIT.
borderThe border along each side of every page.

show

show: function(graph,
doc,
x0,
y0,
w,
h)

Copies the styles and the markup from the graph’s container into the given document and removes all cursor styles.  The document is returned.

This function should be called from within the document with the graph.  If you experience problems with missing stylesheets in IE then try adding the domain to the trusted sites.

Parameters

graphmxGraph to be copied.
docDocument where the new graph is created.
x0X-coordinate of the graph view origin.  Default is 0.
y0Y-coordinate of the graph view origin.  Default is 0.
wOptional width of the graph view.
hOptional height of the graph view.

printScreen

printScreen: function(graph)

Prints the specified graph using a new window and the built-in print dialog.

This function should be called from within the document with the graph.

Parameters

graphmxGraph to be printed.

popup

popup: function(content,
isInternalWindow)

Shows the specified text content in a new mxWindow or a new browser window if isInternalWindow is false.

Parameters

contentString that specifies the text to be displayed.
isInternalWindowOptional boolean indicating if an mxWindow should be used instead of a new browser window.  Default is false.

alert

alert: function(message)

Displayss the given alert in a new dialog.  This implementation uses the built-in alert function.  This is used to display validation errors when connections cannot be changed or created.

Parameters

messageString specifying the message to be displayed.

prompt

prompt: function(message,
defaultValue)

Displays the given message in a prompt dialog.  This implementation uses the built-in prompt function.

Parameters

messageString specifying the message to be displayed.
defaultValueOptional string specifying the default value.

confirm

confirm: function(message)

Displays the given message in a confirm dialog.  This implementation uses the built-in confirm function.

Parameters

messageString specifying the message to be displayed.

error

error: function(message,
width,
close,
icon)

Displays the given error message in a new mxWindow of the given width.  If close is true then an additional close button is added to the window.  The optional icon specifies the icon to be used for the window.  Default is mxUtils.errorImage.

Parameters

messageString specifying the message to be displayed.
widthInteger specifying the width of the window.
closeOptional boolean indicating whether to add a close button.
iconOptional icon for the window decoration.

makeDraggable

makeDraggable: function(element,
graphF,
funct,
dragElement,
dx,
dy,
autoscroll,
scalePreview,
highlightDropTargets,
getDropTarget)

Configures the given DOM element to act as a drag source for the specified graph.  Returns a a new mxDragSource.  If <mxDragSource.guideEnabled> is enabled then the x and y arguments must be used in funct to match the preview location.

Example

var funct = function(graph, evt, cell, x, y)
{
  if (graph.canImportCell(cell))
  {
    var parent = graph.getDefaultParent();
    var vertex = null;

    graph.getModel().beginUpdate();
    try
    {
      vertex = graph.insertVertex(parent, null, 'Hello', x, y, 80, 30);
    }
    finally
    {
      graph.getModel().endUpdate();
    }

    graph.setSelectionCell(vertex);
  }
}

var img = document.createElement('img');
img.setAttribute('src', 'editors/images/rectangle.gif');
img.style.position = 'absolute';
img.style.left = '0px';
img.style.top = '0px';
img.style.width = '16px';
img.style.height = '16px';

var dragImage = img.cloneNode(true);
dragImage.style.width = '32px';
dragImage.style.height = '32px';
mxUtils.makeDraggable(img, graph, funct, dragImage);
document.body.appendChild(img);

Parameters

elementDOM element to make draggable.
graphFmxGraph that acts as the drop target or a function that takes a mouse event and returns the current mxGraph.
functFunction to execute on a successful drop.
dragElementOptional DOM node to be used for the drag preview.
dxOptional horizontal offset between the cursor and the drag preview.
dyOptional vertical offset between the cursor and the drag preview.
autoscrollOptional boolean that specifies if autoscroll should be used.  Default is mxGraph.autoscroll.
scalePreviewOptional boolean that specifies if the preview element should be scaled according to the graph scale.  If this is true, then the offsets will also be scaled.  Default is false.
highlightDropTargetsOptional boolean that specifies if dropTargets should be highlighted.  Default is true.
getDropTargetOptional function to return the drop target for a given location (x, y).  Default is mxGraph.getCellAt.
removeCursors: function(element)
Removes the cursors from the style of the given DOM node and its descendants.
getCurrentStyle: function()
Returns the current style of the specified element.
setPrefixedStyle: function()
Adds the given style with the standard name and an optional vendor prefix for the current browser.
hasScrollbars: function(node)
Returns true if the overflow CSS property of the given node is either scroll or auto.
bind: function(scope,
funct)
Returns a wrapper function that locks the execution scope of the given function to the specified scope.
eval: function(expr)
Evaluates the given expression using eval and returns the JavaScript object that represents the expression result.
findNode: function(node,
attr,
value)
Returns the first node where attr equals value.
findNodeByAttribute: function()
Returns the first node where the given attribute matches the given value.
getFunctionName: function(f)
Returns the name for the given function.
indexOf: function(array,
obj)
Returns the index of obj in array or -1 if the array does not contains the given object.
remove: function(obj,
array)
Removes all occurrences of the given object in the given array or object.
isNode: function(value,
nodeName,
attributeName,
attributeValue)
Returns true if the given value is an XML node with the node name and if the optional attribute has the specified value.
getChildNodes: function(node,
nodeType)
Returns an array of child nodes that are of the given node type.
createXmlDocument: function()
Returns a new, empty XML document.
parseXml: function()
Parses the specified XML string into a new XML document and returns the new document.
clearSelection: function()
Clears the current selection in the page.
removeWhitespace: function(node,
before)
Removes the sibling text nodes for the given node that only consists of tabs, newlines and spaces.
htmlEntities: function(s,
newline)
Replaces characters (less than, greater than, newlines and quotes) with their HTML entities in the given string and returns the result.
isVml: function(node)
Returns true if the given node is in the VML namespace.
getXml: function(node,
linefeed)
Returns the XML content of the specified node.
getTextContent: function(node)
Returns the text content of the specified node.
getInnerHtml: function()
Returns the inner HTML for the given node as a string or an empty string if no node was specified.
getOuterHtml: function()
Returns the outer HTML for the given node as a string or an empty string if no node was specified.
write: function(parent,
text)
Creates a text node for the given string and appends it to the given parent.
writeln: function(parent,
text)
Creates a text node for the given string and appends it to the given parent with an additional linefeed.
br: function(parent,
count)
Appends a linebreak to the given parent and returns the linebreak.
button: function(label,
funct,
doc)
Returns a new button with the given level and function as an onclick event handler.
para: function(parent,
text)
Appends a new paragraph with the given text to the specified parent and returns the paragraph.
addTransparentBackgroundFilter: function(node)
Adds a transparent background to the filter of the given node.
linkAction: function(parent,
text,
editor,
action,
pad)
Adds a hyperlink to the specified parent that invokes action on the specified editor.
linkInvoke: function(parent,
text,
editor,
functName,
arg,
pad)
Adds a hyperlink to the specified parent that invokes the specified function on the editor passing along the specified argument.
link: function(parent,
text,
funct,
pad)
Adds a hyperlink to the specified parent and invokes the given function when the link is clicked.
fit: function(node)
Makes sure the given node is inside the visible area of the window.
open: function(filename)
Opens the specified file from the local filesystem and returns the contents of the file as a string.
save: function(filename,
content)
Saves the specified content in the given file on the local file system.
saveAs: function(content)
Saves the specified content by displaying a dialog to save the content as a file on the local filesystem.
copy: function(content)
Copies the specified content to the local clipboard.
load: function(url)
Loads the specified URL synchronously and returns the mxXmlRequest.
XML HTTP request wrapper.
get: function(url,
onload,
onerror)
Loads the specified URL asynchronously and invokes the given functions depending on the request status.
post: function(url,
params,
onload,
onerror)
Posts the specified params to the given URL asynchronously and invokes the given functions depending on the request status.
submit: function(url,
params,
doc,
target)
Submits the given parameters to the specified URL using mxXmlRequest.simulate and returns the mxXmlRequest.
mxXmlRequest.prototype.simulate = function(doc,
target)
Creates and posts a request to the given target URL using a dynamically created form inside the given document.
loadInto: function(url,
doc,
onload)
Loads the specified URL asynchronously into the specified document, invoking onload after the document has been loaded.
getValue: function(array,
key,
defaultValue)
Returns the value for the given key in the given associative array or the given default value if the value is null.
getNumber: function(array,
key,
defaultValue)
Returns the numeric value for the given key in the given associative array or the given default value (or 0) if the value is null.
getColor: function(array,
key,
defaultValue)
Returns the color value for the given key in the given associative array or the given default value if the value is null.
clone: function(obj,
transients,
shallow)
Recursively clones the specified object ignoring all fieldnames in the given array of transient fields.
equalPoints: function(a,
b)
Compares all mxPoints in the given lists.
equalEntries: function(a,
b)
Returns true if all entries of the given objects are equal.
isNaN: function(value)
Returns true if the given value is of type number and isNaN returns true.
extend: function(ctor,
superCtor)
Assigns a copy of the superclass prototype to the subclass prototype.
toString: function(obj)
Returns a textual representation of the specified object.
toRadians: function(deg)
Converts the given degree to radians.
arcToCurves: function(x0,
y0,
r1,
r2,
angle,
largeArcFlag,
sweepFlag,
x,
y)
Converts the given arc to a series of curves.
getBoundingBox: function(rect,
rotation)
Returns the bounding box for the rotated rectangle.
getRotatedPoint: function(pt,
cos,
sin,
c)
Rotates the given point by the given cos and sin.
reversePortConstraints: function(constraint)
Reverse the port constraint bitmask.
findNearestSegment: function(state,
x,
y)
Finds the index of the nearest segment on the given cell state for the specified coordinate pair.
rectangleIntersectsSegment: function(bounds,
p1,
p2)
Returns true if the given rectangle intersects the given segment.
contains: function(bounds,
x,
y)
Returns true if the specified point (x, y) is contained in the given rectangle.
intersects: function(a,
b)
Returns true if the two rectangles intersect.
getOffset: function(container,
scrollOffset)
Returns the offset for the specified container as an mxPoint.
Implements a 2-dimensional vector with double precision coordinates.
getScrollOrigin: function(node)
Returns the top, left corner of the viewrect as an mxPoint.
convertPoint: function(container,
x,
y)
Converts the specified point (x, y) using the offset of the specified container and returns a new mxPoint with the result.
ltrim: function(str,
chars)
Strips all whitespaces from the beginning of the string.
rtrim: function(str,
chars)
Strips all whitespaces from the end of the string.
trim: function(str,
chars)
Strips all whitespaces from both end of the string.
isNumeric: function(str)
Returns true if the specified value is numeric, that is, if it is not null, not an empty string, not a HEX number and isNaN returns false.
mod: function(n,
m)
Returns the remainder of division of n by m.
intersection: function (x0,
y0,
x1,
y1,
x2,
y2,
x3,
y3)
Returns the intersection of two lines as an mxPoint.
relativeCcw: function(x1,
y1,
x2,
y2,
px,
py)
Returns 1 if the given point on the right side of the segment, 0 if its on the segment, and -1 if the point is on the left side of the segment.
animateChanges: function(graph,
changes)
See mxEffects.animateChanges.
animateChanges: function(graph,
changes,
done)
Asynchronous animated move operation.
cascadeOpacity: function(graph,
cell,
opacity)
See mxEffects.cascadeOpacity.
cascadeOpacity: function(graph,
cell,
opacity)
Sets the opacity on the given cell and its descendants.
fadeOut: function(node,
from,
remove,
step,
delay,
isEnabled)
See mxEffects.fadeOut.
fadeOut: function(node,
from,
remove,
step,
delay,
isEnabled)
Asynchronous fade-out operation.
setOpacity: function(node,
value)
Sets the opacity of the specified DOM node to the given value in %.
createImage: function(src)
Creates and returns an image (IMG node) or VML image (v:image) in IE6 in quirks mode.
sortCells: function(cells,
ascending)
Sorts the given cells according to the order in the cell hierarchy.
getStylename: function(style)
Returns the stylename in a style of the form [(stylename|key=value);] or an empty string if the given style does not contain a stylename.
getStylenames: function(style)
Returns the stylenames in a style of the form [(stylename|key=value);] or an empty array if the given style does not contain any stylenames.
indexOfStylename: function(style,
stylename)
Returns the index of the given stylename in the given style.
addStylename: function(style,
stylename)
Adds the specified stylename to the given style if it does not already contain the stylename.
removeStylename: function(style,
stylename)
Removes all occurrences of the specified stylename in the given style and returns the updated style.
removeAllStylenames: function(style)
Removes all stylenames from the given style and returns the updated style.
setCellStyles: function(model,
cells,
key,
value)
Assigns the value for the given key in the styles of the given cells, or removes the key from the styles if the value is null.
setStyle: function(style,
key,
value)
Adds or removes the given key, value pair to the style and returns the new style.
setCellStyleFlags: function(model,
cells,
key,
flag,
value)
Sets or toggles the flag bit for the given key in the cell’s styles.
setStyleFlag: function(style,
key,
flag,
value)
Sets or removes the given key from the specified style and returns the new style.
getAlignmentAsPoint: function(align,
valign)
Returns an mxPoint that represents the horizontal and vertical alignment for numeric computations.
getSizeForString: function(text,
fontSize,
fontFamily,
textWidth)
Returns an mxRectangle with the size (width and height in pixels) of the given string.
Extends mxPoint to implement a 2-dimensional rectangle with double precision coordinates.
getViewXml: function(graph,
scale,
cells,
x0,
y0)
getScaleForPageCount: function(pageCount,
graph,
pageFormat,
border)
Returns the scale to be used for printing the graph with the given bounds across the specifies number of pages with the given format.
show: function(graph,
doc,
x0,
y0,
w,
h)
Copies the styles and the markup from the graph’s container into the given document and removes all cursor styles.
printScreen: function(graph)
Prints the specified graph using a new window and the built-in print dialog.
popup: function(content,
isInternalWindow)
Shows the specified text content in a new mxWindow or a new browser window if isInternalWindow is false.
Basic window inside a document.
alert: function(message)
Displayss the given alert in a new dialog.
prompt: function(message,
defaultValue)
Displays the given message in a prompt dialog.
confirm: function(message)
Displays the given message in a confirm dialog.
error: function(message,
width,
close,
icon)
Displays the given error message in a new mxWindow of the given width.
makeDraggable: function(element,
graphF,
funct,
dragElement,
dx,
dy,
autoscroll,
scalePreview,
highlightDropTargets,
getDropTarget)
Configures the given DOM element to act as a drag source for the specified graph.
DOM node of type ELEMENT.
Extends mxEventSource to implement a application wrapper for a graph that adds actions, I/O using mxCodec, auto-layout using mxLayoutManager, command history using undoManager, and standard dialogs and widgets, eg.
Defines the value for none.
Name of the field to be used to store the object ID.
Extends mxEventSource to implement a graph model.
Cells are the elements of the graph model.
Defines the default size for all fonts in points.
Defines the default family for all fonts in points.
Implements printing of a diagram across multiple pages.
Extends mxEventSource to implement a graph component for the browser.
Defines the rectangle for the A4 portrait page format.
Defines the image used for error dialogs.
Wrapper to create a drag source from a DOM element so that the element can be dragged over a graph and dropped into the graph as a new cell.
Close