- Refactored the stories for storybook to work

development
Junsik Shim 2021-08-30 23:20:26 +09:00
parent 61648e43ce
commit 0adb9fa1d3
107 changed files with 2266 additions and 3203 deletions

View File

@ -13,7 +13,7 @@ import CompactTreeLayout from '../view/layout/layout/CompactTreeLayout';
import mxDefaultToolbar from './mxDefaultToolbar'; import mxDefaultToolbar from './mxDefaultToolbar';
import StackLayout from '../view/layout/layout/StackLayout'; import StackLayout from '../view/layout/layout/StackLayout';
import EventObject from '../view/event/EventObject'; import EventObject from '../view/event/EventObject';
import utils, { getOffset } from '../util/Utils'; import { getOffset } from '../util/Utils';
import mxCodec from '../util/serialization/mxCodec'; import mxCodec from '../util/serialization/mxCodec';
import mxWindow, { error } from '../util/gui/mxWindow'; import mxWindow, { error } from '../util/gui/mxWindow';
import mxForm from '../util/gui/mxForm'; import mxForm from '../util/gui/mxForm';
@ -40,7 +40,7 @@ import RootChange from '../view/model/RootChange';
import ValueChange from '../view/cell/ValueChange'; import ValueChange from '../view/cell/ValueChange';
import CellAttributeChange from '../view/cell/CellAttributeChange'; import CellAttributeChange from '../view/cell/CellAttributeChange';
import PrintPreview from '../view/printing/PrintPreview'; import PrintPreview from '../view/printing/PrintPreview';
import mxClipboard from '../util/storage/mxClipboard'; import mxClipboard from '../util/storage/Clipboard';
import mxLog from '../util/gui/mxLog'; import mxLog from '../util/gui/mxLog';
import { isNode } from '../util/DomUtils'; import { isNode } from '../util/DomUtils';
import { getViewXml, getXml } from '../util/XmlUtils'; import { getViewXml, getXml } from '../util/XmlUtils';
@ -1292,10 +1292,7 @@ class mxEditor extends EventSource {
const current = editor.graph.getView().scale * 100; const current = editor.graph.getView().scale * 100;
const scale = const scale =
parseFloat( parseFloat(
prompt( prompt(Resources.get(editor.askZoomResource) || editor.askZoomResource, current)
Resources.get(editor.askZoomResource) || editor.askZoomResource,
current
)
) / 100; ) / 100;
if (!isNaN(scale)) { if (!isNaN(scale)) {
@ -1362,8 +1359,7 @@ class mxEditor extends EventSource {
*/ */
// resetFirstTime(): void; // resetFirstTime(): void;
resetFirstTime() { resetFirstTime() {
document.cookie = document.cookie = 'mxgraph=seen; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/';
'mxgraph=seen; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/';
} }
/** /**
@ -1677,10 +1673,8 @@ class mxEditor extends EventSource {
if ( if (
change instanceof RootChange || change instanceof RootChange ||
(change instanceof ValueChange && (change instanceof ValueChange && change.cell === this.graph.model.root) ||
change.cell === this.graph.model.root) || (change instanceof CellAttributeChange && change.cell === this.graph.model.root)
(change instanceof CellAttributeChange &&
change.cell === this.graph.model.root)
) { ) {
this.fireEvent(new EventObject(InternalEvent.ROOT)); this.fireEvent(new EventObject(InternalEvent.ROOT));
break; break;
@ -1801,9 +1795,7 @@ class mxEditor extends EventSource {
this.addListener(InternalEvent.SAVE, () => { this.addListener(InternalEvent.SAVE, () => {
const tstamp = new Date().toLocaleString(); const tstamp = new Date().toLocaleString();
this.setStatus( this.setStatus(
`${ `${Resources.get(this.lastSavedResource) || this.lastSavedResource}: ${tstamp}`
Resources.get(this.lastSavedResource) || this.lastSavedResource
}: ${tstamp}`
); );
}); });
@ -1811,10 +1803,9 @@ class mxEditor extends EventSource {
// when new files are opened // when new files are opened
this.addListener(InternalEvent.OPEN, () => { this.addListener(InternalEvent.OPEN, () => {
this.setStatus( this.setStatus(
`${ `${Resources.get(this.currentFileResource) || this.currentFileResource}: ${
Resources.get(this.currentFileResource) || this.filename
this.currentFileResource }`
}: ${this.filename}`
); );
}); });
} }
@ -2045,15 +2036,7 @@ class mxEditor extends EventSource {
post(url, `${this.postParameterName}=${data}`, (req) => { post(url, `${this.postParameterName}=${data}`, (req) => {
this.fireEvent( this.fireEvent(
new EventObject( new EventObject(InternalEvent.POST, 'request', req, 'url', url, 'data', data)
InternalEvent.POST,
'request',
req,
'url',
url,
'data',
data
)
); );
}); });
} }
@ -2292,11 +2275,7 @@ class mxEditor extends EventSource {
// model, which will also make the change // model, which will also make the change
// part of the current transaction // part of the current transaction
for (let i = 0; i < attrs.length; i += 1) { for (let i = 0; i < attrs.length; i += 1) {
const edit = new CellAttributeChange( const edit = new CellAttributeChange(cell, attrs[i].nodeName, texts[i].value);
cell,
attrs[i].nodeName,
texts[i].value
);
model.execute(edit); model.execute(edit);
} }
@ -2446,8 +2425,7 @@ class mxEditor extends EventSource {
frame.style.backgroundColor = 'white'; frame.style.backgroundColor = 'white';
const w = document.body.clientWidth; const w = document.body.clientWidth;
const h = const h = document.body.clientHeight || document.documentElement.clientHeight;
document.body.clientHeight || document.documentElement.clientHeight;
const wnd = new mxWindow( const wnd = new mxWindow(
Resources.get(this.helpResource) || this.helpResource, Resources.get(this.helpResource) || this.helpResource,
@ -2716,13 +2694,7 @@ class mxEditor extends EventSource {
this.cycleAttribute(vertex); this.cycleAttribute(vertex);
this.fireEvent( this.fireEvent(
new EventObject( new EventObject(InternalEvent.BEFORE_ADD_VERTEX, 'vertex', vertex, 'parent', parent)
InternalEvent.BEFORE_ADD_VERTEX,
'vertex',
vertex,
'parent',
parent
)
); );
model.beginUpdate(); model.beginUpdate();
@ -2741,9 +2713,7 @@ class mxEditor extends EventSource {
if (vertex != null) { if (vertex != null) {
this.graph.setSelectionCell(vertex); this.graph.setSelectionCell(vertex);
this.graph.scrollCellToVisible(vertex); this.graph.scrollCellToVisible(vertex);
this.fireEvent( this.fireEvent(new EventObject(InternalEvent.AFTER_ADD_VERTEX, 'vertex', vertex));
new EventObject(InternalEvent.AFTER_ADD_VERTEX, 'vertex', vertex)
);
} }
return vertex; return vertex;

View File

@ -104,28 +104,28 @@ import RhombusShape from './view/geometry/shape/node/RhombusShape';
import StencilShape from './view/geometry/shape/node/StencilShape'; import StencilShape from './view/geometry/shape/node/StencilShape';
import StencilShapeRegistry from './view/geometry/shape/node/StencilShapeRegistry'; import StencilShapeRegistry from './view/geometry/shape/node/StencilShapeRegistry';
import * as mxConstants from './util/Constants'; import * as Constants from './util/Constants';
import mxGuide from './util/Guide'; import Guide from './util/Guide';
import Resources from './util/Resources'; import Resources from './util/Resources';
import utils from './util/Utils'; import utils from './util/Utils';
import * as mxCloneUtils from './util/CloneUtils'; import * as CloneUtils from './util/CloneUtils';
import * as mxDomUtils from './util/DomUtils'; import * as DomUtils from './util/DomUtils';
import * as mxEventUtils from './util/EventUtils'; import * as EventUtils from './util/EventUtils';
import * as mxGestureUtils from './util/GestureUtils'; import * as GestureUtils from './util/GestureUtils';
import * as mxStringUtils from './util/StringUtils'; import * as StringUtils from './util/StringUtils';
import * as mxXmlUtils from './util/XmlUtils'; import * as XmlUtils from './util/XmlUtils';
import mxAnimation from './util/animate/mxAnimation'; import mxAnimation from './util/animate/mxAnimation';
import mxEffects from './util/animate/mxEffects'; import mxEffects from './util/animate/mxEffects';
import mxMorphing from './util/animate/mxMorphing'; import mxMorphing from './util/animate/mxMorphing';
import mxAbstractCanvas2D from './util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from './util/canvas/AbstractCanvas2D';
import mxSvgCanvas2D from './util/canvas/SvgCanvas2D'; import SvgCanvas2D from './util/canvas/SvgCanvas2D';
import mxXmlCanvas2D from './util/canvas/mxXmlCanvas2D'; import mxXmlCanvas2D from './util/canvas/mxXmlCanvas2D';
import Dictionary from './util/Dictionary'; import Dictionary from './util/Dictionary';
import Geometry from './view/geometry/Geometry'; import Geometry from './view/geometry/Geometry';
import mxObjectIdentity from './util/mxObjectIdentity'; import ObjectIdentity from './util/ObjectIdentity';
import Point from './view/geometry/Point'; import Point from './view/geometry/Point';
import Rectangle from './view/geometry/Rectangle'; import Rectangle from './view/geometry/Rectangle';
@ -147,11 +147,11 @@ import InternalMouseEvent from './view/event/InternalMouseEvent';
import mxForm from './util/gui/mxForm'; import mxForm from './util/gui/mxForm';
import mxLog from './util/gui/mxLog'; import mxLog from './util/gui/mxLog';
import mxPopupMenu from './util/gui/mxPopupMenu'; import PopupMenu from './util/gui/PopupMenu';
import mxToolbar from './util/gui/mxToolbar'; import mxToolbar from './util/gui/mxToolbar';
import mxWindow from './util/gui/mxWindow'; import mxWindow from './util/gui/mxWindow';
import Image from './view/image/ImageBox'; import ImageBox from './view/image/ImageBox';
import ImageBundle from './view/image/ImageBundle'; import ImageBundle from './view/image/ImageBundle';
import ImageExport from './view/image/ImageExport'; import ImageExport from './view/image/ImageExport';
@ -159,7 +159,7 @@ import mxUrlConverter from './util/network/mxUrlConverter';
import mxXmlRequest from './util/network/mxXmlRequest'; import mxXmlRequest from './util/network/mxXmlRequest';
import mxAutoSaveManager from './util/storage/mxAutoSaveManager'; import mxAutoSaveManager from './util/storage/mxAutoSaveManager';
import mxClipboard from './util/storage/mxClipboard'; import Clipboard from './util/storage/Clipboard';
import UndoableEdit from './view/model/UndoableEdit'; import UndoableEdit from './view/model/UndoableEdit';
import mxUndoManager from './util/mxUndoManager'; import mxUndoManager from './util/mxUndoManager';
@ -176,9 +176,8 @@ import TemporaryCellStates from './view/cell/TemporaryCellStates';
import ConnectionConstraint from './view/connection/ConnectionConstraint'; import ConnectionConstraint from './view/connection/ConnectionConstraint';
import Multiplicity from './view/validation/Multiplicity'; import Multiplicity from './view/validation/Multiplicity';
import graph from './view/Graph'; import Graph from './view/Graph';
import Model from './view/model/Model'; import Model from './view/model/Model';
import mxGraphSelectionModel from './view/selection/mxGraphSelectionModel';
import GraphView from './view/view/GraphView'; import GraphView from './view/view/GraphView';
import LayoutManager from './view/layout/LayoutManager'; import LayoutManager from './view/layout/LayoutManager';
import Outline from './view/Outline'; import Outline from './view/Outline';
@ -190,124 +189,124 @@ import '../css/common.css';
export default { export default {
mxClient, mxClient,
mxLog, mxLog,
mxObjectIdentity, ObjectIdentity,
mxDictionary: Dictionary, Dictionary,
mxResources: Resources, Resources,
mxPoint: Point, Point,
mxRectangle: Rectangle, Rectangle,
mxEffects, mxEffects,
mxUtils: utils, utils,
mxConstants, Constants,
mxEventObject: EventObject, EventObject,
mxMouseEvent: InternalMouseEvent, InternalMouseEvent,
mxEventSource: EventSource, EventSource,
mxEvent: InternalEvent, InternalEvent,
mxXmlRequest, mxXmlRequest,
mxClipboard, Clipboard,
mxWindow, mxWindow,
mxForm, mxForm,
mxImage: Image, Image,
mxDivResizer, mxDivResizer,
mxDragSource: DragSource, DragSource,
mxToolbar, mxToolbar,
mxUndoableEdit: UndoableEdit, UndoableEdit,
mxUndoManager, mxUndoManager,
mxUrlConverter, mxUrlConverter,
mxPanningManager: PanningManager, PanningManager,
mxPopupMenu, PopupMenu,
mxAutoSaveManager, mxAutoSaveManager,
mxAnimation, mxAnimation,
mxMorphing, mxMorphing,
mxImageBundle: ImageBundle, ImageBox,
mxImageExport: ImageExport, ImageBundle,
mxAbstractCanvas2D, ImageExport,
AbstractCanvas2D,
mxXmlCanvas2D, mxXmlCanvas2D,
mxSvgCanvas2D, SvgCanvas2D,
mxGuide, Guide,
mxShape: Shape, Shape,
mxStencil: StencilShape, StencilShape,
mxStencilRegistry: StencilShapeRegistry, StencilShapeRegistry,
mxMarker: Marker, Marker,
mxActor: Actor, Actor,
mxCloud: CloudShape, CloudShape,
mxRectangleShape: RectangleShape, RectangleShape,
mxEllipse: EllipseShape, EllipseShape,
mxDoubleEllipse: DoubleEllipseShape, DoubleEllipseShape,
mxRhombus: RhombusShape, RhombusShape,
mxPolyline: Polyline, Polyline,
mxArrow: Arrow, Arrow,
mxArrowConnector: ArrowConnector, ArrowConnector,
mxText: TextShape, TextShape,
mxTriangle: TriangleShape, TriangleShape,
mxHexagon: HexagonShape, HexagonShape,
mxLine: Line, Line,
mxImageShape: ImageShape, ImageShape,
mxLabel: Label, Label,
mxCylinder: CylinderShape, CylinderShape,
mxConnector: Connector, Connector,
mxSwimlane: SwimlaneShape, SwimlaneShape,
mxGraphLayout: GraphLayout, GraphLayout,
mxStackLayout: StackLayout, StackLayout,
mxPartitionLayout: PartitionLayout, PartitionLayout,
mxCompactTreeLayout: CompactTreeLayout, CompactTreeLayout,
mxRadialTreeLayout: RadialTreeLayout, RadialTreeLayout,
mxFastOrganicLayout: MxFastOrganicLayout, MxFastOrganicLayout,
mxCircleLayout: CircleLayout, CircleLayout,
mxParallelEdgeLayout: ParallelEdgeLayout, ParallelEdgeLayout,
mxCompositeLayout: CompositeLayout, CompositeLayout,
mxEdgeLabelLayout: EdgeLabelLayout, EdgeLabelLayout,
mxGraphAbstractHierarchyCell: MxGraphAbstractHierarchyCell, MxGraphAbstractHierarchyCell,
mxGraphHierarchyNode: GraphHierarchyNode, GraphHierarchyNode,
mxGraphHierarchyEdge: GraphHierarchyEdge, GraphHierarchyEdge,
mxGraphHierarchyModel: GraphHierarchyModel, GraphHierarchyModel,
mxSwimlaneModel: SwimlaneModel, SwimlaneModel,
mxHierarchicalLayoutStage: MxHierarchicalLayoutStage, MxHierarchicalLayoutStage,
mxMedianHybridCrossingReduction: MedianHybridCrossingReduction, MedianHybridCrossingReduction,
mxMinimumCycleRemover: MinimumCycleRemover, MinimumCycleRemover,
mxCoordinateAssignment: CoordinateAssignment, CoordinateAssignment,
mxSwimlaneOrdering, mxSwimlaneOrdering,
mxHierarchicalLayout, mxHierarchicalLayout,
mxSwimlaneLayout: SwimlaneLayout, SwimlaneLayout,
mxGraphModel: Model, Model,
mxCell: Cell, Cell,
mxGeometry: Geometry, Geometry,
mxCellPath: CellPath, CellPath,
mxPerimeter: Perimeter, Perimeter,
mxPrintPreview: PrintPreview, PrintPreview,
mxStylesheet: Stylesheet, Stylesheet,
mxCellState: CellState, CellState,
mxGraphSelectionModel, CellEditor,
mxCellEditor: CellEditor, CellRenderer,
mxCellRenderer: CellRenderer, EdgeStyle,
mxEdgeStyle: EdgeStyle, StyleRegistry,
mxStyleRegistry: StyleRegistry, GraphView,
mxGraphView: GraphView, Graph,
mxGraph: graph, CellOverlay,
mxCellOverlay: CellOverlay, Outline,
mxOutline: Outline, Multiplicity,
mxMultiplicity: Multiplicity, LayoutManager,
mxLayoutManager: LayoutManager, SwimlaneManager,
mxSwimlaneManager: SwimlaneManager, TemporaryCellStates,
mxTemporaryCellStates: TemporaryCellStates, CellStatePreview,
mxCellStatePreview: CellStatePreview, ConnectionConstraint,
mxConnectionConstraint: ConnectionConstraint, GraphHandler,
mxGraphHandler: GraphHandler, PanningHandler,
mxPanningHandler: PanningHandler, PopupMenuHandler,
mxPopupMenuHandler: PopupMenuHandler, CellMarker,
mxCellMarker: CellMarker, SelectionCellsHandler,
mxSelectionCellsHandler: SelectionCellsHandler, ConnectionHandler,
mxConnectionHandler: ConnectionHandler, ConstraintHandler,
mxConstraintHandler: ConstraintHandler, RubberBand,
mxRubberband: RubberBand, VertexHandle,
mxHandle: VertexHandle, VertexHandler,
mxVertexHandler: VertexHandler, EdgeHandler,
mxEdgeHandler: EdgeHandler, ElbowEdgeHandler,
mxElbowEdgeHandler: ElbowEdgeHandler, EdgeSegmentHandler,
mxEdgeSegmentHandler: EdgeSegmentHandler,
mxKeyHandler, mxKeyHandler,
mxTooltipHandler: TooltipHandler, TooltipHandler,
mxCellTracker: CellTracker, CellTracker,
mxCellHighlight: CellHighlight, CellHighlight,
mxDefaultKeyHandler, mxDefaultKeyHandler,
mxDefaultPopupMenu, mxDefaultPopupMenu,
mxDefaultToolbar, mxDefaultToolbar,
@ -328,22 +327,22 @@ export default {
// mxDefaultToolbarCodec, // mxDefaultToolbarCodec,
// mxDefaultPopupMenuCodec, // mxDefaultPopupMenuCodec,
// mxEditorCodec, // mxEditorCodec,
mxCloneUtils, CloneUtils,
mxDomUtils, DomUtils,
mxEventUtils, EventUtils,
mxGestureUtils, GestureUtils,
mxStringUtils, StringUtils,
mxXmlUtils, XmlUtils,
mxDomHelpers, mxDomHelpers,
mxCellAttributeChange: CellAttributeChange, CellAttributeChange,
mxChildChange: ChildChange, ChildChange,
mxCollapseChange: CollapseChange, CollapseChange,
mxCurrentRootChange: CurrentRootChange, CurrentRootChange,
mxGeometryChange: GeometryChange, GeometryChange,
mxRootChange: RootChange, RootChange,
mxSelectionChange: SelectionChange, SelectionChange,
mxStyleChange: StyleChange, StyleChange,
mxTerminalChange: TerminalChange, TerminalChange,
mxValueChange: ValueChange, ValueChange,
mxVisibleChange: VisibleChange, VisibleChange,
}; };

View File

@ -1,4 +1,4 @@
import mxObjectIdentity from "./mxObjectIdentity"; import ObjectIdentity from './ObjectIdentity';
/** /**
* Function: clone * Function: clone
@ -26,7 +26,7 @@ export const clone = function _clone(obj, transients, shallow) {
for (const i in obj) { for (const i in obj) {
if ( if (
i != mxObjectIdentity.FIELD_NAME && i != ObjectIdentity.FIELD_NAME &&
(transients == null || transients.indexOf(i) < 0) (transients == null || transients.indexOf(i) < 0)
) { ) {
if (!shallow && typeof obj[i] === 'object') { if (!shallow && typeof obj[i] === 'object') {
@ -39,4 +39,4 @@ export const clone = function _clone(obj, transients, shallow) {
} }
return clone; return clone;
}; };

View File

@ -5,10 +5,9 @@
* Type definitions from the typed-mxgraph project * Type definitions from the typed-mxgraph project
*/ */
import utils from '../Utils';
import InternalEvent from '../../view/event/InternalEvent'; import InternalEvent from '../../view/event/InternalEvent';
import Point from '../../view/geometry/Point'; import Point from '../../view/geometry/Point';
import mxPopupMenu from './mxPopupMenu'; import PopupMenu from './PopupMenu';
import EventSource from '../../view/event/EventSource'; import EventSource from '../../view/event/EventSource';
import EventObject from '../../view/event/EventObject'; import EventObject from '../../view/event/EventObject';
import mxClient from '../../mxClient'; import mxClient from '../../mxClient';
@ -109,7 +108,7 @@ class mxToolbar extends EventSource {
} }
} }
const mouseHandler = evt => { const mouseHandler = (evt) => {
if (pressedIcon != null) { if (pressedIcon != null) {
img.setAttribute('src', icon); img.setAttribute('src', icon);
} else { } else {
@ -121,7 +120,7 @@ class mxToolbar extends EventSource {
// while it is being clicked with the mouse // while it is being clicked with the mouse
InternalEvent.addGestureListeners( InternalEvent.addGestureListeners(
img, img,
evt => { (evt) => {
if (pressedIcon != null) { if (pressedIcon != null) {
img.setAttribute('src', pressedIcon); img.setAttribute('src', pressedIcon);
} else { } else {
@ -131,7 +130,7 @@ class mxToolbar extends EventSource {
// Popup Menu // Popup Menu
if (factoryMethod != null) { if (factoryMethod != null) {
if (this.menu == null) { if (this.menu == null) {
this.menu = new mxPopupMenu(); this.menu = new PopupMenu();
this.menu.init(); this.menu.init();
} }
@ -146,10 +145,7 @@ class mxToolbar extends EventSource {
this.currentImg = img; this.currentImg = img;
this.menu.factoryMethod = factoryMethod; this.menu.factoryMethod = factoryMethod;
const point = new Point( const point = new Point(img.offsetLeft, img.offsetTop + img.offsetHeight);
img.offsetLeft,
img.offsetTop + img.offsetHeight
);
this.menu.popup(point.x, point.y, null, evt); this.menu.popup(point.x, point.y, null, evt);
// Sets and overrides to restore classname // Sets and overrides to restore classname
@ -209,7 +205,7 @@ class mxToolbar extends EventSource {
select.className = style || 'mxToolbarCombo'; select.className = style || 'mxToolbarCombo';
this.addOption(select, title, null); this.addOption(select, title, null);
InternalEvent.addListener(select, 'change', evt => { InternalEvent.addListener(select, 'change', (evt) => {
const value = select.options[select.selectedIndex]; const value = select.options[select.selectedIndex];
select.selectedIndex = 0; select.selectedIndex = 0;
@ -266,7 +262,7 @@ class mxToolbar extends EventSource {
img.setAttribute('title', title); img.setAttribute('title', title);
} }
InternalEvent.addListener(img, 'click', evt => { InternalEvent.addListener(img, 'click', (evt) => {
let tmp = this.selectedMode.altIcon; let tmp = this.selectedMode.altIcon;
if (tmp != null) { if (tmp != null) {
@ -333,12 +329,12 @@ class mxToolbar extends EventSource {
} }
if (this.enabled && toggle) { if (this.enabled && toggle) {
InternalEvent.addListener(img, 'click', evt => { InternalEvent.addListener(img, 'click', (evt) => {
this.selectMode(img, funct); this.selectMode(img, funct);
this.noReset = false; this.noReset = false;
}); });
InternalEvent.addListener(img, 'dblclick', evt => { InternalEvent.addListener(img, 'dblclick', (evt) => {
this.selectMode(img, funct); this.selectMode(img, funct);
this.noReset = true; this.noReset = true;
}); });

View File

@ -5,12 +5,12 @@
* Type definitions from the typed-mxgraph project * Type definitions from the typed-mxgraph project
*/ */
import mxObjectIdentity from '../mxObjectIdentity'; import ObjectIdentity from '../ObjectIdentity';
import mxLog from '../gui/mxLog'; import mxLog from '../gui/mxLog';
import Geometry from '../../view/geometry/Geometry'; import Geometry from '../../view/geometry/Geometry';
import Point from '../../view/geometry/Point'; import Point from '../../view/geometry/Point';
import { NODETYPE_ELEMENT } from '../Constants'; import { NODETYPE_ELEMENT } from '../Constants';
import utils, { isInteger, isNumeric } from '../Utils'; import { isInteger, isNumeric } from '../Utils';
import { getTextContent } from '../DomUtils'; import { getTextContent } from '../DomUtils';
import { load } from '../network/mxXmlRequest'; import { load } from '../network/mxXmlRequest';
@ -303,7 +303,7 @@ class mxObjectCodec {
/** /**
* Returns true if the given attribute is to be ignored by the codec. This * Returns true if the given attribute is to be ignored by the codec. This
* implementation returns true if the given fieldname is in {@link exclude} or * implementation returns true if the given fieldname is in {@link exclude} or
* if the fieldname equals {@link mxObjectIdentity.FIELD_NAME}. * if the fieldname equals {@link ObjectIdentity.FIELD_NAME}.
* *
* @param obj Object instance that contains the field. * @param obj Object instance that contains the field.
* @param attr Fieldname of the field. * @param attr Fieldname of the field.
@ -313,9 +313,7 @@ class mxObjectCodec {
*/ */
// isExcluded(obj: any, attr: string, value: any, write?: boolean): boolean; // isExcluded(obj: any, attr: string, value: any, write?: boolean): boolean;
isExcluded(obj, attr, value, write) { isExcluded(obj, attr, value, write) {
return ( return attr == ObjectIdentity.FIELD_NAME || this.exclude.indexOf(attr) >= 0;
attr == mxObjectIdentity.FIELD_NAME || this.exclude.indexOf(attr) >= 0
);
} }
/** /**
@ -495,9 +493,7 @@ class mxObjectCodec {
node.appendChild(child); node.appendChild(child);
} else { } else {
mxLog.warn( mxLog.warn(`mxObjectCodec.encode: No node for ${this.getName()}.${name}: ${value}`);
`mxObjectCodec.encode: No node for ${this.getName()}.${name}: ${value}`
);
} }
} }
@ -532,9 +528,7 @@ class mxObjectCodec {
*/ */
// isBooleanAttribute(enc: mxCodec, obj: any, name: string, value: any): boolean; // isBooleanAttribute(enc: mxCodec, obj: any, name: string, value: any): boolean;
isBooleanAttribute(enc, obj, name, value) { isBooleanAttribute(enc, obj, name, value) {
return ( return typeof value.length === 'undefined' && (value == true || value == false);
typeof value.length === 'undefined' && (value == true || value == false)
);
} }
/** /**
@ -576,8 +570,7 @@ class mxObjectCodec {
attr.name === 'y' || attr.name === 'y' ||
attr.name === 'width' || attr.name === 'width' ||
attr.name === 'height')) || attr.name === 'height')) ||
(obj.constructor === Point && (obj.constructor === Point && (attr.name === 'x' || attr.name === 'y')) ||
(attr.name === 'x' || attr.name === 'y')) ||
isNumeric(attr.value); isNumeric(attr.value);
return result; return result;
@ -782,10 +775,7 @@ class mxObjectCodec {
while (child != null) { while (child != null) {
const tmp = child.nextSibling; const tmp = child.nextSibling;
if ( if (child.nodeType === NODETYPE_ELEMENT && !this.processInclude(dec, child, obj)) {
child.nodeType === NODETYPE_ELEMENT &&
!this.processInclude(dec, child, obj)
) {
this.decodeChild(dec, child, obj); this.decodeChild(dec, child, obj);
} }

View File

@ -203,6 +203,10 @@ type PartialDragDrop = Pick<
'isDropEnabled' | 'isAutoScroll' | 'isAutoExtend' | 'isSplitEnabled' | 'isSplitTarget' 'isDropEnabled' | 'isAutoScroll' | 'isAutoExtend' | 'isSplitEnabled' | 'isSplitTarget'
>; >;
type PartialSwimlane = Pick<GraphSwimlane, 'getDropTarget'>; type PartialSwimlane = Pick<GraphSwimlane, 'getDropTarget'>;
type PartialPorts = Pick<
GraphPorts,
'isPort' | 'getTerminalForPort' | 'isPortsEnabled' | 'setPortsEnabled'
>;
type PartialClass = PartialEvents & type PartialClass = PartialEvents &
PartialSelection & PartialSelection &
PartialCells & PartialCells &
@ -220,6 +224,7 @@ type PartialClass = PartialEvents &
PartialZoom & PartialZoom &
PartialDragDrop & PartialDragDrop &
PartialSwimlane & PartialSwimlane &
PartialPorts &
EventSource; EventSource;
export type MaxGraph = Graph & PartialClass; export type MaxGraph = Graph & PartialClass;

View File

@ -15,7 +15,7 @@ import {
import Point from './geometry/Point'; import Point from './geometry/Point';
import Rectangle from './geometry/Rectangle'; import Rectangle from './geometry/Rectangle';
import RectangleShape from './geometry/shape/node/RectangleShape'; import RectangleShape from './geometry/shape/node/RectangleShape';
import graph from './Graph'; import graph, { MaxGraph } from './Graph';
import ImageShape from './geometry/shape/node/ImageShape'; import ImageShape from './geometry/shape/node/ImageShape';
import InternalEvent from './event/InternalEvent'; import InternalEvent from './event/InternalEvent';
import utils from '../util/Utils'; import utils from '../util/Utils';
@ -71,7 +71,7 @@ import EventSource from './event/EventSource';
* ``` * ```
*/ */
class Outline { class Outline {
constructor(source: graph, container: HTMLElement | null = null) { constructor(source: MaxGraph, container: HTMLElement | null = null) {
this.source = source; this.source = source;
if (container != null) { if (container != null) {
@ -224,7 +224,7 @@ class Outline {
/** /**
* Reference to the source {@link graph}. * Reference to the source {@link graph}.
*/ */
source: graph; source: MaxGraph;
/** /**
* Reference to the {@link graph} that renders the outline. * Reference to the {@link graph} that renders the outline.
@ -576,10 +576,7 @@ class Outline {
this.active = true; this.active = true;
const sourceContainer = <HTMLElement>this.source.container; const sourceContainer = <HTMLElement>this.source.container;
if ( if (this.source.useScrollbarsForPanning && hasScrollbars(this.source.container)) {
this.source.useScrollbarsForPanning &&
hasScrollbars(this.source.container)
) {
this.dx0 = sourceContainer.scrollLeft; this.dx0 = sourceContainer.scrollLeft;
this.dy0 = sourceContainer.scrollTop; this.dy0 = sourceContainer.scrollTop;
} else { } else {

View File

@ -13,7 +13,7 @@ import Shape from '../../geometry/shape/Shape';
import TextShape from '../../geometry/shape/node/TextShape'; import TextShape from '../../geometry/shape/node/TextShape';
import Dictionary from '../../../util/Dictionary'; import Dictionary from '../../../util/Dictionary';
import { NONE } from '../../../util/Constants'; import { NONE } from '../../../util/Constants';
import { CellStateStyles } from 'packages/core/src/types'; import { CellStateStyles } from 'core/types';
import RectangleShape from '../../geometry/shape/node/RectangleShape'; import RectangleShape from '../../geometry/shape/node/RectangleShape';
import CellOverlay from '../CellOverlay'; import CellOverlay from '../CellOverlay';

View File

@ -59,7 +59,7 @@ import {
import Graph, { MaxGraph } from '../../Graph'; import Graph, { MaxGraph } from '../../Graph';
import CellState from '../datatypes/CellState'; import CellState from '../datatypes/CellState';
import Shape from '../../geometry/shape/Shape'; import Shape from '../../geometry/shape/Shape';
import { CellHandle, ColorValue, Listenable } from 'packages/core/src/types'; import { CellHandle, ColorValue, Listenable } from 'core/types';
import InternalMouseEvent from '../../event/InternalMouseEvent'; import InternalMouseEvent from '../../event/InternalMouseEvent';
import Cell from '../datatypes/Cell'; import Cell from '../datatypes/Cell';
import ImageBox from '../../image/ImageBox'; import ImageBox from '../../image/ImageBox';

View File

@ -1,7 +1,6 @@
import Cell from '../datatypes/Cell'; import Cell from '../datatypes/Cell';
import Geometry from '../../geometry/Geometry'; import Geometry from '../../geometry/Geometry';
import CellArray from '../datatypes/CellArray'; import { autoImplement } from 'core/util/Utils';
import { autoImplement } from 'packages/core/src/util/Utils';
import type GraphCells from '../GraphCells'; import type GraphCells from '../GraphCells';

View File

@ -26,7 +26,7 @@ import CellState from '../datatypes/CellState';
import CellArray from '../datatypes/CellArray'; import CellArray from '../datatypes/CellArray';
import type { MaxGraph } from '../../Graph'; import type { MaxGraph } from '../../Graph';
import type { CellHandle, CellStateStyles } from 'packages/core/src/types'; import type { CellHandle, CellStateStyles } from 'core/types';
/** /**
* Implements a single custom handle for vertices. * Implements a single custom handle for vertices.

View File

@ -33,7 +33,7 @@ import Graph, { MaxGraph } from '../../Graph';
import CellState from '../datatypes/CellState'; import CellState from '../datatypes/CellState';
import Image from '../../image/ImageBox'; import Image from '../../image/ImageBox';
import Cell from '../datatypes/Cell'; import Cell from '../datatypes/Cell';
import { CellHandle, Listenable } from 'packages/core/src/types'; import { CellHandle, Listenable } from 'core/types';
import Shape from '../../geometry/shape/Shape'; import Shape from '../../geometry/shape/Shape';
import InternalMouseEvent from '../../event/InternalMouseEvent'; import InternalMouseEvent from '../../event/InternalMouseEvent';
import VertexHandle from './VertexHandle'; import VertexHandle from './VertexHandle';

View File

@ -7,8 +7,8 @@
import Rectangle from '../Rectangle'; import Rectangle from '../Rectangle';
import Shape from './Shape'; import Shape from './Shape';
import SvgCanvas2D from '../../../util/canvas/SvgCanvas2D'; import SvgCanvas2D from '../../../util/canvas/SvgCanvas2D';
import { ColorValue } from 'packages/core/src/types'; import { ColorValue } from 'core/types';
import { NONE } from 'packages/core/src/util/Constants'; import { NONE } from 'core/util/Constants';
/** /**
* Extends {@link Shape} to implement an actor shape. If a custom shape with one * Extends {@link Shape} to implement an actor shape. If a custom shape with one

View File

@ -23,7 +23,7 @@ import {
SHADOW_OFFSET_Y, SHADOW_OFFSET_Y,
} from '../../../util/Constants'; } from '../../../util/Constants';
import Point from '../Point'; import Point from '../Point';
import AbstractCanvas2D from 'packages/core/src/util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from 'core/util/canvas/AbstractCanvas2D';
import SvgCanvas2D from '../../../util/canvas/SvgCanvas2D'; import SvgCanvas2D from '../../../util/canvas/SvgCanvas2D';
import InternalEvent from '../../event/InternalEvent'; import InternalEvent from '../../event/InternalEvent';
import mxClient from '../../../mxClient'; import mxClient from '../../../mxClient';

View File

@ -9,7 +9,7 @@ import { ARROW_SIZE, ARROW_SPACING, ARROW_WIDTH } from '../../../../util/Constan
import Rectangle from '../../Rectangle'; import Rectangle from '../../Rectangle';
import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D';
import Point from '../../Point'; import Point from '../../Point';
import { ColorValue } from 'packages/core/src/types'; import { ColorValue } from 'core/types';
/** /**
* Extends {@link Shape} to implement an arrow shape. The shape is used to represent edges, not vertices. * Extends {@link Shape} to implement an arrow shape. The shape is used to represent edges, not vertices.

View File

@ -11,7 +11,7 @@ import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D';
import Point from '../../Point'; import Point from '../../Point';
import Rectangle from '../../Rectangle'; import Rectangle from '../../Rectangle';
import CellState from '../../../cell/datatypes/CellState'; import CellState from '../../../cell/datatypes/CellState';
import { ColorValue } from 'packages/core/src/types'; import { ColorValue } from 'core/types';
/** /**
* Extends {@link Shape} to implement an new rounded arrow shape with support for waypoints and double arrows. The * Extends {@link Shape} to implement an new rounded arrow shape with support for waypoints and double arrows. The

View File

@ -11,7 +11,7 @@ import Marker from './Marker';
import Point from '../../Point'; import Point from '../../Point';
import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D';
import Rectangle from '../../Rectangle'; import Rectangle from '../../Rectangle';
import { ColorValue } from 'packages/core/src/types'; import { ColorValue } from 'core/types';
/** /**
* Extends {@link mxShape} to implement a connector shape. * Extends {@link mxShape} to implement a connector shape.

View File

@ -7,7 +7,7 @@
import Shape from '../Shape'; import Shape from '../Shape';
import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D';
import Rectangle from '../../Rectangle'; import Rectangle from '../../Rectangle';
import { ColorValue } from 'packages/core/src/types'; import { ColorValue } from 'core/types';
/** /**
* Extends {@link Shape} to implement a horizontal line shape. * Extends {@link Shape} to implement a horizontal line shape.

View File

@ -4,8 +4,8 @@
* Updated to ES9 syntax by David Morrissey 2021 * Updated to ES9 syntax by David Morrissey 2021
* Type definitions from the typed-mxgraph project * Type definitions from the typed-mxgraph project
*/ */
import { ArrowType } from 'packages/core/src/types'; import { ArrowType } from 'core/types';
import AbstractCanvas2D from 'packages/core/src/util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from 'core/util/canvas/AbstractCanvas2D';
import { import {
ARROW_CLASSIC, ARROW_CLASSIC,
ARROW_CLASSIC_THIN, ARROW_CLASSIC_THIN,

View File

@ -8,7 +8,7 @@ import Shape from '../Shape';
import { LINE_ARCSIZE } from '../../../../util/Constants'; import { LINE_ARCSIZE } from '../../../../util/Constants';
import Point from '../../Point'; import Point from '../../Point';
import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D';
import { ColorValue } from 'packages/core/src/types'; import { ColorValue } from 'core/types';
/** /**
* Class: mxPolyline * Class: mxPolyline

View File

@ -7,7 +7,7 @@
import Shape from '../Shape'; import Shape from '../Shape';
import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D';
import Rectangle from '../../Rectangle'; import Rectangle from '../../Rectangle';
import { NONE } from 'packages/core/src/util/Constants'; import { NONE } from 'core/util/Constants';
/** /**
* Extends {@link Shape} to implement an cylinder shape. If a custom shape with one filled area and an overlay path is * Extends {@link Shape} to implement an cylinder shape. If a custom shape with one filled area and an overlay path is

View File

@ -10,7 +10,7 @@ import Rectangle from '../../Rectangle';
import CellState from '../../../cell/datatypes/CellState'; import CellState from '../../../cell/datatypes/CellState';
import AbstractCanvas2D from '../../../../util/canvas/SvgCanvas2D'; import AbstractCanvas2D from '../../../../util/canvas/SvgCanvas2D';
import CellOverlay from '../../../cell/CellOverlay'; import CellOverlay from '../../../cell/CellOverlay';
import { NONE } from 'packages/core/src/util/Constants'; import { NONE } from 'core/util/Constants';
/** /**
* Extends {@link mxShape} to implement an image shape. * Extends {@link mxShape} to implement an image shape.

View File

@ -16,8 +16,8 @@ import {
NONE, NONE,
} from '../../../../util/Constants'; } from '../../../../util/Constants';
import RectangleShape from './RectangleShape'; import RectangleShape from './RectangleShape';
import { ColorValue } from 'packages/core/src/types'; import { ColorValue } from 'core/types';
import AbstractCanvas2D from 'packages/core/src/util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from 'core/util/canvas/AbstractCanvas2D';
/** /**
* Class: mxLabel * Class: mxLabel

View File

@ -13,7 +13,7 @@ import {
import Shape from '../Shape'; import Shape from '../Shape';
import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D';
import Rectangle from '../../Rectangle'; import Rectangle from '../../Rectangle';
import { ColorValue } from 'packages/core/src/types'; import { ColorValue } from 'core/types';
/** /**
* Extends {@link Shape} to implement a rectangle shape. * Extends {@link Shape} to implement a rectangle shape.

View File

@ -24,7 +24,7 @@ import StencilShapeRegistry from './StencilShapeRegistry';
import { getChildNodes, getTextContent } from '../../../../util/DomUtils'; import { getChildNodes, getTextContent } from '../../../../util/DomUtils';
import Point from '../../Point'; import Point from '../../Point';
import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D';
import { AlignValue, ColorValue, VAlignValue } from 'packages/core/src/types'; import { AlignValue, ColorValue, VAlignValue } from 'core/types';
/** /**
* Implements a generic shape which is based on a XML node as a description. * Implements a generic shape which is based on a XML node as a description.

View File

@ -15,8 +15,8 @@ import {
NONE, NONE,
RECTANGLE_ROUNDING_FACTOR, RECTANGLE_ROUNDING_FACTOR,
} from '../../../../util/Constants'; } from '../../../../util/Constants';
import { ColorValue } from 'packages/core/src/types'; import { ColorValue } from 'core/types';
import AbstractCanvas2D from 'packages/core/src/util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from 'core/util/canvas/AbstractCanvas2D';
/** /**
* Extends {@link Shape} to implement a swimlane shape. * Extends {@link Shape} to implement a swimlane shape.

View File

@ -47,8 +47,8 @@ import {
OverflowValue, OverflowValue,
TextDirectionValue, TextDirectionValue,
VAlignValue, VAlignValue,
} from 'packages/core/src/types'; } from 'core/types';
import SvgCanvas2D from 'packages/core/src/util/canvas/SvgCanvas2D'; import SvgCanvas2D from 'core/util/canvas/SvgCanvas2D';
/** /**
* Extends mxShape to implement a text shape. * Extends mxShape to implement a text shape.

View File

@ -8,7 +8,7 @@
import Point from '../../Point'; import Point from '../../Point';
import Actor from '../Actor'; import Actor from '../Actor';
import { LINE_ARCSIZE } from '../../../../util/Constants'; import { LINE_ARCSIZE } from '../../../../util/Constants';
import AbstractCanvas2D from 'packages/core/src/util/canvas/AbstractCanvas2D'; import AbstractCanvas2D from 'core/util/canvas/AbstractCanvas2D';
/** /**
* Implementation of the triangle shape. * Implementation of the triangle shape.

View File

@ -1,20 +1,53 @@
import Cell from "../cell/datatypes/Cell"; import Cell from '../cell/datatypes/Cell';
import CellArray from "../cell/datatypes/CellArray"; import CellArray from '../cell/datatypes/CellArray';
import {sortCells} from "../../util/Utils"; import { autoImplement, sortCells } from '../../util/Utils';
import Geometry from "../geometry/Geometry"; import Geometry from '../geometry/Geometry';
import EventObject from "../event/EventObject"; import EventObject from '../event/EventObject';
import InternalEvent from "../event/InternalEvent"; import InternalEvent from '../event/InternalEvent';
import Rectangle from "../geometry/Rectangle"; import Rectangle from '../geometry/Rectangle';
import Point from "../geometry/Point"; import Point from '../geometry/Point';
import Graph from "../Graph"; import Graph from '../Graph';
import GraphSelection from '../selection/GraphSelection';
import GraphCells from '../cell/GraphCells';
import GraphSwimlane from '../swimlane/GraphSwimlane';
import GraphEdge from '../cell/edge/GraphEdge';
class GraphGrouping { type PartialGraph = Pick<
constructor(graph: Graph) { Graph,
this.graph = graph; | 'getModel'
} | 'fireEvent'
| 'getView'
graph: Graph; | 'getDefaultParent'
| 'batchUpdate'
| 'isValidRoot'
| 'getCurrentRoot'
>;
type PartialCells = Pick<
GraphCells,
| 'cellsAdded'
| 'cellsMoved'
| 'cellsResized'
| 'getBoundingBoxFromGeometry'
| 'cellsRemoved'
| 'getChildCells'
| 'moveCells'
>;
type PartialEdge = Pick<GraphEdge, 'addAllEdges'>;
type PartialSelection = Pick<
GraphSelection,
'getSelectionCells' | 'getSelectionCell' | 'clearSelection' | 'setSelectionCell'
>;
type PartialSwimlane = Pick<
GraphSwimlane,
'isSwimlane' | 'getStartSize' | 'getActualStartSize'
>;
type PartialClass = PartialGraph &
PartialCells &
PartialEdge &
PartialSelection &
PartialSwimlane;
class GraphGrouping extends autoImplement<PartialClass>() {
/***************************************************************************** /*****************************************************************************
* Group: Grouping * Group: Grouping
*****************************************************************************/ *****************************************************************************/
@ -55,12 +88,12 @@ class GraphGrouping {
parent = <Cell>cells[0].getParent(); parent = <Cell>cells[0].getParent();
} }
this.graph.model.beginUpdate(); this.getModel().beginUpdate();
try { try {
// Checks if the group has a geometry and // Checks if the group has a geometry and
// creates one if one does not exist // creates one if one does not exist
if (group.getGeometry() == null) { if (group.getGeometry() == null) {
this.graph.model.setGeometry(group, new Geometry()); this.getModel().setGeometry(group, new Geometry());
} }
// Adds the group into the parent // Adds the group into the parent
@ -84,7 +117,7 @@ class GraphGrouping {
// Resizes the group // Resizes the group
this.cellsResized(new CellArray(group), [bounds], false); this.cellsResized(new CellArray(group), [bounds], false);
this.graph.fireEvent( this.fireEvent(
new EventObject( new EventObject(
InternalEvent.GROUP_CELLS, InternalEvent.GROUP_CELLS,
'group', 'group',
@ -96,7 +129,7 @@ class GraphGrouping {
) )
); );
} finally { } finally {
this.graph.model.endUpdate(); this.getModel().endUpdate();
} }
} }
return group; return group;
@ -125,10 +158,11 @@ class GraphGrouping {
/** /**
* Returns the bounds to be used for the given group and children. * Returns the bounds to be used for the given group and children.
*/ */
getBoundsForGroup(group: Cell, getBoundsForGroup(
children: CellArray, group: Cell,
border: number | null): Rectangle | null { children: CellArray,
border: number | null
): Rectangle | null {
const result = this.getBoundingBoxFromGeometry(children, true); const result = this.getBoundingBoxFromGeometry(children, true);
if (result != null) { if (result != null) {
if (this.isSwimlane(group)) { if (this.isSwimlane(group)) {
@ -193,7 +227,7 @@ class GraphGrouping {
} }
if (cells != null && cells.length > 0) { if (cells != null && cells.length > 0) {
this.graph.model.beginUpdate(); this.getModel().beginUpdate();
try { try {
for (let i = 0; i < cells.length; i += 1) { for (let i = 0; i < cells.length; i += 1) {
let children = cells[i].getChildren(); let children = cells[i].getChildren();
@ -208,7 +242,7 @@ class GraphGrouping {
// Fix relative child cells // Fix relative child cells
for (const child of children) { for (const child of children) {
const state = this.graph.view.getState(child); const state = this.getView().getState(child);
let geo = child.getGeometry(); let geo = child.getGeometry();
if (state != null && geo != null && geo.relative) { if (state != null && geo != null && geo.relative) {
@ -217,18 +251,16 @@ class GraphGrouping {
geo.y = (<Point>state.origin).y; geo.y = (<Point>state.origin).y;
geo.relative = false; geo.relative = false;
this.graph.model.setGeometry(child, geo); this.getModel().setGeometry(child, geo);
} }
} }
} }
} }
this.removeCellsAfterUngroup(cells); this.removeCellsAfterUngroup(cells);
this.graph.fireEvent( this.fireEvent(new EventObject(InternalEvent.UNGROUP_CELLS, 'cells', cells));
new EventObject(InternalEvent.UNGROUP_CELLS, 'cells', cells)
);
} finally { } finally {
this.graph.model.endUpdate(); this.getModel().endUpdate();
} }
} }
return result; return result;
@ -272,7 +304,7 @@ class GraphGrouping {
if (cells == null) { if (cells == null) {
cells = this.getSelectionCells(); cells = this.getSelectionCells();
} }
this.graph.model.beginUpdate(); this.getModel().beginUpdate();
try { try {
const parent = this.getDefaultParent(); const parent = this.getDefaultParent();
const index = parent.getChildCount(); const index = parent.getChildCount();
@ -282,7 +314,7 @@ class GraphGrouping {
new EventObject(InternalEvent.REMOVE_CELLS_FROM_PARENT, 'cells', cells) new EventObject(InternalEvent.REMOVE_CELLS_FROM_PARENT, 'cells', cells)
); );
} finally { } finally {
this.graph.model.endUpdate(); this.getModel().endUpdate();
} }
return cells; return cells;
} }
@ -317,7 +349,7 @@ class GraphGrouping {
leftBorder: number = 0 leftBorder: number = 0
): CellArray { ): CellArray {
if (cells == null) { if (cells == null) {
cells = this.graph.selection.getSelectionCells(); cells = this.getSelectionCells();
} }
border = border != null ? border : 0; border = border != null ? border : 0;
@ -327,7 +359,7 @@ class GraphGrouping {
bottomBorder = bottomBorder != null ? bottomBorder : 0; bottomBorder = bottomBorder != null ? bottomBorder : 0;
leftBorder = leftBorder != null ? leftBorder : 0; leftBorder = leftBorder != null ? leftBorder : 0;
this.graph.batchUpdate(() => { this.batchUpdate(() => {
for (let i = cells.length - 1; i >= 0; i--) { for (let i = cells.length - 1; i >= 0; i--) {
let geo = cells[i].getGeometry(); let geo = cells[i].getGeometry();
if (geo == null) { if (geo == null) {
@ -348,32 +380,18 @@ class GraphGrouping {
geo = <Geometry>geo.clone(); geo = <Geometry>geo.clone();
if (moveGroup) { if (moveGroup) {
geo.x = Math.round( geo.x = Math.round(geo.x + bounds.x - border - size.x - leftBorder);
geo.x + bounds.x - border - size.x - leftBorder geo.y = Math.round(geo.y + bounds.y - border - size.y - topBorder);
);
geo.y = Math.round(
geo.y + bounds.y - border - size.y - topBorder
);
} }
geo.width = Math.round( geo.width = Math.round(
bounds.width + bounds.width + 2 * border + size.x + leftBorder + rightBorder + size.width
2 * border +
size.x +
leftBorder +
rightBorder +
size.width
); );
geo.height = Math.round( geo.height = Math.round(
bounds.height + bounds.height + 2 * border + size.y + topBorder + bottomBorder + size.height
2 * border +
size.y +
topBorder +
bottomBorder +
size.height
); );
this.graph.model.setGeometry(cells[i], geo); this.getModel().setGeometry(cells[i], geo);
this.moveCells( this.moveCells(
children, children,
border + size.x - bounds.x + leftBorder, border + size.x - bounds.x + leftBorder,
@ -402,7 +420,7 @@ class GraphGrouping {
cell = cell || this.getSelectionCell(); cell = cell || this.getSelectionCell();
if (cell != null && this.isValidRoot(cell)) { if (cell != null && this.isValidRoot(cell)) {
this.view.setCurrentRoot(cell); this.getView().setCurrentRoot(cell);
this.clearSelection(); this.clearSelection();
} }
} }
@ -416,30 +434,26 @@ class GraphGrouping {
const current = this.getCurrentRoot(); const current = this.getCurrentRoot();
if (current != null) { if (current != null) {
let next = <Cell>current.getParent(); let next = current.getParent();
// Finds the next valid root in the hierarchy // Finds the next valid root in the hierarchy
while ( while (next !== root && !this.isValidRoot(next) && next.getParent() !== root) {
next !== root &&
!this.isValidRoot(next) &&
next.getParent() !== root
) {
next = <Cell>next.getParent(); next = <Cell>next.getParent();
} }
// Clears the current root if the new root is // Clears the current root if the new root is
// the model's root or one of the layers. // the model's root or one of the layers.
if (next === root || next.getParent() === root) { if (next === root || next.getParent() === root) {
this.view.setCurrentRoot(null); this.getView().setCurrentRoot(null);
} else { } else {
this.view.setCurrentRoot(next); this.getView().setCurrentRoot(next);
} }
const state = this.view.getState(current); const state = this.getView().getState(current);
// Selects the previous root in the graph // Selects the previous root in the graph
if (state != null) { if (state != null) {
this.selection.setSelectionCell(current); this.setSelectionCell(current);
} }
} }
} }

View File

@ -1,16 +1,15 @@
import CellArray from "../cell/datatypes/CellArray"; import CellArray from '../cell/datatypes/CellArray';
import {sortCells} from "../../util/Utils"; import { autoImplement, sortCells } from '../../util/Utils';
import EventObject from "../event/EventObject"; import EventObject from '../event/EventObject';
import InternalEvent from "../event/InternalEvent"; import InternalEvent from '../event/InternalEvent';
import Graph from "../Graph"; import Graph from '../Graph';
import GraphSelection from '../selection/GraphSelection';
class GraphOrder { type PartialGraph = Pick<Graph, 'fireEvent' | 'batchUpdate' | 'getModel'>;
constructor(graph: Graph) { type PartialSelection = Pick<GraphSelection, 'getSelectionCells'>;
this.graph = graph; type PartialClass = PartialGraph & PartialSelection;
}
graph: Graph;
class GraphOrder extends autoImplement<PartialClass>() {
/***************************************************************************** /*****************************************************************************
* Group: Order * Group: Order
*****************************************************************************/ *****************************************************************************/
@ -26,17 +25,22 @@ class GraphOrder {
*/ */
orderCells( orderCells(
back: boolean = false, back: boolean = false,
cells: CellArray = this.graph.selection.getSelectionCells() cells: CellArray = this.getSelectionCells()
): CellArray { ): CellArray {
if (cells == null) { if (cells == null) {
cells = sortCells(this.graph.selection.getSelectionCells(), true); cells = sortCells(this.getSelectionCells(), true);
} }
this.graph.batchUpdate(() => { this.batchUpdate(() => {
this.cellsOrdered(cells, back); this.cellsOrdered(cells, back);
const event = new EventObject(InternalEvent.ORDER_CELLS, 'back', back, 'cells', cells); const event = new EventObject(
this.graph.events.fireEvent(event); InternalEvent.ORDER_CELLS,
'back',
back,
'cells',
cells
);
this.fireEvent(event);
}); });
return cells; return cells;
@ -49,25 +53,19 @@ class GraphOrder {
* @param cells Array of {@link mxCell} whose order should be changed. * @param cells Array of {@link mxCell} whose order should be changed.
* @param back Boolean that specifies if the cells should be moved to back. * @param back Boolean that specifies if the cells should be moved to back.
*/ */
cellsOrdered(cells: CellArray, cellsOrdered(cells: CellArray, back: boolean = false) {
back: boolean = false) { this.batchUpdate(() => {
this.graph.batchUpdate(() => {
for (let i = 0; i < cells.length; i += 1) { for (let i = 0; i < cells.length; i += 1) {
const parent = cells[i].getParent(); const parent = cells[i].getParent();
if (back) { if (back) {
this.graph.model.add(parent, cells[i], i); this.getModel().add(parent, cells[i], i);
} else { } else {
this.graph.model.add( this.getModel().add(parent, cells[i], parent ? parent.getChildCount() - 1 : 0);
parent,
cells[i],
parent ? parent.getChildCount() - 1 : 0
);
} }
} }
this.graph.events.fireEvent( this.fireEvent(
new EventObject(InternalEvent.CELLS_ORDERED, 'back', back, 'cells', cells) new EventObject(InternalEvent.CELLS_ORDERED, 'back', back, 'cells', cells)
); );
}); });

View File

@ -75,7 +75,8 @@ class ImageExport {
for (let i = 0; i < childCount; i += 1) { for (let i = 0; i < childCount; i += 1) {
const childState = graph.view.getState(state.cell.getChildAt(i)); const childState = graph.view.getState(state.cell.getChildAt(i));
this.visitStatesRecursive(childState, canvas, visitor);
if (childState) this.visitStatesRecursive(childState, canvas, visitor);
} }
} }
} }

View File

@ -4,7 +4,7 @@
* Updated to ES9 syntax by David Morrissey 2021 * Updated to ES9 syntax by David Morrissey 2021
* Type definitions from the typed-mxgraph project * Type definitions from the typed-mxgraph project
*/ */
import mxObjectIdentity from '../../../util/mxObjectIdentity'; import ObjectIdentity from '../../../util/ObjectIdentity';
import GraphLayout from './GraphLayout'; import GraphLayout from './GraphLayout';
import Graph from '../../Graph'; import Graph from '../../Graph';
import Cell from '../../cell/datatypes/Cell'; import Cell from '../../cell/datatypes/Cell';
@ -186,8 +186,7 @@ class MxFastOrganicLayout extends GraphLayout {
*/ */
isVertexIgnored(vertex: Cell) { isVertexIgnored(vertex: Cell) {
return ( return (
super.isVertexIgnored(vertex) || super.isVertexIgnored(vertex) || this.graph.getConnections(vertex).length === 0
this.graph.getConnections(vertex).length === 0
); );
} }
@ -237,7 +236,7 @@ class MxFastOrganicLayout extends GraphLayout {
this.cellLocation[i] = []; this.cellLocation[i] = [];
// Set up the mapping from array indices to cells // Set up the mapping from array indices to cells
const id = mxObjectIdentity.get(vertex); const id = ObjectIdentity.get(vertex);
this.indices[id] = i; this.indices[id] = i;
const bounds = this.getVertexBounds(vertex); const bounds = this.getVertexBounds(vertex);
@ -283,7 +282,7 @@ class MxFastOrganicLayout extends GraphLayout {
} }
// Looks the cell up in the indices dictionary // Looks the cell up in the indices dictionary
const id = mxObjectIdentity.get(cells[j]); const id = ObjectIdentity.get(cells[j]);
const index = this.indices[id]; const index = this.indices[id];
// Check the connected cell in part of the vertex list to be // Check the connected cell in part of the vertex list to be
@ -309,11 +308,7 @@ class MxFastOrganicLayout extends GraphLayout {
} }
// Main iteration loop // Main iteration loop
for ( for (this.iteration = 0; this.iteration < this.maxIterations; this.iteration += 1) {
this.iteration = 0;
this.iteration < this.maxIterations;
this.iteration += 1
) {
if (!this.allowedToRun) { if (!this.allowedToRun) {
return; return;
} }
@ -391,8 +386,7 @@ class MxFastOrganicLayout extends GraphLayout {
// Get the distance of displacement for this node for this // Get the distance of displacement for this node for this
// iteration // iteration
let deltaLength = Math.sqrt( let deltaLength = Math.sqrt(
this.dispX[index] * this.dispX[index] + this.dispX[index] * this.dispX[index] + this.dispY[index] * this.dispY[index]
this.dispY[index] * this.dispY[index]
); );
if (deltaLength < 0.001) { if (deltaLength < 0.001) {
@ -402,12 +396,10 @@ class MxFastOrganicLayout extends GraphLayout {
// Scale down by the current temperature if less than the // Scale down by the current temperature if less than the
// displacement distance // displacement distance
const newXDisp = const newXDisp =
(this.dispX[index] / deltaLength) * (this.dispX[index] / deltaLength) * Math.min(deltaLength, this.temperature);
Math.min(deltaLength, this.temperature);
const newYDisp = const newYDisp =
(this.dispY[index] / deltaLength) * (this.dispY[index] / deltaLength) * Math.min(deltaLength, this.temperature);
Math.min(deltaLength, this.temperature);
// reset displacements // reset displacements
this.dispX[index] = 0; this.dispX[index] = 0;
@ -495,8 +487,7 @@ class MxFastOrganicLayout extends GraphLayout {
// Distance between nodes // Distance between nodes
const deltaLength = Math.sqrt(xDelta * xDelta + yDelta * yDelta); const deltaLength = Math.sqrt(xDelta * xDelta + yDelta * yDelta);
let deltaLengthWithRadius = let deltaLengthWithRadius = deltaLength - this.radius[i] - this.radius[j];
deltaLength - this.radius[i] - this.radius[j];
if (deltaLengthWithRadius > this.maxDistanceLimit) { if (deltaLengthWithRadius > this.maxDistanceLimit) {
// Ignore vertices too far apart // Ignore vertices too far apart
@ -529,8 +520,7 @@ class MxFastOrganicLayout extends GraphLayout {
* fashion to zero. * fashion to zero.
*/ */
reduceTemperature() { reduceTemperature() {
this.temperature = this.temperature = this.initialTemp * (1.0 - this.iteration / this.maxIterations);
this.initialTemp * (1.0 - this.iteration / this.maxIterations);
} }
} }

View File

@ -7,7 +7,7 @@
import Point from '../../geometry/Point'; import Point from '../../geometry/Point';
import GraphLayout from './GraphLayout'; import GraphLayout from './GraphLayout';
import mxObjectIdentity from '../../../util/mxObjectIdentity'; import ObjectIdentity from '../../../util/ObjectIdentity';
import Graph from '../../Graph'; import Graph from '../../Graph';
import CellArray from '../../cell/datatypes/CellArray'; import CellArray from '../../cell/datatypes/CellArray';
import Cell from '../../cell/datatypes/Cell'; import Cell from '../../cell/datatypes/Cell';
@ -105,7 +105,7 @@ class ParallelEdgeLayout extends GraphLayout {
findParallels(parent: Cell, cells: CellArray) { findParallels(parent: Cell, cells: CellArray) {
const lookup = []; const lookup = [];
const addCell = cell => { const addCell = (cell) => {
if (!this.isEdgeIgnored(cell)) { if (!this.isEdgeIgnored(cell)) {
const id = this.getEdgeId(cell); const id = this.getEdgeId(cell);
@ -151,8 +151,8 @@ class ParallelEdgeLayout extends GraphLayout {
let pts = ''; let pts = '';
if (src != null && trg != null) { if (src != null && trg != null) {
src = mxObjectIdentity.get(src); src = ObjectIdentity.get(src);
trg = mxObjectIdentity.get(trg); trg = ObjectIdentity.get(trg);
if (this.checkOverlap) { if (this.checkOverlap) {
const state = this.graph.view.getState(edge); const state = this.graph.view.getState(edge);

View File

@ -11,7 +11,7 @@ import HierarchicalEdgeStyle from './HierarchicalEdgeStyle';
import Dictionary from '../../../../util/Dictionary'; import Dictionary from '../../../../util/Dictionary';
import Rectangle from '../../../geometry/Rectangle'; import Rectangle from '../../../geometry/Rectangle';
import SwimlaneModel from './model/SwimlaneModel'; import SwimlaneModel from './model/SwimlaneModel';
import mxObjectIdentity from '../../../../util/mxObjectIdentity'; import ObjectIdentity from '../../../../util/ObjectIdentity';
import mxSwimlaneOrdering from './stage/mxSwimlaneOrdering'; import mxSwimlaneOrdering from './stage/mxSwimlaneOrdering';
import MedianHybridCrossingReduction from './stage/MedianHybridCrossingReduction'; import MedianHybridCrossingReduction from './stage/MedianHybridCrossingReduction';
import CoordinateAssignment from './stage/CoordinateAssignment'; import CoordinateAssignment from './stage/CoordinateAssignment';
@ -694,7 +694,7 @@ class SwimlaneLayout extends GraphLayout {
cell.getParent() !== this.parent && cell.getParent() !== this.parent &&
cell.isVisible() cell.isVisible()
) { ) {
result[mxObjectIdentity.get(cell)] = cell; result[ObjectIdentity.get(cell)] = cell;
} }
if (this.traverseAncestors || (cell === this.parent && cell.isVisible())) { if (this.traverseAncestors || (cell === this.parent && cell.isVisible())) {
@ -792,7 +792,7 @@ class SwimlaneLayout extends GraphLayout {
// Has this vertex been seen before in any traversal // Has this vertex been seen before in any traversal
// And if the filled vertex set is populated, only // And if the filled vertex set is populated, only
// process vertices in that it contains // process vertices in that it contains
const vertexID = mxObjectIdentity.get(vertex); const vertexID = ObjectIdentity.get(vertex);
if ( if (
allVertices[vertexID] == null && allVertices[vertexID] == null &&

View File

@ -4,65 +4,65 @@
* Updated to ES9 syntax by David Morrissey 2021 * Updated to ES9 syntax by David Morrissey 2021
* Type definitions from the typed-mxgraph project * Type definitions from the typed-mxgraph project
*/ */
import CellArray from 'core/view/cell/datatypes/CellArray';
import Cell from '../../../../cell/datatypes/Cell'; import Cell from '../../../../cell/datatypes/Cell';
import CellArray from '../../../../cell/datatypes/CellArray';
class MxGraphAbstractHierarchyCell { class GraphAbstractHierarchyCell extends Cell {
/** /**
* Variable: maxRank * Variable: maxRank
* *
* The maximum rank this cell occupies. Default is -1. * The maximum rank this cell occupies. Default is -1.
*/ */
maxRank: number = -1; maxRank = -1;
/** /**
* Variable: minRank * Variable: minRank
* *
* The minimum rank this cell occupies. Default is -1. * The minimum rank this cell occupies. Default is -1.
*/ */
minRank: number = -1; minRank = -1;
/** /**
* Variable: x * Variable: x
* *
* The x position of this cell for each layer it occupies * The x position of this cell for each layer it occupies
*/ */
x: number = null; x: number[];
/** /**
* Variable: y * Variable: y
* *
* The y position of this cell for each layer it occupies * The y position of this cell for each layer it occupies
*/ */
y: number = null; y: number[];
/** /**
* Variable: width * Variable: width
* *
* The width of this cell. Default is 0. * The width of this cell. Default is 0.
*/ */
width: number = 0; width = 0;
/** /**
* Variable: height * Variable: height
* *
* The height of this cell. Default is 0. * The height of this cell. Default is 0.
*/ */
height: number = 0; height = 0;
/** /**
* Variable: nextLayerConnectedCells * Variable: nextLayerConnectedCells
* *
* A cached version of the cells this cell connects to on the next layer up * A cached version of the cells this cell connects to on the next layer up
*/ */
nextLayerConnectedCells: CellArray | null = null; nextLayerConnectedCells: CellArray[] | null = null;
/** /**
* Variable: previousLayerConnectedCells * Variable: previousLayerConnectedCells
* *
* A cached version of the cells this cell connects to on the next layer down * A cached version of the cells this cell connects to on the next layer down
*/ */
previousLayerConnectedCells: CellArray | null = null; previousLayerConnectedCells: CellArray[] | null = null;
/** /**
* Variable: temp * Variable: temp
@ -74,7 +74,7 @@ class MxGraphAbstractHierarchyCell {
* be used for hashing the nodes in the model dfs and so hashCode * be used for hashing the nodes in the model dfs and so hashCode
* was created * was created
*/ */
temp: any = null; temp: number[];
/** /**
* Class: mxGraphAbstractHierarchyCell * Class: mxGraphAbstractHierarchyCell
@ -86,6 +86,8 @@ class MxGraphAbstractHierarchyCell {
* Constructs a new hierarchical layout algorithm. * Constructs a new hierarchical layout algorithm.
*/ */
constructor() { constructor() {
super();
this.x = []; this.x = [];
this.y = []; this.y = [];
this.temp = []; this.temp = [];
@ -96,7 +98,7 @@ class MxGraphAbstractHierarchyCell {
* *
* Returns the cells this cell connects to on the next layer up * Returns the cells this cell connects to on the next layer up
*/ */
getNextLayerConnectedCells(layer: number): Cell | null { getNextLayerConnectedCells(layer: number): CellArray | null {
return null; return null;
} }
@ -105,7 +107,7 @@ class MxGraphAbstractHierarchyCell {
* *
* Returns the cells this cell connects to on the next layer down * Returns the cells this cell connects to on the next layer down
*/ */
getPreviousLayerConnectedCells(layer: number): Cell | null { getPreviousLayerConnectedCells(layer: number): CellArray | null {
return null; return null;
} }
@ -114,7 +116,7 @@ class MxGraphAbstractHierarchyCell {
* *
* Returns whether or not this cell is an edge * Returns whether or not this cell is an edge
*/ */
isEdge(): boolean { isEdge() {
return false; return false;
} }
@ -123,7 +125,7 @@ class MxGraphAbstractHierarchyCell {
* *
* Returns whether or not this cell is a node * Returns whether or not this cell is a node
*/ */
isVertex(): boolean { isVertex() {
return false; return false;
} }
@ -132,7 +134,7 @@ class MxGraphAbstractHierarchyCell {
* *
* Gets the value of temp for the specified layer * Gets the value of temp for the specified layer
*/ */
getGeneralPurposeVariable(layer: number): null | number { getGeneralPurposeVariable(layer: number): number | null {
return null; return null;
} }
@ -141,16 +143,14 @@ class MxGraphAbstractHierarchyCell {
* *
* Set the value of temp for the specified layer * Set the value of temp for the specified layer
*/ */
setGeneralPurposeVariable(layer: number, value: number): null | void { setGeneralPurposeVariable(layer: number, value: number) {}
return null;
}
/** /**
* Function: setX * Function: setX
* *
* Set the value of x for the specified layer * Set the value of x for the specified layer
*/ */
setX(layer: number, value: number): void { setX(layer: number, value: number) {
if (this.isVertex()) { if (this.isVertex()) {
this.x[0] = value; this.x[0] = value;
} else if (this.isEdge()) { } else if (this.isEdge()) {
@ -163,7 +163,7 @@ class MxGraphAbstractHierarchyCell {
* *
* Gets the value of x on the specified layer * Gets the value of x on the specified layer
*/ */
getX(layer: number): number { getX(layer: number) {
if (this.isVertex()) { if (this.isVertex()) {
return this.x[0]; return this.x[0];
} }
@ -178,7 +178,7 @@ class MxGraphAbstractHierarchyCell {
* *
* Set the value of y for the specified layer * Set the value of y for the specified layer
*/ */
setY(layer: number, value: number): void { setY(layer: number, value: number) {
if (this.isVertex()) { if (this.isVertex()) {
this.y[0] = value; this.y[0] = value;
} else if (this.isEdge()) { } else if (this.isEdge()) {
@ -187,4 +187,4 @@ class MxGraphAbstractHierarchyCell {
} }
} }
export default MxGraphAbstractHierarchyCell; export default GraphAbstractHierarchyCell;

View File

@ -5,7 +5,7 @@
* Type definitions from the typed-mxgraph project * Type definitions from the typed-mxgraph project
*/ */
import GraphAbstractHierarchyCell from './GraphAbstractHierarchyCell'; import GraphAbstractHierarchyCell from './GraphAbstractHierarchyCell';
import mxObjectIdentity from '../../../../../util/mxObjectIdentity'; import ObjectIdentity from '../../../../../util/ObjectIdentity';
import CellArray from '../../../../cell/datatypes/CellArray'; import CellArray from '../../../../cell/datatypes/CellArray';
import Cell from '../../../../cell/datatypes/Cell'; import Cell from '../../../../cell/datatypes/Cell';
@ -23,7 +23,7 @@ class GraphHierarchyEdge extends GraphAbstractHierarchyCell {
* *
* The object identities of the wrapped cells * The object identities of the wrapped cells
*/ */
ids = null; ids: string[];
/** /**
* Variable: source * Variable: source
@ -61,12 +61,12 @@ class GraphHierarchyEdge extends GraphAbstractHierarchyCell {
* edges - a list of real graph edges this abstraction represents * edges - a list of real graph edges this abstraction represents
*/ */
constructor(edges: CellArray) { constructor(edges: CellArray) {
super(edges); super();
this.edges = edges; this.edges = edges;
this.ids = []; this.ids = [];
for (let i = 0; i < edges.length; i += 1) { for (let i = 0; i < edges.length; i += 1) {
this.ids.push(mxObjectIdentity.get(edges[i])); this.ids.push(ObjectIdentity.get(edges[i]));
} }
} }
@ -75,7 +75,7 @@ class GraphHierarchyEdge extends GraphAbstractHierarchyCell {
* *
* Inverts the direction of this internal edge(s) * Inverts the direction of this internal edge(s)
*/ */
invert(layer) { invert() {
const temp = this.source; const temp = this.source;
this.source = this.target; this.source = this.target;
this.target = temp; this.target = temp;
@ -87,15 +87,15 @@ class GraphHierarchyEdge extends GraphAbstractHierarchyCell {
* *
* Returns the cells this cell connects to on the next layer up * Returns the cells this cell connects to on the next layer up
*/ */
getNextLayerConnectedCells(layer: Cell): CellArray { getNextLayerConnectedCells(layer: number) {
if (this.nextLayerConnectedCells == null) { if (this.nextLayerConnectedCells == null) {
this.nextLayerConnectedCells = []; this.nextLayerConnectedCells = [];
for (let i = 0; i < this.temp.length; i += 1) { for (let i = 0; i < this.temp.length; i += 1) {
this.nextLayerConnectedCells[i] = []; this.nextLayerConnectedCells[i] = new CellArray();
if (i === this.temp.length - 1) { if (i === this.temp.length - 1) {
this.nextLayerConnectedCells[i].push(this.source); this.nextLayerConnectedCells[i].push(this.source as Cell);
} else { } else {
this.nextLayerConnectedCells[i].push(this); this.nextLayerConnectedCells[i].push(this);
} }
@ -109,15 +109,15 @@ class GraphHierarchyEdge extends GraphAbstractHierarchyCell {
* *
* Returns the cells this cell connects to on the next layer down * Returns the cells this cell connects to on the next layer down
*/ */
getPreviousLayerConnectedCells(layer: Cell): CellArray { getPreviousLayerConnectedCells(layer: number) {
if (this.previousLayerConnectedCells == null) { if (this.previousLayerConnectedCells == null) {
this.previousLayerConnectedCells = []; this.previousLayerConnectedCells = [];
for (let i = 0; i < this.temp.length; i += 1) { for (let i = 0; i < this.temp.length; i += 1) {
this.previousLayerConnectedCells[i] = []; this.previousLayerConnectedCells[i] = new CellArray();
if (i === 0) { if (i === 0) {
this.previousLayerConnectedCells[i].push(this.target); this.previousLayerConnectedCells[i].push(this.target as Cell);
} else { } else {
this.previousLayerConnectedCells[i].push(this); this.previousLayerConnectedCells[i].push(this);
} }
@ -131,7 +131,7 @@ class GraphHierarchyEdge extends GraphAbstractHierarchyCell {
* *
* Returns true. * Returns true.
*/ */
isEdge(): boolean { isEdge() {
return true; return true;
} }
@ -140,7 +140,7 @@ class GraphHierarchyEdge extends GraphAbstractHierarchyCell {
* *
* Gets the value of temp for the specified layer * Gets the value of temp for the specified layer
*/ */
getGeneralPurposeVariable(layer: number): any { getGeneralPurposeVariable(layer: number) {
return this.temp[layer - this.minRank - 1]; return this.temp[layer - this.minRank - 1];
} }
@ -149,7 +149,7 @@ class GraphHierarchyEdge extends GraphAbstractHierarchyCell {
* *
* Set the value of temp for the specified layer * Set the value of temp for the specified layer
*/ */
setGeneralPurposeVariable(layer: number, value: any): void { setGeneralPurposeVariable(layer: number, value: number) {
this.temp[layer - this.minRank - 1] = value; this.temp[layer - this.minRank - 1] = value;
} }
@ -158,8 +158,8 @@ class GraphHierarchyEdge extends GraphAbstractHierarchyCell {
* *
* Gets the first core edge associated with this wrapper * Gets the first core edge associated with this wrapper
*/ */
getCoreCell(): Cell | null { getCoreCell() {
if (this.edges != null && this.edges.length > 0) { if (this.edges.length > 0) {
return this.edges[0]; return this.edges[0];
} }
return null; return null;

View File

@ -5,7 +5,7 @@
* Type definitions from the typed-mxgraph project * Type definitions from the typed-mxgraph project
*/ */
import MxGraphAbstractHierarchyCell from './GraphAbstractHierarchyCell'; import MxGraphAbstractHierarchyCell from './GraphAbstractHierarchyCell';
import mxObjectIdentity from '../../../../../util/mxObjectIdentity'; import ObjectIdentity from '../../../../../util/ObjectIdentity';
import CellArray from '../../../../cell/datatypes/CellArray'; import CellArray from '../../../../cell/datatypes/CellArray';
import Cell from '../../../../cell/datatypes/Cell'; import Cell from '../../../../cell/datatypes/Cell';
@ -26,9 +26,9 @@ class GraphHierarchyNode extends MxGraphAbstractHierarchyCell {
constructor(cell) { constructor(cell) {
super(cell); super(cell);
this.cell = cell; this.cell = cell;
this.id = mxObjectIdentity.get(cell); this.id = ObjectIdentity.get(cell);
this.connectsAsTarget: CellArray = []; this.connectsAsTarget = [];
this.connectsAsSource: CellArray = []; this.connectsAsSource = [];
} }
/** /**

View File

@ -9,7 +9,7 @@ import { DIRECTION_NORTH } from '../../../../util/Constants';
import HierarchicalEdgeStyle from './HierarchicalEdgeStyle'; import HierarchicalEdgeStyle from './HierarchicalEdgeStyle';
import Dictionary from '../../../../util/Dictionary'; import Dictionary from '../../../../util/Dictionary';
import GraphHierarchyModel from './model/GraphHierarchyModel'; import GraphHierarchyModel from './model/GraphHierarchyModel';
import mxObjectIdentity from '../../../../util/mxObjectIdentity'; import ObjectIdentity from '../../../../util/ObjectIdentity';
import MinimumCycleRemover from './stage/MinimumCycleRemover'; import MinimumCycleRemover from './stage/MinimumCycleRemover';
import MedianHybridCrossingReduction from './stage/MedianHybridCrossingReduction'; import MedianHybridCrossingReduction from './stage/MedianHybridCrossingReduction';
import CoordinateAssignment from './stage/CoordinateAssignment'; import CoordinateAssignment from './stage/CoordinateAssignment';
@ -249,8 +249,7 @@ class mxHierarchicalLayout extends GraphLayout {
const rootsCopy = []; const rootsCopy = [];
for (let i = 0; i < roots.length; i += 1) { for (let i = 0; i < roots.length; i += 1) {
const ancestor = const ancestor = parent != null ? model.isAncestor(parent, roots[i]) : true;
parent != null ? model.isAncestor(parent, roots[i]) : true;
if (ancestor && roots[i].isVertex()) { if (ancestor && roots[i].isVertex()) {
rootsCopy.push(roots[i]); rootsCopy.push(roots[i]);
@ -265,11 +264,7 @@ class mxHierarchicalLayout extends GraphLayout {
this.run(parent); this.run(parent);
if (this.resizeParent && !parent.isCollapsed()) { if (this.resizeParent && !parent.isCollapsed()) {
this.graph.updateGroupBounds( this.graph.updateGroupBounds([parent], this.parentBorder, this.moveParent);
[parent],
this.parentBorder,
this.moveParent
);
} }
// Maintaining parent location // Maintaining parent location
@ -574,7 +569,7 @@ class mxHierarchicalLayout extends GraphLayout {
const { model } = this.graph; const { model } = this.graph;
if (cell.isVertex() && cell !== this.parent && cell.isVisible()) { if (cell.isVertex() && cell !== this.parent && cell.isVisible()) {
result[mxObjectIdentity.get(cell)] = cell; result[ObjectIdentity.get(cell)] = cell;
} }
if (this.traverseAncestors || (cell === this.parent && cell.isVisible())) { if (this.traverseAncestors || (cell === this.parent && cell.isVisible())) {
@ -672,7 +667,7 @@ class mxHierarchicalLayout extends GraphLayout {
// Has this vertex been seen before in any traversal // Has this vertex been seen before in any traversal
// And if the filled vertex set is populated, only // And if the filled vertex set is populated, only
// process vertices in that it contains // process vertices in that it contains
const vertexID = mxObjectIdentity.get(vertex); const vertexID = ObjectIdentity.get(vertex);
if ( if (
allVertices[vertexID] == null && allVertices[vertexID] == null &&

View File

@ -1,13 +1,6 @@
import Cell from '../cell/datatypes/Cell'; import Cell from '../cell/datatypes/Cell';
import Graph from '../Graph';
class GraphPorts { class GraphPorts {
constructor(graph: Graph) {
this.graph = graph;
}
graph: Graph;
/** /**
* Specifies if ports are enabled. This is used in {@link cellConnected} to update * Specifies if ports are enabled. This is used in {@link cellConnected} to update
* the respective style. * the respective style.

View File

@ -1,6 +1,6 @@
const path = require('path'); const path = require('path');
const webpack = require('webpack'); const webpack = require('webpack');
const {merge} = require('webpack-merge'); const { merge } = require('webpack-merge');
const base = require('../../webpack.config'); const base = require('../../webpack.config');
const CircularDependencyPlugin = require('circular-dependency-plugin'); const CircularDependencyPlugin = require('circular-dependency-plugin');
@ -8,20 +8,20 @@ module.exports = merge(base, {
entry: './src/index.ts', entry: './src/index.ts',
resolve: { resolve: {
alias: { alias: {
'@': path.resolve(__dirname, 'src') '@': path.resolve(__dirname, 'src'),
} },
}, },
output: { output: {
filename: 'mxgraph.js', filename: 'mxgraph.js',
path: path.resolve(__dirname, 'dist'), path: path.resolve(__dirname, 'dist'),
library: 'mxgraph', library: 'mxgraph',
libraryTarget: 'umd' libraryTarget: 'umd',
}, },
module: { module: {
rules: [ rules: [
{ {
test: /\.(sa|sc|c)ss$/, test: /\.(sa|sc|c)ss$/,
use: ['style-loader', 'css-loader'] use: ['style-loader', 'css-loader'],
}, },
{ {
test: /\.(ico|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/, test: /\.(ico|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
@ -30,8 +30,8 @@ module.exports = merge(base, {
name: 'images/[hash].[ext]', name: 'images/[hash].[ext]',
limit: 10000, limit: 10000,
}, },
} },
] ],
}, },
plugins: [ plugins: [
new webpack.optimize.LimitChunkCountPlugin({ new webpack.optimize.LimitChunkCountPlugin({
@ -49,6 +49,6 @@ module.exports = merge(base, {
allowAsyncCycles: false, allowAsyncCycles: false,
// set the current working directory for displaying module paths // set the current working directory for displaying module paths
cwd: process.cwd(), cwd: process.cwd(),
}) }),
] ],
}); });

View File

@ -8,22 +8,22 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxEvent, InternalEvent,
mxRubberband, Rubberband,
mxConnectionHandler, ConnectionHandler,
mxConnectionConstraint, ConnectionConstraint,
mxGeometry, Geometry,
mxPolyline, Polyline,
mxPoint, Point,
mxCellState CellState,
} = mxgraph; } = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
@ -34,22 +34,17 @@ const Template = ({ label, ...args }) => {
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
container.style.cursor = 'default'; container.style.cursor = 'default';
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
class MyCustomConnectionHandler extends mxConnectionHandler { class MyCustomConnectionHandler extends ConnectionHandler {
// Enables connect preview for the default edge style // Enables connect preview for the default edge style
createEdgeState(me) { createEdgeState(me) {
const edge = graph.createEdge(null, null, null, null, null); const edge = graph.createEdge(null, null, null, null, null);
return new mxCellState( return new CellState(this.graph.view, edge, this.graph.getCellStyle(edge));
this.graph.view,
edge,
this.graph.getCellStyle(edge)
);
} }
} }
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
getAllConnectionConstraints(terminal, source) { getAllConnectionConstraints(terminal, source) {
// Overridden to define per-shape connection points // Overridden to define per-shape connection points
if (terminal != null && terminal.shape != null) { if (terminal != null && terminal.shape != null) {
@ -69,38 +64,36 @@ const Template = ({ label, ...args }) => {
} }
} }
class MyCustomGeometryClass extends mxGeometry { class MyCustomGeometryClass extends Geometry {
// Defines the default constraints for the vertices // Defines the default constraints for the vertices
constraints = [ constraints = [
new mxConnectionConstraint(new mxPoint(0.25, 0), true), new ConnectionConstraint(new Point(0.25, 0), true),
new mxConnectionConstraint(new mxPoint(0.5, 0), true), new ConnectionConstraint(new Point(0.5, 0), true),
new mxConnectionConstraint(new mxPoint(0.75, 0), true), new ConnectionConstraint(new Point(0.75, 0), true),
new mxConnectionConstraint(new mxPoint(0, 0.25), true), new ConnectionConstraint(new Point(0, 0.25), true),
new mxConnectionConstraint(new mxPoint(0, 0.5), true), new ConnectionConstraint(new Point(0, 0.5), true),
new mxConnectionConstraint(new mxPoint(0, 0.75), true), new ConnectionConstraint(new Point(0, 0.75), true),
new mxConnectionConstraint(new mxPoint(1, 0.25), true), new ConnectionConstraint(new Point(1, 0.25), true),
new mxConnectionConstraint(new mxPoint(1, 0.5), true), new ConnectionConstraint(new Point(1, 0.5), true),
new mxConnectionConstraint(new mxPoint(1, 0.75), true), new ConnectionConstraint(new Point(1, 0.75), true),
new mxConnectionConstraint(new mxPoint(0.25, 1), true), new ConnectionConstraint(new Point(0.25, 1), true),
new mxConnectionConstraint(new mxPoint(0.5, 1), true), new ConnectionConstraint(new Point(0.5, 1), true),
new mxConnectionConstraint(new mxPoint(0.75, 1), true), new ConnectionConstraint(new Point(0.75, 1), true),
]; ];
} }
// Edges have no connection points // Edges have no connection points
mxPolyline.prototype.constraints = null; Polyline.prototype.constraints = null;
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new MyCustomGraph(container); const graph = new MyCustomGraph(container);
graph.setConnectable(true); graph.setConnectable(true);
// Specifies the default edge style // Specifies the default edge style
graph.getStylesheet().getDefaultEdgeStyle().edgeStyle = graph.getStylesheet().getDefaultEdgeStyle().edgeStyle = 'orthogonalEdgeStyle';
'orthogonalEdgeStyle';
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -131,6 +124,6 @@ const Template = ({ label, ...args }) => {
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -7,15 +7,12 @@ import './css/animation.css';
export default { export default {
title: 'Effects/Animation', title: 'Effects/Animation',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Point } = maxgraph;
mxGraph,
mxPoint
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -25,7 +22,7 @@ const Template = ({ label, ...args }) => {
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
container.style.cursor = 'default'; container.style.cursor = 'default';
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setEnabled(false); graph.setEnabled(false);
const parent = graph.getDefaultParent(); const parent = graph.getDefaultParent();
@ -67,26 +64,18 @@ const Template = ({ label, ...args }) => {
style: style:
'strokeWidth=3;endArrow=block;endSize=2;endFill=1;strokeColor=black;rounded=1;', 'strokeWidth=3;endArrow=block;endSize=2;endFill=1;strokeColor=black;rounded=1;',
}); });
e1.geometry.points = [new mxPoint(230, 50)]; e1.geometry.points = [new Point(230, 50)];
graph.orderCells(true, [e1]); graph.orderCells(true, [e1]);
}); });
// Adds animation to edge shape and makes "pipe" visible // Adds animation to edge shape and makes "pipe" visible
const state = graph.view.getState(e1); const state = graph.view.getState(e1);
state.shape.node state.shape.node.getElementsByTagName('path')[0].removeAttribute('visibility');
.getElementsByTagName('path')[0] state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke-width', '6');
.removeAttribute('visibility'); state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke', 'lightGray');
state.shape.node state.shape.node.getElementsByTagName('path')[1].setAttribute('class', 'flow');
.getElementsByTagName('path')[0]
.setAttribute('stroke-width', '6');
state.shape.node
.getElementsByTagName('path')[0]
.setAttribute('stroke', 'lightGray');
state.shape.node
.getElementsByTagName('path')[1]
.setAttribute('class', 'flow');
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,32 +8,32 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxRubberband, Rubberband,
mxEvent, InternalEvent,
mxUtils, utils,
mxCellRenderer, CellRenderer,
mxEdgeHandler, EdgeHandler,
mxHierarchicalLayout, mxHierarchicalLayout,
mxConstants, Constants,
mxCellOverlay, CellOverlay,
mxImage, ImageBox,
mxClient, mxClient,
mxMorphing, mxMorphing,
mxEventObject, EventObject,
mxEventUtils EventUtils,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -43,41 +43,36 @@ const Template = ({ label, ...args }) => {
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
container.style.cursor = 'default'; container.style.cursor = 'default';
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
class MyCustomCellRenderer extends mxCellRenderer { class MyCustomCellRenderer extends CellRenderer {
installCellOverlayListeners(state, overlay, shape) { installCellOverlayListeners(state, overlay, shape) {
super.installCellOverlayListeners(state, overlay, shape); super.installCellOverlayListeners(state, overlay, shape);
mxEvent.addListener( InternalEvent.addListener(
shape.node, shape.node,
mxClient.IS_POINTER ? 'pointerdown' : 'mousedown', mxClient.IS_POINTER ? 'pointerdown' : 'mousedown',
evt => { (evt) => {
overlay.fireEvent( overlay.fireEvent(new EventObject('pointerdown', 'event', evt, 'state', state));
new mxEventObject('pointerdown', 'event', evt, 'state', state)
);
} }
); );
if (!mxClient.IS_POINTER && mxClient.IS_TOUCH) { if (!mxClient.IS_POINTER && mxClient.IS_TOUCH) {
mxEvent.addListener(shape.node, 'touchstart', evt => { InternalEvent.addListener(shape.node, 'touchstart', (evt) => {
overlay.fireEvent( overlay.fireEvent(new EventObject('pointerdown', 'event', evt, 'state', state));
new mxEventObject('pointerdown', 'event', evt, 'state', state)
);
}); });
} }
} }
} }
class MyCustomEdgeHandler extends mxEdgeHandler { class MyCustomEdgeHandler extends EdgeHandler {
connect(edge, terminal, isSource, isClone, me) { connect(edge, terminal, isSource, isClone, me) {
super.connect(edge, terminal, isSource, isClone, me); super.connect(edge, terminal, isSource, isClone, me);
executeLayout(); executeLayout();
} }
} }
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
createEdgeHandler(state, edgeStyle) { createEdgeHandler(state, edgeStyle) {
return new MyCustomEdgeHandler(state, edgeStyle); return new MyCustomEdgeHandler(state, edgeStyle);
} }
@ -96,14 +91,13 @@ const Template = ({ label, ...args }) => {
graph.view.setTranslate(20, 20); graph.view.setTranslate(20, 20);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
const parent = graph.getDefaultParent(); const parent = graph.getDefaultParent();
const layout = new mxHierarchicalLayout(graph, mxConstants.DIRECTION_WEST); const layout = new mxHierarchicalLayout(graph, Constants.DIRECTION_WEST);
let v1; let v1;
const executeLayout = (change, post) => { const executeLayout = (change, post) => {
@ -118,7 +112,7 @@ const Template = ({ label, ...args }) => {
} finally { } finally {
// New API for animating graph layout results asynchronously // New API for animating graph layout results asynchronously
const morph = new mxMorphing(graph); const morph = new mxMorphing(graph);
morph.addListener(mxEvent.DONE, () => { morph.addListener(InternalEvent.DONE, () => {
graph.getModel().endUpdate(); graph.getModel().endUpdate();
if (post != null) { if (post != null) {
post(); post();
@ -128,16 +122,16 @@ const Template = ({ label, ...args }) => {
} }
}; };
const addOverlay = cell => { const addOverlay = (cell) => {
// Creates a new overlay with an image and a tooltip // Creates a new overlay with an image and a tooltip
const overlay = new mxCellOverlay( const overlay = new CellOverlay(
new mxImage('images/add.png', 24, 24), new ImageBox('images/add.png', 24, 24),
'Add outgoing' 'Add outgoing'
); );
overlay.cursor = 'hand'; overlay.cursor = 'hand';
// Installs a handler for clicks on the overlay // Installs a handler for clicks on the overlay
overlay.addListener(mxEvent.CLICK, (sender, evt2) => { overlay.addListener(InternalEvent.CLICK, (sender, evt2) => {
graph.clearSelection(); graph.clearSelection();
const geo = graph.getCellGeometry(cell); const geo = graph.getCellGeometry(cell);
@ -173,15 +167,15 @@ const Template = ({ label, ...args }) => {
graph.popupMenuHandler.hideMenu(); graph.popupMenuHandler.hideMenu();
graph.stopEditing(false); graph.stopEditing(false);
const pt = mxUtils.convertPoint( const pt = utils.convertPoint(
graph.container, graph.container,
mxEventUtils.getClientX(evt2), EventUtils.getClientX(evt2),
mxEventUtils.getClientY(evt2) EventUtils.getClientY(evt2)
); );
graph.connectionHandler.start(state, pt.x, pt.y); graph.connectionHandler.start(state, pt.x, pt.y);
graph.isMouseDown = true; graph.isMouseDown = true;
graph.isMouseTrigger = mxEventUtils.isMouseEvent(evt2); graph.isMouseTrigger = EventUtils.isMouseEvent(evt2);
mxEvent.consume(evt2); InternalEvent.consume(evt2);
}); });
// Sets the overlay for the cell in the graph // Sets the overlay for the cell in the graph
@ -199,16 +193,16 @@ const Template = ({ label, ...args }) => {
addOverlay(v1); addOverlay(v1);
}); });
graph.resizeCell = function() { graph.resizeCell = function () {
mxGraph.prototype.resizeCell.apply(this, arguments); Graph.prototype.resizeCell.apply(this, arguments);
executeLayout(); executeLayout();
}; };
graph.connectionHandler.addListener(mxEvent.CONNECT, function() { graph.connectionHandler.addListener(InternalEvent.CONNECT, function () {
executeLayout(); executeLayout();
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,24 +8,17 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, InternalEvent, Rubberband, Point, GraphHandler, utils } = maxgraph;
mxGraph,
mxEvent,
mxRubberband,
mxPoint,
mxGraphHandler,
mxUtils
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -36,10 +29,9 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Disables the built-in context menu // Disables the built-in context menu
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
// Enables moving of relative children // Enables moving of relative children
isCellLocked(cell) { isCellLocked(cell) {
return false; return false;
@ -94,7 +86,7 @@ const Template = ({ label, ...args }) => {
y = y > 0.5 ? 1 : 0; y = y > 0.5 ? 1 : 0;
} }
return new mxPoint(x, y); return new Point(x, y);
} }
} }
} }
@ -122,7 +114,7 @@ const Template = ({ label, ...args }) => {
this.model.setGeometry(cell, geo); this.model.setGeometry(cell, geo);
} }
} else { } else {
mxGraph.prototype.translateCell.apply(this, arguments); Graph.prototype.translateCell.apply(this, arguments);
} }
} }
} }
@ -142,29 +134,19 @@ const Template = ({ label, ...args }) => {
graph.getStylesheet().putDefaultVertexStyle(style); graph.getStylesheet().putDefaultVertexStyle(style);
// Replaces move preview for relative children // Replaces move preview for relative children
graph.graphHandler.getDelta = function(me) { graph.graphHandler.getDelta = function (me) {
const point = mxUtils.convertPoint( const point = utils.convertPoint(this.graph.container, me.getX(), me.getY());
this.graph.container, let delta = new Point(point.x - this.first.x, point.y - this.first.y);
me.getX(),
me.getY()
);
let delta = new mxPoint(point.x - this.first.x, point.y - this.first.y);
if ( if (this.cells != null && this.cells.length > 0 && this.cells[0] != null) {
this.cells != null &&
this.cells.length > 0 &&
this.cells[0] != null
) {
const state = this.graph.view.getState(this.cells[0]); const state = this.graph.view.getState(this.cells[0]);
const rel = graph.getRelativePosition(state, delta.x, delta.y); const rel = graph.getRelativePosition(state, delta.x, delta.y);
if (rel != null) { if (rel != null) {
const pstate = this.graph.view.getState( const pstate = this.graph.view.getState(state.cell.getParent());
state.cell.getParent()
);
if (pstate != null) { if (pstate != null) {
delta = new mxPoint( delta = new Point(
pstate.x + pstate.width * rel.x - state.getCenterX(), pstate.x + pstate.width * rel.x - state.getCenterX(),
pstate.y + pstate.height * rel.y - state.getCenterY() pstate.y + pstate.height * rel.y - state.getCenterY()
); );
@ -176,24 +158,16 @@ const Template = ({ label, ...args }) => {
}; };
// Relative children cannot be removed from parent // Relative children cannot be removed from parent
graph.graphHandler.shouldRemoveCellsFromParent = function( graph.graphHandler.shouldRemoveCellsFromParent = function (parent, cells, evt) {
parent,
cells,
evt
) {
return ( return (
cells.length === 0 && cells.length === 0 &&
!cells[0].geometry.relative && !cells[0].geometry.relative &&
mxGraphHandler.prototype.shouldRemoveCellsFromParent.apply( GraphHandler.prototype.shouldRemoveCellsFromParent.apply(this, arguments)
this,
arguments
)
); );
}; };
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -215,7 +189,7 @@ const Template = ({ label, ...args }) => {
size: [20, 20], size: [20, 20],
style: 'fontSize=9;shape=ellipse;resizable=0;', style: 'fontSize=9;shape=ellipse;resizable=0;',
}); });
v2.geometry.offset = new mxPoint(-10, -10); v2.geometry.offset = new Point(-10, -10);
v2.geometry.relative = true; v2.geometry.relative = true;
const v3 = graph.insertVertex({ const v3 = graph.insertVertex({
@ -225,11 +199,11 @@ const Template = ({ label, ...args }) => {
size: [20, 20], size: [20, 20],
style: 'fontSize=9;shape=ellipse;resizable=0;', style: 'fontSize=9;shape=ellipse;resizable=0;',
}); });
v3.geometry.offset = new mxPoint(-10, -10); v3.geometry.offset = new Point(-10, -10);
v3.geometry.relative = true; v3.geometry.relative = true;
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,28 +8,28 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxEvent, InternalEvent,
mxRubberband, Rubberband,
mxClipboard, mxClipboard,
mxUtils, utils,
mxEventUtils, EventUtils,
mxClient, mxClient,
mxCodec, mxCodec,
mxGraphModel, GraphModel,
mxStringUtils mxStringUtils,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -40,28 +40,27 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Disables the built-in context menu // Disables the built-in context menu
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
// Creates the graph inside the given this.el // Creates the graph inside the given this.el
const graph = new mxGraph(container); const graph = new Graph(container);
// Public helper method for shared clipboard. // Public helper method for shared clipboard.
mxClipboard.cellsToString = function(cells) { mxClipboard.cellsToString = function (cells) {
const codec = new mxCodec(); const codec = new mxCodec();
const model = new mxGraphModel(); const model = new GraphModel();
const parent = model.getRoot().getChildAt(0); const parent = model.getRoot().getChildAt(0);
for (let i = 0; i < cells.length; i++) { for (let i = 0; i < cells.length; i++) {
model.add(parent, cells[i]); model.add(parent, cells[i]);
} }
return mxUtils.getXml(codec.encode(model)); return utils.getXml(codec.encode(model));
}; };
// Focused but invisible textarea during control or meta key events // Focused but invisible textarea during control or meta key events
const textInput = document.createElement('textarea'); const textInput = document.createElement('textarea');
mxUtils.setOpacity(textInput, 0); utils.setOpacity(textInput, 0);
textInput.style.width = '1px'; textInput.style.width = '1px';
textInput.style.height = '1px'; textInput.style.height = '1px';
let restoreFocus = false; let restoreFocus = false;
@ -74,9 +73,9 @@ const Template = ({ label, ...args }) => {
textInput.value = ' '; textInput.value = ' ';
// Shows a textare when control/cmd is pressed to handle native clipboard actions // Shows a textare when control/cmd is pressed to handle native clipboard actions
mxEvent.addListener(document, 'keydown', function(evt) { InternalEvent.addListener(document, 'keydown', function (evt) {
// No dialog visible // No dialog visible
const source = mxEventUtils.getSource(evt); const source = EventUtils.getSource(evt);
if ( if (
graph.isEnabled() && graph.isEnabled() &&
@ -107,11 +106,11 @@ const Template = ({ label, ...args }) => {
}); });
// Restores focus on graph this.el and removes text input from DOM // Restores focus on graph this.el and removes text input from DOM
mxEvent.addListener(document, 'keyup', function(evt) { InternalEvent.addListener(document, 'keyup', function (evt) {
if ( if (
restoreFocus && restoreFocus &&
(evt.keyCode === 224 /* FF */ || (evt.keyCode === 224 /* FF */ ||
evt.keyCode === 17 /* Control */ || evt.keyCode === 17 /* Control */ ||
evt.keyCode === 91 || evt.keyCode === 91 ||
evt.keyCode === 93) /* Meta */ evt.keyCode === 93) /* Meta */
) { ) {
@ -126,7 +125,7 @@ const Template = ({ label, ...args }) => {
}); });
// Inserts the XML for the given cells into the text input for copy // Inserts the XML for the given cells into the text input for copy
const copyCells = function(graph, cells) { const copyCells = function (graph, cells) {
if (cells.length > 0) { if (cells.length > 0) {
const clones = graph.cloneCells(cells); const clones = graph.cloneCells(cells);
@ -153,48 +152,38 @@ const Template = ({ label, ...args }) => {
}; };
// Handles copy event by putting XML for current selection into text input // Handles copy event by putting XML for current selection into text input
mxEvent.addListener( InternalEvent.addListener(textInput, 'copy', (evt) => {
textInput, if (graph.isEnabled() && !graph.isSelectionEmpty()) {
'copy', copyCells(
(evt) => { graph,
if (graph.isEnabled() && !graph.isSelectionEmpty()) { utils.sortCells(graph.model.getTopmostCells(graph.getSelectionCells()))
copyCells( );
graph, dx = 0;
mxUtils.sortCells( dy = 0;
graph.model.getTopmostCells(graph.getSelectionCells())
)
);
dx = 0;
dy = 0;
}
} }
); });
// Handles cut event by removing cells putting XML into text input // Handles cut event by removing cells putting XML into text input
mxEvent.addListener( InternalEvent.addListener(textInput, 'cut', (evt) => {
textInput, if (graph.isEnabled() && !graph.isSelectionEmpty()) {
'cut', copyCells(graph, graph.removeCells());
(evt) => { dx = -gs;
if (graph.isEnabled() && !graph.isSelectionEmpty()) { dy = -gs;
copyCells(graph, graph.removeCells());
dx = -gs;
dy = -gs;
}
} }
); });
// Merges XML into existing graph and layers // Merges XML into existing graph and layers
const importXml = function(xml, dx, dy) { const importXml = function (xml, dx, dy) {
dx = dx != null ? dx : 0; dx = dx != null ? dx : 0;
dy = dy != null ? dy : 0; dy = dy != null ? dy : 0;
let cells = []; let cells = [];
try { try {
const doc = mxUtils.parseXml(xml); const doc = utils.parseXml(xml);
const node = doc.documentElement; const node = doc.documentElement;
if (node != null) { if (node != null) {
const model = new mxGraphModel(); const model = new GraphModel();
const codec = new mxCodec(node.ownerDocument); const codec = new mxCodec(node.ownerDocument);
codec.decode(node, model); codec.decode(node, model);
@ -217,18 +206,11 @@ const Template = ({ label, ...args }) => {
if (!graph.isCellLocked(target)) { if (!graph.isCellLocked(target)) {
const children = parent.getChildren(); const children = parent.getChildren();
cells = cells.concat( cells = cells.concat(graph.importCells(children, dx, dy, target));
graph.importCells(children, dx, dy, target)
);
} }
} else { } else {
// Delta is non cascading, needs separate move for layers // Delta is non cascading, needs separate move for layers
parent = graph.importCells( parent = graph.importCells([parent], 0, 0, graph.model.getRoot())[0];
[parent],
0,
0,
graph.model.getRoot()
)[0];
const children = parent.getChildren(); const children = parent.getChildren();
graph.moveCells(children, dx, dy); graph.moveCells(children, dx, dy);
cells = cells.concat(children); cells = cells.concat(children);
@ -247,12 +229,10 @@ const Template = ({ label, ...args }) => {
}; };
// Parses and inserts XML into graph // Parses and inserts XML into graph
const pasteText = function(text) { const pasteText = function (text) {
const xml = mxStringUtils.trim(text); const xml = mxStringUtils.trim(text);
const x = const x = graph.container.scrollLeft / graph.view.scale - graph.view.translate.x;
graph.container.scrollLeft / graph.view.scale - graph.view.translate.x; const y = graph.container.scrollTop / graph.view.scale - graph.view.translate.y;
const y =
graph.container.scrollTop / graph.view.scale - graph.view.translate.y;
if (xml.length > 0) { if (xml.length > 0) {
if (lastPaste !== xml) { if (lastPaste !== xml) {
@ -273,23 +253,17 @@ const Template = ({ label, ...args }) => {
}; };
// Function to fetch text from paste events // Function to fetch text from paste events
const extractGraphModelFromEvent = function(evt) { const extractGraphModelFromEvent = function (evt) {
let data = null; let data = null;
if (evt != null) { if (evt != null) {
const provider = const provider = evt.dataTransfer != null ? evt.dataTransfer : evt.clipboardData;
evt.dataTransfer != null ? evt.dataTransfer : evt.clipboardData;
if (provider != null) { if (provider != null) {
data = data =
provider.types.indexOf('text/html') >= 0 provider.types.indexOf('text/html') >= 0 ? provider.getData('text/html') : null;
? provider.getData('text/html')
: null;
if ( if (provider.types.indexOf('text/plain') && (data == null || data.length === 0)) {
provider.types.indexOf('text/plain')
&& (data == null || data.length === 0)
) {
data = provider.getData('text/plain'); data = provider.getData('text/plain');
} }
} }
@ -299,7 +273,7 @@ const Template = ({ label, ...args }) => {
}; };
// Handles paste event by parsing and inserting XML // Handles paste event by parsing and inserting XML
mxEvent.addListener(textInput, 'paste', function(evt) { InternalEvent.addListener(textInput, 'paste', function (evt) {
// Clears existing contents before paste - should not be needed // Clears existing contents before paste - should not be needed
// because all text is selected, but doesn't hurt since the // because all text is selected, but doesn't hurt since the
// actual pasting of the new text is delayed in all cases. // actual pasting of the new text is delayed in all cases.
@ -312,12 +286,9 @@ const Template = ({ label, ...args }) => {
pasteText(xml); pasteText(xml);
} else { } else {
// Timeout for new value to appear // Timeout for new value to appear
window.setTimeout( window.setTimeout(() => {
() => { pasteText(textInput.value);
pasteText(textInput.value); }, 0);
},
0
);
} }
} }
@ -325,8 +296,7 @@ const Template = ({ label, ...args }) => {
}); });
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -350,6 +320,6 @@ const Template = ({ label, ...args }) => {
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,19 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Layouts/Collapse', title: 'Layouts/Collapse',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Rectangle } = maxgraph;
mxGraph,
mxRectangle
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -23,10 +20,10 @@ const Template = ({ label, ...args }) => {
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
container.style.cursor = 'default'; container.style.cursor = 'default';
const graph = new mxGraph(container); const graph = new Graph(container);
const parent = graph.getDefaultParent(); const parent = graph.getDefaultParent();
const getStyle = function() { const getStyle = function () {
// Extends Transactions.getStyle to show an image when collapsed // Extends Transactions.getStyle to show an image when collapsed
// TODO cannot use super without a parent class // TODO cannot use super without a parent class
// let style = super.getStyle(); // let style = super.getStyle();
@ -37,7 +34,7 @@ const Template = ({ label, ...args }) => {
`noLabel=1;imageBackground=#C3D9FF;imageBorder=#6482B9`; `noLabel=1;imageBackground=#C3D9FF;imageBorder=#6482B9`;
} }
return style; return style;
} };
graph.batchUpdate(() => { graph.batchUpdate(() => {
const v1 = graph.insertVertex({ const v1 = graph.insertVertex({
@ -47,7 +44,7 @@ const Template = ({ label, ...args }) => {
size: [200, 200], size: [200, 200],
style: 'shape=swimlane;startSize=20;', style: 'shape=swimlane;startSize=20;',
}); });
v1.geometry.alternateBounds = new mxRectangle(0, 0, 110, 70); v1.geometry.alternateBounds = new Rectangle(0, 0, 110, 70);
v1.getStyle = getStyle; v1.getStyle = getStyle;
const v11 = graph.insertVertex({ const v11 = graph.insertVertex({
@ -60,6 +57,6 @@ const Template = ({ label, ...args }) => {
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,22 +8,17 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, InternalEvent, GraphHandler, Rubberband } = maxgraph;
mxGraph,
mxEvent,
mxGraphHandler,
mxRubberband
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -34,9 +29,9 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Disables the built-in context menu // Disables the built-in context menu
mxEvent.disableContextMenu(container); InternalEvent.disableContextMenu(container);
class MyCustomGraphHandler extends mxGraphHandler { class MyCustomGraphHandler extends GraphHandler {
/** /**
* Redirects start drag to parent. * Redirects start drag to parent.
*/ */
@ -49,7 +44,7 @@ const Template = ({ label, ...args }) => {
} }
} }
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
foldingEnabled = false; foldingEnabled = false;
recursiveResize = true; recursiveResize = true;
@ -76,7 +71,7 @@ const Template = ({ label, ...args }) => {
const graph = new MyCustomGraph(container); const graph = new MyCustomGraph(container);
// Enables rubberband selection // Enables rubberband selection
new mxRubberband(graph); new Rubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -99,6 +94,6 @@ const Template = ({ label, ...args }) => {
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,20 +8,13 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, InternalEvent, Rubberband, EventUtils, utils, VertexHandler } = maxgraph;
mxGraph,
mxEvent,
mxRubberband,
mxEventUtils,
mxUtils,
mxVertexHandler
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -31,8 +24,8 @@ const Template = ({ label, ...args }) => {
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
container.style.cursor = 'default'; container.style.cursor = 'default';
class mxVertexToolHandler extends mxVertexHandler { class mxVertexToolHandler extends VertexHandler {
// Defines a subclass for mxVertexHandler that adds a set of clickable // Defines a subclass for VertexHandler that adds a set of clickable
// icons to every selected vertex. // icons to every selected vertex.
domNode = null; domNode = null;
@ -49,8 +42,8 @@ const Template = ({ label, ...args }) => {
this.domNode.style.whiteSpace = 'nowrap'; this.domNode.style.whiteSpace = 'nowrap';
// Workaround for event redirection via image tag in quirks and IE8 // Workaround for event redirection via image tag in quirks and IE8
const createImage = src => { const createImage = (src) => {
return mxUtils.createImage(src); return utils.createImage(src);
}; };
// Delete // Delete
@ -59,13 +52,13 @@ const Template = ({ label, ...args }) => {
img.style.cursor = 'pointer'; img.style.cursor = 'pointer';
img.style.width = '16px'; img.style.width = '16px';
img.style.height = '16px'; img.style.height = '16px';
mxEvent.addGestureListeners(img, evt => { InternalEvent.addGestureListeners(img, (evt) => {
// Disables dragging the image // Disables dragging the image
mxEvent.consume(evt); InternalEvent.consume(evt);
}); });
mxEvent.addListener(img, 'click', evt => { InternalEvent.addListener(img, 'click', (evt) => {
this.graph.removeCells([this.state.cell]); this.graph.removeCells([this.state.cell]);
mxEvent.consume(evt); InternalEvent.consume(evt);
}); });
this.domNode.appendChild(img); this.domNode.appendChild(img);
@ -76,11 +69,11 @@ const Template = ({ label, ...args }) => {
img.style.width = '16px'; img.style.width = '16px';
img.style.height = '16px'; img.style.height = '16px';
mxEvent.addGestureListeners(img, evt => { InternalEvent.addGestureListeners(img, (evt) => {
this.start(mxEventUtils.getClientX(evt), mxEventUtils.getClientY(evt), 7); this.start(EventUtils.getClientX(evt), EventUtils.getClientY(evt), 7);
this.graph.isMouseDown = true; this.graph.isMouseDown = true;
this.graph.isMouseTrigger = mxEventUtils.isMouseEvent(evt); this.graph.isMouseTrigger = EventUtils.isMouseEvent(evt);
mxEvent.consume(evt); InternalEvent.consume(evt);
}); });
this.domNode.appendChild(img); this.domNode.appendChild(img);
@ -91,16 +84,16 @@ const Template = ({ label, ...args }) => {
img.style.width = '16px'; img.style.width = '16px';
img.style.height = '16px'; img.style.height = '16px';
mxEvent.addGestureListeners(img, evt => { InternalEvent.addGestureListeners(img, (evt) => {
this.graph.graphHandler.start( this.graph.graphHandler.start(
this.state.cell, this.state.cell,
mxEventUtils.getClientX(evt), EventUtils.getClientX(evt),
mxEventUtils.getClientY(evt) EventUtils.getClientY(evt)
); );
this.graph.graphHandler.cellWasClicked = true; this.graph.graphHandler.cellWasClicked = true;
this.graph.isMouseDown = true; this.graph.isMouseDown = true;
this.graph.isMouseTrigger = mxEventUtils.isMouseEvent(evt); this.graph.isMouseTrigger = EventUtils.isMouseEvent(evt);
mxEvent.consume(evt); InternalEvent.consume(evt);
}); });
this.domNode.appendChild(img); this.domNode.appendChild(img);
@ -111,16 +104,16 @@ const Template = ({ label, ...args }) => {
img.style.width = '16px'; img.style.width = '16px';
img.style.height = '16px'; img.style.height = '16px';
mxEvent.addGestureListeners(img, evt => { InternalEvent.addGestureListeners(img, (evt) => {
const pt = mxUtils.convertPoint( const pt = utils.convertPoint(
this.graph.container, this.graph.container,
mxEventUtils.getClientX(evt), EventUtils.getClientX(evt),
mxEventUtils.getClientY(evt) EventUtils.getClientY(evt)
); );
this.graph.connectionHandler.start(this.state, pt.x, pt.y); this.graph.connectionHandler.start(this.state, pt.x, pt.y);
this.graph.isMouseDown = true; this.graph.isMouseDown = true;
this.graph.isMouseTrigger = mxEventUtils.isMouseEvent(evt); this.graph.isMouseTrigger = EventUtils.isMouseEvent(evt);
mxEvent.consume(evt); InternalEvent.consume(evt);
}); });
this.domNode.appendChild(img); this.domNode.appendChild(img);
@ -151,7 +144,7 @@ const Template = ({ label, ...args }) => {
} }
} }
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
createHandler(state) { createHandler(state) {
if (state != null && state.cell.isVertex()) { if (state != null && state.cell.isVertex()) {
return new mxVertexToolHandler(state); return new mxVertexToolHandler(state);
@ -170,8 +163,7 @@ const Template = ({ label, ...args }) => {
// graph.setResizeContainer(true); // graph.setResizeContainer(true);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -199,6 +191,6 @@ const Template = ({ label, ...args }) => {
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,22 +8,22 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxEvent, InternalEvent,
mxRubberband, Rubberband,
mxDomHelpers, mxDomHelpers,
mxImageShape, ImageShape,
mxRectangle, Rectangle,
mxCellRenderer, CellRenderer,
mxImage ImageBox,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -37,13 +37,9 @@ const Template = ({ label, ...args }) => {
div.appendChild(container); div.appendChild(container);
// Specifies the URL and size of the new control // Specifies the URL and size of the new control
const deleteImage = new mxImage( const deleteImage = new ImageBox('/images/forbidden.png', 16, 16);
'/images/forbidden.png',
16,
16
);
class MyCustomCellRenderer extends mxCellRenderer { class MyCustomCellRenderer extends CellRenderer {
createControl(state) { createControl(state) {
super.createControl(state); super.createControl(state);
@ -51,20 +47,15 @@ const Template = ({ label, ...args }) => {
if (state.cell.isVertex()) { if (state.cell.isVertex()) {
if (state.deleteControl == null) { if (state.deleteControl == null) {
const b = new mxRectangle( const b = new Rectangle(0, 0, deleteImage.width, deleteImage.height);
0, state.deleteControl = new ImageShape(b, deleteImage.src);
0,
deleteImage.width,
deleteImage.height
);
state.deleteControl = new mxImageShape(b, deleteImage.src);
state.deleteControl.dialect = graph.dialect; state.deleteControl.dialect = graph.dialect;
state.deleteControl.preserveImageAspect = false; state.deleteControl.preserveImageAspect = false;
this.initControl(state, state.deleteControl, false, function(evt) { this.initControl(state, state.deleteControl, false, function (evt) {
if (graph.isEnabled()) { if (graph.isEnabled()) {
graph.removeCells([state.cell]); graph.removeCells([state.cell]);
mxEvent.consume(evt); InternalEvent.consume(evt);
} }
}); });
} }
@ -83,18 +74,13 @@ const Template = ({ label, ...args }) => {
const s = state.view.scale; const s = state.view.scale;
return state.cell.isEdge() return state.cell.isEdge()
? new mxRectangle( ? new Rectangle(
state.x + state.width / 2 - (w / 2) * s, state.x + state.width / 2 - (w / 2) * s,
state.y + state.height / 2 - (h / 2) * s, state.y + state.height / 2 - (h / 2) * s,
w * s, w * s,
h * s h * s
) )
: new mxRectangle( : new Rectangle(state.x + state.width - w * s, state.y, w * s, h * s);
state.x + state.width - w * s,
state.y,
w * s,
h * s
);
} }
return null; return null;
} }
@ -129,7 +115,7 @@ const Template = ({ label, ...args }) => {
} }
} }
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
createCellRenderer() { createCellRenderer() {
return new MyCustomCellRenderer(); return new MyCustomCellRenderer();
} }
@ -144,8 +130,7 @@ const Template = ({ label, ...args }) => {
// graph.setResizeContainer(true); // graph.setResizeContainer(true);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -194,6 +179,6 @@ const Template = ({ label, ...args }) => {
); );
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,26 +8,26 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxDomUtils, mxDomUtils,
mxRubberband, Rubberband,
mxDragSource, DragSource,
mxUtils, utils,
mxGestureUtils, GestureUtils,
mxEdgeHandler, EdgeHandler,
mxGraphHandler, GraphHandler,
mxGuide, Guide,
mxEventUtils, EventUtils,
mxCell, Cell,
mxGeometry Geometry,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -36,14 +36,14 @@ const Template = ({ label, ...args }) => {
container.style.height = `${args.height}px`; container.style.height = `${args.height}px`;
container.style.cursor = 'default'; container.style.cursor = 'default';
class MyCustomGuide extends mxGuide { class MyCustomGuide extends Guide {
isEnabledForEvent(evt) { isEnabledForEvent(evt) {
// Alt disables guides // Alt disables guides
return !mxEventUtils.isAltDown(evt); return !EventUtils.isAltDown(evt);
} }
} }
class MyCustomGraphHandler extends mxGraphHandler { class MyCustomGraphHandler extends GraphHandler {
// Enables guides // Enables guides
guidesEnabled = true; guidesEnabled = true;
@ -52,12 +52,12 @@ const Template = ({ label, ...args }) => {
} }
} }
class MyCustomEdgeHandler extends mxEdgeHandler { class MyCustomEdgeHandler extends EdgeHandler {
// Enables snapping waypoints to terminals // Enables snapping waypoints to terminals
snapToTerminals = true; snapToTerminals = true;
} }
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
createGraphHandler() { createGraphHandler() {
return new MyCustomGraphHandler(this); return new MyCustomGraphHandler(this);
} }
@ -89,8 +89,7 @@ const Template = ({ label, ...args }) => {
// graph.setResizeContainer(true); // graph.setResizeContainer(true);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -121,9 +120,9 @@ const Template = ({ label, ...args }) => {
} }
// Returns the graph under the mouse // Returns the graph under the mouse
const graphF = evt => { const graphF = (evt) => {
const x = mxEventUtils.getClientX(evt); const x = EventUtils.getClientX(evt);
const y = mxEventUtils.getClientY(evt); const y = EventUtils.getClientY(evt);
const elt = document.elementFromPoint(x, y); const elt = document.elementFromPoint(x, y);
for (const graph of graphs) { for (const graph of graphs) {
@ -137,7 +136,7 @@ const Template = ({ label, ...args }) => {
// Inserts a cell at the given location // Inserts a cell at the given location
const funct = (graph, evt, target, x, y) => { const funct = (graph, evt, target, x, y) => {
const cell = new mxCell('Test', new mxGeometry(0, 0, 120, 40)); const cell = new Cell('Test', new Geometry(0, 0, 120, 40));
cell.vertex = true; cell.vertex = true;
const cells = graph.importCells([cell], x, y, target); const cells = graph.importCells([cell], x, y, target);
@ -148,7 +147,7 @@ const Template = ({ label, ...args }) => {
}; };
// Creates a DOM node that acts as the drag source // Creates a DOM node that acts as the drag source
const img = mxUtils.createImage('images/icons48/gear.png'); const img = utils.createImage('images/icons48/gear.png');
img.style.width = '48px'; img.style.width = '48px';
img.style.height = '48px'; img.style.height = '48px';
container.appendChild(img); container.appendChild(img);
@ -163,7 +162,7 @@ const Template = ({ label, ...args }) => {
// if scalePreview (last) argument is true. Dx and dy are null to force // if scalePreview (last) argument is true. Dx and dy are null to force
// the use of the defaults. Note that dx and dy are only used for the // the use of the defaults. Note that dx and dy are only used for the
// drag icon but not for the preview. // drag icon but not for the preview.
const ds = mxGestureUtils.makeDraggable( const ds = GestureUtils.makeDraggable(
img, img,
graphF, graphF,
funct, funct,
@ -181,9 +180,9 @@ const Template = ({ label, ...args }) => {
}; };
// Restores original drag icon while outside of graph // Restores original drag icon while outside of graph
ds.createDragElement = mxDragSource.prototype.createDragElement; ds.createDragElement = DragSource.prototype.createDragElement;
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,7 +1,7 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
import { getXml, parseXml } from '@mxgraph/core/src/util/XmlUtils'; import { getXml, parseXml } from '@maxgraph/core/util/XmlUtils';
export default { export default {
title: 'DnD_CopyPaste/Drop', title: 'DnD_CopyPaste/Drop',
@ -9,24 +9,17 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Rubberband, utils, EventUtils, InternalEvent, mxClient } = maxgraph;
mxGraph,
mxRubberband,
mxUtils,
mxEventUtils,
mxEvent,
mxClient
} = mxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
div.innerHTML = 'Drag & drop your images below:<br>'; div.innerHTML = 'Drag & drop your images below:<br>';
@ -42,42 +35,38 @@ const Template = ({ label, ...args }) => {
// Checks if the browser is supported // Checks if the browser is supported
const fileSupport = const fileSupport =
window.File != null && window.File != null && window.FileReader != null && window.FileList != null;
window.FileReader != null &&
window.FileList != null;
if (!fileSupport || !mxClient.isBrowserSupported()) { if (!fileSupport || !mxClient.isBrowserSupported()) {
// Displays an error message if the browser is not supported. // Displays an error message if the browser is not supported.
mxUtils.error('Browser is not supported!', 200, false); utils.error('Browser is not supported!', 200, false);
} else { } else {
// Disables the built-in context menu // Disables the built-in context menu
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
// Creates the graph inside the given this.el // Creates the graph inside the given this.el
const graph = new mxGraph(container); const graph = new Graph(container);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
mxEvent.addListener(container, 'dragover', function(evt) { InternalEvent.addListener(container, 'dragover', function (evt) {
if (graph.isEnabled()) { if (graph.isEnabled()) {
evt.stopPropagation(); evt.stopPropagation();
evt.preventDefault(); evt.preventDefault();
} }
}); });
mxEvent.addListener(container, 'drop', evt => { InternalEvent.addListener(container, 'drop', (evt) => {
if (graph.isEnabled()) { if (graph.isEnabled()) {
evt.stopPropagation(); evt.stopPropagation();
evt.preventDefault(); evt.preventDefault();
// Gets drop location point for vertex // Gets drop location point for vertex
const pt = mxUtils.convertPoint( const pt = utils.convertPoint(
graph.container, graph.container,
mxEventUtils.getClientX(evt), EventUtils.getClientX(evt),
mxEventUtils.getClientY(evt) EventUtils.getClientY(evt)
); );
const tr = graph.view.translate; const tr = graph.view.translate;
const { scale } = graph.view; const { scale } = graph.view;
@ -95,7 +84,7 @@ const Template = ({ label, ...args }) => {
} }
return div; return div;
} };
function handleDrop(graph, file, x, y) { function handleDrop(graph, file, x, y) {
// Handles each file as a separate insert for simplicity. // Handles each file as a separate insert for simplicity.
@ -104,7 +93,7 @@ function handleDrop(graph, file, x, y) {
if (file.type.substring(0, 5) === 'image') { if (file.type.substring(0, 5) === 'image') {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = function(e) { reader.onload = function (e) {
// Gets size of image for vertex // Gets size of image for vertex
let data = e.target.result; let data = e.target.result;
@ -144,9 +133,7 @@ function handleDrop(graph, file, x, y) {
w = Math.max(1, Math.round(w)); w = Math.max(1, Math.round(w));
h = Math.max(1, Math.round(h)); h = Math.max(1, Math.round(h));
data = `data:image/svg+xml,${btoa( data = `data:image/svg+xml,${btoa(getXml(svgs[0], '\n'))}`;
getXml(svgs[0], '\n')
)}`;
graph.insertVertex({ graph.insertVertex({
position: [x, y], position: [x, y],
size: [w, h], size: [w, h],
@ -165,9 +152,7 @@ function handleDrop(graph, file, x, y) {
const semi = data.indexOf(';'); const semi = data.indexOf(';');
if (semi > 0) { if (semi > 0) {
data = data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
data.substring(0, semi) +
data.substring(data.indexOf(',', semi + 1));
} }
graph.insertVertex({ graph.insertVertex({
@ -185,4 +170,4 @@ function handleDrop(graph, file, x, y) {
} }
} }
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,26 +1,26 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Misc/DynamicLoading', title: 'Misc/DynamicLoading',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxText, Text,
mxEffects, mxEffects,
mxEvent, InternalEvent,
mxConstants, Constants,
mxPerimeter, Perimeter,
mxCodec, mxCodec,
mxUtils, utils,
mxXmlUtils mxXmlUtils,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -33,16 +33,16 @@ const Template = ({ label, ...args }) => {
let requestId = 0; let requestId = 0;
// Speedup the animation // Speedup the animation
mxText.prototype.enableBoundingBox = false; Text.prototype.enableBoundingBox = false;
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Disables all built-in interactions // Disables all built-in interactions
graph.setEnabled(false); graph.setEnabled(false);
// Handles clicks on cells // Handles clicks on cells
graph.addListener(mxEvent.CLICK, function(sender, evt) { graph.addListener(InternalEvent.CLICK, function (sender, evt) {
const cell = evt.getProperty('cell'); const cell = evt.getProperty('cell');
if (cell != null) { if (cell != null) {
@ -52,8 +52,8 @@ const Template = ({ label, ...args }) => {
// Changes the default vertex style in-place // Changes the default vertex style in-place
const style = graph.getStylesheet().getDefaultVertexStyle(); const style = graph.getStylesheet().getDefaultVertexStyle();
style.shape = mxConstants.SHAPE_ELLIPSE; style.shape = Constants.SHAPE_ELLIPSE;
style.perimiter = mxPerimeter.EllipsePerimeter; style.perimiter = Perimeter.EllipsePerimeter;
style.gradientColor = 'white'; style.gradientColor = 'white';
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
@ -63,18 +63,10 @@ const Template = ({ label, ...args }) => {
const cx = graph.container.clientWidth / 2; const cx = graph.container.clientWidth / 2;
const cy = graph.container.clientHeight / 2; const cy = graph.container.clientHeight / 2;
const cell = graph.insertVertex( const cell = graph.insertVertex(parent, '0-0', '0-0', cx - 20, cy - 15, 60, 40);
parent,
'0-0',
'0-0',
cx - 20,
cy - 15,
60,
40
);
// Animates the changes in the graph model // Animates the changes in the graph model
graph.getModel().addListener(mxEvent.CHANGE, function(sender, evt) { graph.getModel().addListener(InternalEvent.CHANGE, function (sender, evt) {
const { changes } = evt.getProperty('edit'); const { changes } = evt.getProperty('edit');
mxEffects.animateChanges(graph, changes); mxEffects.animateChanges(graph, changes);
}); });
@ -180,7 +172,7 @@ const Template = ({ label, ...args }) => {
requestId++; requestId++;
// Creates a local graph with no display // Creates a local graph with no display
const graph = new mxGraph(); const graph = new Graph();
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -206,12 +198,12 @@ const Template = ({ label, ...args }) => {
const enc = new mxCodec(); const enc = new mxCodec();
const node = enc.encode(graph.getModel()); const node = enc.encode(graph.getModel());
return mxUtils.getXml(node); return utils.getXml(node);
} }
load(graph, cell); load(graph, cell);
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,18 +8,13 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, utils, Constants, Rubberband } = maxgraph;
mxGraph,
mxUtils,
mxConstants,
mxRubberband
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -30,25 +25,24 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Disables moving of edge labels in this examples // Disables moving of edge labels in this examples
graph.edgeLabelsMovable = false; graph.edgeLabelsMovable = false;
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Needs to set a flag to check for dynamic style changes, // Needs to set a flag to check for dynamic style changes,
// that is, changes to styles on cells where the style was // that is, changes to styles on cells where the style was
// not explicitely changed using mxStyleChange // not explicitely changed using mxStyleChange
graph.getView().updateStyle = true; graph.getView().updateStyle = true;
// Overrides mxCell.getStyle to return a specific style // Overrides Cell.getStyle to return a specific style
// for edges that reflects their target terminal (in this case // for edges that reflects their target terminal (in this case
// the strokeColor will be equal to the target's fillColor). // the strokeColor will be equal to the target's fillColor).
const getStyle = function() { const getStyle = function () {
// TODO super cannot be used here // TODO super cannot be used here
// let style = super.getStyle(); // let style = super.getStyle();
let style; let style;
@ -58,10 +52,7 @@ const Template = ({ label, ...args }) => {
if (target != null) { if (target != null) {
const targetStyle = graph.getCurrentCellStyle(target); const targetStyle = graph.getCurrentCellStyle(target);
const fill = mxUtils.getValue( const fill = utils.getValue(targetStyle, 'fillColor');
targetStyle,
'fillColor'
);
if (fill != null) { if (fill != null) {
style += `;strokeColor=${fill}`; style += `;strokeColor=${fill}`;
@ -120,6 +111,6 @@ const Template = ({ label, ...args }) => {
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,26 +8,26 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxRubberband, Rubberband,
mxConnectionHandler, ConnectionHandler,
mxImage, ImageBox,
mxToolbar, mxToolbar,
mxGraphModel, GraphModel,
mxKeyHandler, mxKeyHandler,
mxCell, Cell,
mxGeometry, Geometry,
mxEvent, InternalEvent,
mxUtils, utils,
mxGestureUtils GestureUtils,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -42,7 +42,7 @@ const Template = ({ label, ...args }) => {
// Defines an icon for creating new connections in the connection handler. // Defines an icon for creating new connections in the connection handler.
// This will automatically disable the highlighting of the source vertex. // This will automatically disable the highlighting of the source vertex.
mxConnectionHandler.prototype.connectImage = new mxImage( ConnectionHandler.prototype.connectImage = new ImageBox(
'/images/connector.gif', '/images/connector.gif',
16, 16,
16 16
@ -66,8 +66,8 @@ const Template = ({ label, ...args }) => {
// Creates the model and the graph inside the container // Creates the model and the graph inside the container
// using the fastest rendering available on the browser // using the fastest rendering available on the browser
const model = new mxGraphModel(); const model = new GraphModel();
const graph = new mxGraph(container, model); const graph = new Graph(container, model);
// Enables new connections in the graph // Enables new connections in the graph
graph.setConnectable(true); graph.setConnectable(true);
@ -76,8 +76,7 @@ const Template = ({ label, ...args }) => {
// Stops editing on enter or escape keypress // Stops editing on enter or escape keypress
const keyHandler = new mxKeyHandler(graph); const keyHandler = new mxKeyHandler(graph);
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
addVertex('/images/rectangle.gif', 100, 40, ''); addVertex('/images/rectangle.gif', 100, 40, '');
addVertex('/images/rounded.gif', 100, 40, 'shape=rounded'); addVertex('/images/rounded.gif', 100, 40, 'shape=rounded');
@ -88,60 +87,60 @@ const Template = ({ label, ...args }) => {
addVertex('/images/actor.gif', 30, 40, 'shape=actor'); addVertex('/images/actor.gif', 30, 40, 'shape=actor');
function addVertex(icon, w, h, style) { function addVertex(icon, w, h, style) {
const vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style); const vertex = new Cell(null, new Geometry(0, 0, w, h), style);
vertex.setVertex(true); vertex.setVertex(true);
const img = addToolbarItem(graph, toolbar, vertex, icon); const img = addToolbarItem(graph, toolbar, vertex, icon);
img.enabled = true; img.enabled = true;
graph.getSelectionModel().addListener(mxEvent.CHANGE, () => { graph.getSelectionModel().addListener(InternalEvent.CHANGE, () => {
const tmp = graph.isSelectionEmpty(); const tmp = graph.isSelectionEmpty();
mxUtils.setOpacity(img, tmp ? 100 : 20); utils.setOpacity(img, tmp ? 100 : 20);
img.enabled = tmp; img.enabled = tmp;
}); });
} }
function addToolbarItem(graph, toolbar, prototype, image) { function addToolbarItem(graph, toolbar, prototype, image) {
// Function that is executed when the image is dropped on // Function that is executed when the image is dropped on
// the graph. The cell argument points to the cell under // the graph. The cell argument points to the cell under
// the mousepointer if there is one. // the mousepointer if there is one.
const funct = (graph, evt, cell, x, y) => { const funct = (graph, evt, cell, x, y) => {
graph.stopEditing(false); graph.stopEditing(false);
const vertex = graph.getModel().cloneCell(prototype); const vertex = graph.getModel().cloneCell(prototype);
vertex.geometry.x = x; vertex.geometry.x = x;
vertex.geometry.y = y; vertex.geometry.y = y;
graph.addCell(vertex); graph.addCell(vertex);
graph.setSelectionCell(vertex); graph.setSelectionCell(vertex);
}; };
// Creates the image which is used as the drag icon (preview) // Creates the image which is used as the drag icon (preview)
const img = toolbar.addMode(null, image, (evt, cell) => { const img = toolbar.addMode(null, image, (evt, cell) => {
const pt = graph.getPointForEvent(evt); const pt = graph.getPointForEvent(evt);
funct(graph, evt, cell, pt.x, pt.y); funct(graph, evt, cell, pt.x, pt.y);
}); });
// Disables dragging if element is disabled. This is a workaround // Disables dragging if element is disabled. This is a workaround
// for wrong event order in IE. Following is a dummy listener that // for wrong event order in IE. Following is a dummy listener that
// is invoked as the last listener in IE. // is invoked as the last listener in IE.
mxEvent.addListener(img, 'mousedown', evt => { InternalEvent.addListener(img, 'mousedown', (evt) => {
// do nothing // do nothing
}); });
// This listener is always called first before any other listener // This listener is always called first before any other listener
// in all browsers. // in all browsers.
mxEvent.addListener(img, 'mousedown', evt => { InternalEvent.addListener(img, 'mousedown', (evt) => {
if (img.enabled == false) { if (img.enabled == false) {
mxEvent.consume(evt); InternalEvent.consume(evt);
} }
}); });
mxGestureUtils.makeDraggable(img, graph, funct); GestureUtils.makeDraggable(img, graph, funct);
return img; return img;
} }
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,19 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Connections/EdgeTolerance', title: 'Connections/EdgeTolerance',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, utils } = maxgraph;
mxGraph,
mxUtils
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -23,7 +20,7 @@ const Template = ({ label, ...args }) => {
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
container.style.cursor = 'default'; container.style.cursor = 'default';
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
fireMouseEvent(evtName, me, sender) { fireMouseEvent(evtName, me, sender) {
// Overrides the mouse event dispatching mechanism to update the // Overrides the mouse event dispatching mechanism to update the
// cell which is associated with the event in case the native hit // cell which is associated with the event in case the native hit
@ -35,14 +32,14 @@ const Template = ({ label, ...args }) => {
// them here. Storing them in the event means the overridden // them here. Storing them in the event means the overridden
// method doesn't have to do this again. // method doesn't have to do this again.
if (me.graphX == null || me.graphY == null) { if (me.graphX == null || me.graphY == null) {
const pt = mxUtils.convertPoint(container, me.getX(), me.getY()); const pt = utils.convertPoint(container, me.getX(), me.getY());
me.graphX = pt.x; me.graphX = pt.x;
me.graphY = pt.y; me.graphY = pt.y;
} }
const cell = this.getCellAt(me.graphX, me.graphY); const cell = this.getCellAt(me.graphX, me.graphY);
if (cell?.isEdge()) { if (cell?.isEdge()) {
me.state = this.view.getState(cell); me.state = this.view.getState(cell);
@ -62,10 +59,10 @@ const Template = ({ label, ...args }) => {
dblClick(evt, cell) { dblClick(evt, cell) {
// Overrides double click handling to use the tolerance // Overrides double click handling to use the tolerance
if (cell == null) { if (cell == null) {
const pt = mxUtils.convertPoint( const pt = utils.convertPoint(
el, el,
mxEventUtils.getClientX(evt), EventUtils.getClientX(evt),
mxEventUtils.getClientY(evt) EventUtils.getClientY(evt)
); );
cell = this.getCellAt(pt.x, pt.y); cell = this.getCellAt(pt.x, pt.y);
} }
@ -110,6 +107,6 @@ const Template = ({ label, ...args }) => {
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,23 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Editing/Editing', title: 'Editing/Editing',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, mxKeyHandler, utils, mxDomUtils, CloneUtils, EventUtils } = maxgraph;
mxGraph,
mxKeyHandler,
mxUtils,
mxDomUtils,
mxCloneUtils,
mxEventUtils
} = mxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
div.innerHTML = ` div.innerHTML = `
@ -34,7 +27,7 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
div.appendChild(container); div.appendChild(container);
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
getLabel(cell) { getLabel(cell) {
// Returns a HTML representation of the cell where the // Returns a HTML representation of the cell where the
// upper half is the first value, lower half is second // upper half is the first value, lower half is second
@ -79,10 +72,10 @@ const Template = ({ label, ...args }) => {
// a mouse event // a mouse event
if (evt != null) { if (evt != null) {
// Finds the relative coordinates inside the cell // Finds the relative coordinates inside the cell
const point = mxUtils.convertPoint( const point = utils.convertPoint(
this.container, this.container,
mxEventUtils.getClientX(evt), EventUtils.getClientX(evt),
mxEventUtils.getClientY(evt) EventUtils.getClientY(evt)
); );
const state = this.getView().getState(cell); const state = this.getView().getState(cell);
@ -106,7 +99,7 @@ const Template = ({ label, ...args }) => {
if (name != null) { if (name != null) {
// Clones the user object for correct undo and puts // Clones the user object for correct undo and puts
// the new value in the correct field. // the new value in the correct field.
const value = mxCloneUtils.clone(cell.value); const value = CloneUtils.clone(cell.value);
value[name] = newValue; value[name] = newValue;
newValue = value; newValue = value;
@ -143,6 +136,6 @@ const Template = ({ label, ...args }) => {
}); });
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,28 +8,28 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxEvent, InternalEvent,
mxRubberband, Rubberband,
mxConnectionHandler, ConnectionHandler,
mxLayoutManager, LayoutManager,
mxParallelEdgeLayout, mxParallelEdgeLayout,
mxImage, ImageBox,
mxKeyHandler, mxKeyHandler,
mxConstants, Constants,
mxEdgeStyle EdgeStyle,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -39,15 +39,15 @@ const Template = ({ label, ...args }) => {
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
container.style.cursor = 'default'; container.style.cursor = 'default';
class MyCustomConnectionHandler extends mxConnectionHandler { class MyCustomConnectionHandler extends ConnectionHandler {
// Sets the image to be used for creating new connections // Sets the image to be used for creating new connections
connectImage = new mxImage('/images/green-dot.gif', 14, 14); connectImage = new ImageBox('/images/green-dot.gif', 14, 14);
} }
// Disables built-in context menu // Disables built-in context menu
mxEvent.disableContextMenu(container); InternalEvent.disableContextMenu(container);
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
alternateEdgeStyle = 'elbow=vertical'; alternateEdgeStyle = 'elbow=vertical';
getTooltipForCell(cell) { getTooltipForCell(cell) {
@ -64,7 +64,7 @@ const Template = ({ label, ...args }) => {
// Optionally you can enable panning, tooltips and connections // Optionally you can enable panning, tooltips and connections
// using graph.setPanning(), setTooltips() & setConnectable(). // using graph.setPanning(), setTooltips() & setConnectable().
// To enable rubberband selection and basic keyboard events, // To enable rubberband selection and basic keyboard events,
// use new mxRubberband(graph) and new mxKeyHandler(graph). // use new Rubberband(graph) and new mxKeyHandler(graph).
const graph = new MyCustomGraph(container); const graph = new MyCustomGraph(container);
// Enables tooltips, new connections and panning // Enables tooltips, new connections and panning
@ -74,9 +74,9 @@ const Template = ({ label, ...args }) => {
// Automatically handle parallel edges // Automatically handle parallel edges
const layout = new mxParallelEdgeLayout(graph); const layout = new mxParallelEdgeLayout(graph);
const layoutMgr = new mxLayoutManager(graph); const layoutMgr = new LayoutManager(graph);
layoutMgr.getLayout = function(cell) { layoutMgr.getLayout = function (cell) {
if (cell.getChildCount() > 0) { if (cell.getChildCount() > 0) {
return layout; return layout;
} }
@ -84,17 +84,17 @@ const Template = ({ label, ...args }) => {
// Enables rubberband (marquee) selection and a handler // Enables rubberband (marquee) selection and a handler
// for basic keystrokes (eg. return, escape during editing). // for basic keystrokes (eg. return, escape during editing).
const rubberband = new mxRubberband(graph); const rubberband = new Rubberband(graph);
const keyHandler = new mxKeyHandler(graph); const keyHandler = new mxKeyHandler(graph);
// Changes the default style for edges "in-place" and assigns // Changes the default style for edges "in-place" and assigns
// an alternate edge style which is applied in mxGraph.flip // an alternate edge style which is applied in Graph.flip
// when the user double clicks on the adjustment control point // when the user double clicks on the adjustment control point
// of the edge. The ElbowConnector edge style switches to TopToBottom // of the edge. The ElbowConnector edge style switches to TopToBottom
// if the horizontal style is true. // if the horizontal style is true.
const style = graph.getStylesheet().getDefaultEdgeStyle(); const style = graph.getStylesheet().getDefaultEdgeStyle();
style.rounded = true; style.rounded = true;
style.edge = mxEdgeStyle.ElbowConnector; style.edge = EdgeStyle.ElbowConnector;
// Installs a popupmenu handler using local function (see below). // Installs a popupmenu handler using local function (see below).
graph.popupMenuHandler.factoryMethod = (menu, cell, evt) => { graph.popupMenuHandler.factoryMethod = (menu, cell, evt) => {
@ -108,42 +108,10 @@ const Template = ({ label, ...args }) => {
// Adds cells to the model in a single step // Adds cells to the model in a single step
graph.getModel().beginUpdate(); graph.getModel().beginUpdate();
try { try {
const v1 = graph.insertVertex( const v1 = graph.insertVertex(parent, null, 'Doubleclick', 20, 20, 80, 30);
parent, const v2 = graph.insertVertex(parent, null, 'Right-/Shiftclick', 200, 150, 120, 30);
null, const v3 = graph.insertVertex(parent, null, 'Connect/Reconnect', 200, 20, 120, 30);
'Doubleclick', const v4 = graph.insertVertex(parent, null, 'Control-Drag', 20, 150, 100, 30);
20,
20,
80,
30
);
const v2 = graph.insertVertex(
parent,
null,
'Right-/Shiftclick',
200,
150,
120,
30
);
const v3 = graph.insertVertex(
parent,
null,
'Connect/Reconnect',
200,
20,
120,
30
);
const v4 = graph.insertVertex(
parent,
null,
'Control-Drag',
20,
150,
100,
30
);
const e1 = graph.insertEdge(parent, null, 'Tooltips', v1, v2); const e1 = graph.insertEdge(parent, null, 'Tooltips', v1, v2);
const e2 = graph.insertEdge(parent, null, '', v2, v3); const e2 = graph.insertEdge(parent, null, '', v2, v3);
} finally { } finally {
@ -152,7 +120,7 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
function createPopupMenu(graph, menu, cell, evt) { function createPopupMenu(graph, menu, cell, evt) {
// Function to create the entries in the popupmenu // Function to create the entries in the popupmenu
@ -171,4 +139,4 @@ function createPopupMenu(graph, menu, cell, evt) {
}); });
} }
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,24 +8,17 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, InternalEvent, Rubberband, Rectangle, Point, utils } = maxgraph;
mxGraph,
mxEvent,
mxRubberband,
mxRectangle,
mxPoint,
mxUtils
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -35,233 +28,209 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
/** /**
* Specifies the size of the size for "tiles" to be used for a graph with * Specifies the size of the size for "tiles" to be used for a graph with
* scrollbars but no visible background page. A good value is large * scrollbars but no visible background page. A good value is large
* enough to reduce the number of repaints that is caused for auto- * enough to reduce the number of repaints that is caused for auto-
* translation, which depends on this value, and small enough to give * translation, which depends on this value, and small enough to give
* a small empty buffer around the graph. Default is 400x400. * a small empty buffer around the graph. Default is 400x400.
*/
const scrollTileSize = new Rectangle(0, 0, 400, 400);
class MyCustomGraph extends Graph {
/**
* Returns the padding for pages in page view with scrollbars.
*/ */
const scrollTileSize = new mxRectangle(0, 0, 400, 400); getPagePadding() {
return new Point(
Math.max(0, Math.round(this.container.offsetWidth - 34)),
Math.max(0, Math.round(this.container.offsetHeight - 34))
);
}
class MyCustomGraph extends mxGraph { /**
/** * Returns the size of the page format scaled with the page size.
* Returns the padding for pages in page view with scrollbars. */
*/ getPageSize() {
getPagePadding() { return this.pageVisible
return new mxPoint( ? new Rectangle(
Math.max(0, Math.round(this.container.offsetWidth - 34)),
Math.max(0, Math.round(this.container.offsetHeight - 34))
);
}
/**
* Returns the size of the page format scaled with the page size.
*/
getPageSize() {
return this.pageVisible
? new mxRectangle(
0, 0,
0, 0,
this.pageFormat.width * this.pageScale, this.pageFormat.width * this.pageScale,
this.pageFormat.height * this.pageScale this.pageFormat.height * this.pageScale
) )
: scrollTileSize; : scrollTileSize;
}
/**
* Returns a rectangle describing the position and count of the
* background pages, where x and y are the position of the top,
* left page and width and height are the vertical and horizontal
* page count.
*/
getPageLayout() {
const size = this.pageVisible ? this.getPageSize() : scrollTileSize;
const bounds = this.getGraphBounds();
if (bounds.width === 0 || bounds.height === 0) {
return new mxRectangle(0, 0, 1, 1);
}
// Computes untransformed graph bounds
const x = Math.ceil(bounds.x / this.view.scale - this.view.translate.x);
const y = Math.ceil(bounds.y / this.view.scale - this.view.translate.y);
const w = Math.floor(bounds.width / this.view.scale);
const h = Math.floor(bounds.height / this.view.scale);
const x0 = Math.floor(x / size.width);
const y0 = Math.floor(y / size.height);
const w0 = Math.ceil((x + w) / size.width) - x0;
const h0 = Math.ceil((y + h) / size.height) - y0;
return new mxRectangle(x0, y0, w0, h0);
}
getPreferredPageSize(bounds, width, height) {
const pages = this.getPageLayout();
const size = this.getPageSize();
return new mxRectangle(
0,
0,
pages.width * size.width,
pages.height * size.height
);
}
sizeDidChange() {
if (this.container != null && mxUtils.hasScrollbars(this.container)) {
const pages = this.getPageLayout();
const pad = this.getPagePadding();
const size = this.getPageSize();
// Updates the minimum graph size
const minw = Math.ceil(
(2 * pad.x) / this.view.scale + pages.width * size.width
);
const minh = Math.ceil(
(2 * pad.y) / this.view.scale + pages.height * size.height
);
const min = this.minimumGraphSize;
// LATER: Fix flicker of scrollbar size in IE quirks mode
// after delayed call in window.resize event handler
if (min == null || min.width !== minw || min.height !== minh) {
this.minimumGraphSize = new mxRectangle(0, 0, minw, minh);
}
// Updates auto-translate to include padding and graph size
const dx = pad.x / this.view.scale - pages.x * size.width;
const dy = pad.y / this.view.scale - pages.y * size.height;
if (
!this.autoTranslate &&
(this.view.translate.x !== dx || this.view.translate.y !== dy)
) {
this.autoTranslate = true;
this.view.x0 = pages.x;
this.view.y0 = pages.y;
// NOTE: THIS INVOKES THIS METHOD AGAIN. UNFORTUNATELY THERE IS NO WAY AROUND THIS SINCE THE
// BOUNDS ARE KNOWN AFTER THE VALIDATION AND SETTING THE TRANSLATE TRIGGERS A REVALIDATION.
// SHOULD MOVE TRANSLATE/SCALE TO VIEW.
const tx = this.view.translate.x;
const ty = this.view.translate.y;
this.view.setTranslate(dx, dy);
this.container.scrollLeft += (dx - tx) * this.view.scale;
this.container.scrollTop += (dy - ty) * this.view.scale;
this.autoTranslate = false;
return;
}
super.sizeDidChange();
}
}
} }
// Creates the graph inside the given container
const graph = new MyCustomGraph(container);
graph.panningHandler.ignoreCell = true;
graph.setPanning(true);
// Fits the number of background pages to the graph
graph.view.getBackgroundPageBounds = function() {
const layout = this.graph.getPageLayout();
const page = this.graph.getPageSize();
return new mxRectangle(
this.scale * (this.translate.x + layout.x * page.width),
this.scale * (this.translate.y + layout.y * page.height),
this.scale * layout.width * page.width,
this.scale * layout.height * page.height
);
};
/** /**
* Guesses autoTranslate to avoid another repaint (see below). * Returns a rectangle describing the position and count of the
* Works if only the scale of the graph changes or if pages * background pages, where x and y are the position of the top,
* are visible and the visible pages do not change. * left page and width and height are the vertical and horizontal
* page count.
*/ */
const graphViewValidate = graph.view.validate; getPageLayout() {
graph.view.validate = function() { const size = this.pageVisible ? this.getPageSize() : scrollTileSize;
if ( const bounds = this.getGraphBounds();
this.graph.container != null &&
mxUtils.hasScrollbars(this.graph.container)
) {
const pad = this.graph.getPagePadding();
const size = this.graph.getPageSize();
// Updating scrollbars here causes flickering in quirks and is not needed if (bounds.width === 0 || bounds.height === 0) {
// if zoom method is always used to set the current scale on the graph. return new Rectangle(0, 0, 1, 1);
const tx = this.translate.x;
const ty = this.translate.y;
this.translate.x = pad.x / this.scale - (this.x0 || 0) * size.width;
this.translate.y = pad.y / this.scale - (this.y0 || 0) * size.height;
} }
graphViewValidate.apply(this, arguments); // Computes untransformed graph bounds
}; const x = Math.ceil(bounds.x / this.view.scale - this.view.translate.x);
const y = Math.ceil(bounds.y / this.view.scale - this.view.translate.y);
const w = Math.floor(bounds.width / this.view.scale);
const h = Math.floor(bounds.height / this.view.scale);
// Enables rubberband selection const x0 = Math.floor(x / size.width);
if (args.rubberBand) const y0 = Math.floor(y / size.height);
new mxRubberband(graph); const w0 = Math.ceil((x + w) / size.width) - x0;
const h0 = Math.ceil((y + h) / size.height) - y0;
// Gets the default parent for inserting new cells. This return new Rectangle(x0, y0, w0, h0);
// is normally the first child of the root (ie. layer 0). }
const parent = graph.getDefaultParent();
// Adds cells to the model in a single step getPreferredPageSize(bounds, width, height) {
graph.batchUpdate(() => { const pages = this.getPageLayout();
const v1 = graph.insertVertex({ const size = this.getPageSize();
parent,
value: 'Hello,', return new Rectangle(0, 0, pages.width * size.width, pages.height * size.height);
position: [20, 20], }
size: [80, 30],
}); sizeDidChange() {
const v2 = graph.insertVertex({ if (this.container != null && utils.hasScrollbars(this.container)) {
parent, const pages = this.getPageLayout();
value: 'World!', const pad = this.getPagePadding();
position: [200, 150], const size = this.getPageSize();
size: [80, 30],
}); // Updates the minimum graph size
const e1 = graph.insertEdge({ const minw = Math.ceil((2 * pad.x) / this.view.scale + pages.width * size.width);
parent, const minh = Math.ceil(
source: v1, (2 * pad.y) / this.view.scale + pages.height * size.height
target: v2, );
});
const min = this.minimumGraphSize;
// LATER: Fix flicker of scrollbar size in IE quirks mode
// after delayed call in window.resize event handler
if (min == null || min.width !== minw || min.height !== minh) {
this.minimumGraphSize = new Rectangle(0, 0, minw, minh);
}
// Updates auto-translate to include padding and graph size
const dx = pad.x / this.view.scale - pages.x * size.width;
const dy = pad.y / this.view.scale - pages.y * size.height;
if (
!this.autoTranslate &&
(this.view.translate.x !== dx || this.view.translate.y !== dy)
) {
this.autoTranslate = true;
this.view.x0 = pages.x;
this.view.y0 = pages.y;
// NOTE: THIS INVOKES THIS METHOD AGAIN. UNFORTUNATELY THERE IS NO WAY AROUND THIS SINCE THE
// BOUNDS ARE KNOWN AFTER THE VALIDATION AND SETTING THE TRANSLATE TRIGGERS A REVALIDATION.
// SHOULD MOVE TRANSLATE/SCALE TO VIEW.
const tx = this.view.translate.x;
const ty = this.view.translate.y;
this.view.setTranslate(dx, dy);
this.container.scrollLeft += (dx - tx) * this.view.scale;
this.container.scrollTop += (dy - ty) * this.view.scale;
this.autoTranslate = false;
return;
}
super.sizeDidChange();
}
}
}
// Creates the graph inside the given container
const graph = new MyCustomGraph(container);
graph.panningHandler.ignoreCell = true;
graph.setPanning(true);
// Fits the number of background pages to the graph
graph.view.getBackgroundPageBounds = function () {
const layout = this.graph.getPageLayout();
const page = this.graph.getPageSize();
return new Rectangle(
this.scale * (this.translate.x + layout.x * page.width),
this.scale * (this.translate.y + layout.y * page.height),
this.scale * layout.width * page.width,
this.scale * layout.height * page.height
);
};
/**
* Guesses autoTranslate to avoid another repaint (see below).
* Works if only the scale of the graph changes or if pages
* are visible and the visible pages do not change.
*/
const graphViewValidate = graph.view.validate;
graph.view.validate = function () {
if (this.graph.container != null && utils.hasScrollbars(this.graph.container)) {
const pad = this.graph.getPagePadding();
const size = this.graph.getPageSize();
// Updating scrollbars here causes flickering in quirks and is not needed
// if zoom method is always used to set the current scale on the graph.
const tx = this.translate.x;
const ty = this.translate.y;
this.translate.x = pad.x / this.scale - (this.x0 || 0) * size.width;
this.translate.y = pad.y / this.scale - (this.y0 || 0) * size.height;
}
graphViewValidate.apply(this, arguments);
};
// Enables rubberband selection
if (args.rubberBand) new Rubberband(graph);
// Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0).
const parent = graph.getDefaultParent();
// Adds cells to the model in a single step
graph.batchUpdate(() => {
const v1 = graph.insertVertex({
parent,
value: 'Hello,',
position: [20, 20],
size: [80, 30],
}); });
const v2 = graph.insertVertex({
parent,
value: 'World!',
position: [200, 150],
size: [80, 30],
});
const e1 = graph.insertEdge({
parent,
source: v1,
target: v2,
});
});
// Sets initial scrollbar positions // Sets initial scrollbar positions
window.setTimeout(() => { window.setTimeout(() => {
const bounds = graph.getGraphBounds(); const bounds = graph.getGraphBounds();
const width = Math.max( const width = Math.max(bounds.width, scrollTileSize.width * graph.view.scale);
bounds.width, const height = Math.max(bounds.height, scrollTileSize.height * graph.view.scale);
scrollTileSize.width * graph.view.scale graph.container.scrollTop = Math.floor(
); Math.max(0, bounds.y - Math.max(20, (graph.container.clientHeight - height) / 4))
const height = Math.max( );
bounds.height, graph.container.scrollLeft = Math.floor(
scrollTileSize.height * graph.view.scale Math.max(0, bounds.x - Math.max(0, (graph.container.clientWidth - width) / 2))
); );
graph.container.scrollTop = Math.floor( }, 0);
Math.max(
0,
bounds.y - Math.max(20, (graph.container.clientHeight - height) / 4)
)
);
graph.container.scrollLeft = Math.floor(
Math.max(
0,
bounds.x - Math.max(0, (graph.container.clientWidth - width) / 2)
)
);
}, 0);
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,23 +1,20 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
import { error } from '@mxgraph/core/src/util/mxDomUtils'; import { error } from '@maxgraph/core/util/DomUtils';
import { clone } from '@mxgraph/core/src/util/CloneUtils'; import { clone } from '@maxgraph/core/util/CloneUtils';
import { button } from '@mxgraph/core/src/util/dom/mxDomHelpers'; import { button } from '@maxgraph/core/util/dom/mxDomHelpers';
import { load } from '@mxgraph/core/src/util/network/mxXmlRequest'; import { load } from '@maxgraph/core/util/network/mxXmlRequest';
export default { export default {
title: 'Xml_Json/FileIO', title: 'Xml_Json/FileIO',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Constants } = maxgraph;
mxGraph,
mxConstants
} = mxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -41,7 +38,7 @@ const Template = ({ label, ...args }) => {
error('Browser is not supported!', 200, false); error('Browser is not supported!', 200, false);
} else { } else {
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setEnabled(false); graph.setEnabled(false);
graph.setPanning(true); graph.setPanning(true);
@ -53,7 +50,7 @@ const Template = ({ label, ...args }) => {
// Changes the default vertex style in-place // Changes the default vertex style in-place
let style = graph.getStylesheet().getDefaultVertexStyle(); let style = graph.getStylesheet().getDefaultVertexStyle();
style.shape = mxConstants.SHAPE_ROUNDED; style.shape = Constants.SHAPE_ROUNDED;
style.perimiter = Perimeter.RectanglePerimeter; style.perimiter = Perimeter.RectanglePerimeter;
style.gradientColor = 'white'; style.gradientColor = 'white';
style.perimeterSpacing = 4; style.perimeterSpacing = 4;
@ -63,10 +60,10 @@ const Template = ({ label, ...args }) => {
style.labelBackgroundColor = 'white'; style.labelBackgroundColor = 'white';
style = clone(style); style = clone(style);
style.startArrow = mxConstants.ARROW_CLASSIC; style.startArrow = Constants.ARROW_CLASSIC;
graph.getStylesheet().putCellStyle('2way', style); graph.getStylesheet().putCellStyle('2way', style);
graph.isHtmlLabel = function(cell) { graph.isHtmlLabel = function (cell) {
return true; return true;
}; };
@ -82,7 +79,7 @@ const Template = ({ label, ...args }) => {
// Adds a button to execute the layout // Adds a button to execute the layout
this.el2.appendChild( this.el2.appendChild(
button('Arrange', function(evt) { button('Arrange', function (evt) {
const parent = graph.getDefaultParent(); const parent = graph.getDefaultParent();
layout.execute(parent); layout.execute(parent);
}) })
@ -94,7 +91,7 @@ const Template = ({ label, ...args }) => {
// Loads the custom file format (TXT file) // Loads the custom file format (TXT file)
parse(graph, 'fileio.txt'); parse(graph, 'fileio.txt');
// Loads the mxGraph file format (XML file) // Loads the Graph file format (XML file)
// read(graph, 'fileio.xml'); // read(graph, 'fileio.xml');
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
@ -108,9 +105,9 @@ const Template = ({ label, ...args }) => {
graph.getModel().endUpdate(); graph.getModel().endUpdate();
} }
graph.dblClick = function(evt, cell) { graph.dblClick = function (evt, cell) {
const mxe = new EventObject( const mxe = new EventObject(
mxEvent.DOUBLE_CLICK, InternalEvent.DOUBLE_CLICK,
'event', 'event',
evt, evt,
'cell', 'cell',
@ -120,13 +117,11 @@ const Template = ({ label, ...args }) => {
if ( if (
this.isEnabled() && this.isEnabled() &&
!mxEvent.isConsumed(evt) && !InternalEvent.isConsumed(evt) &&
!mxe.isConsumed() && !mxe.isConsumed() &&
cell != null cell != null
) { ) {
alert( alert(`Show properties for cell ${cell.customId || cell.getId()}`);
`Show properties for cell ${cell.customId || cell.getId()}`
);
} }
}; };
} }
@ -163,15 +158,7 @@ const Template = ({ label, ...args }) => {
const key = lines[i].substring(0, colon); const key = lines[i].substring(0, colon);
if (key.length > 0) { if (key.length > 0) {
vertices[key] = graph.insertVertex( vertices[key] = graph.insertVertex(parent, null, value, 0, 0, 80, 70);
parent,
null,
value,
0,
0,
80,
70
);
} }
} else if (comma < colon) { } else if (comma < colon) {
// Looks up the vertices in the lookup table // Looks up the vertices in the lookup table
@ -194,7 +181,7 @@ const Template = ({ label, ...args }) => {
} }
} }
// Parses the mxGraph XML file format // Parses the Graph XML file format
function read(graph, filename) { function read(graph, filename) {
const req = load(filename); const req = load(filename);
const root = req.getDocumentElement(); const root = req.getDocumentElement();
@ -204,6 +191,6 @@ const Template = ({ label, ...args }) => {
} }
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,20 +8,13 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Rubberband, Rectangle, Constants, utils, mxLabel } = maxgraph;
mxGraph,
mxRubberband,
mxRectangle,
mxConstants,
mxUtils,
mxLabel
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -32,38 +25,29 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Overrides the image bounds code to change the position // Overrides the image bounds code to change the position
mxLabel.prototype.getImageBounds = function(x, y, w, h) { mxLabel.prototype.getImageBounds = function (x, y, w, h) {
const iw = mxUtils.getValue( const iw = utils.getValue(this.style, 'imageWidth', Constants.DEFAULT_IMAGESIZE);
this.style, const ih = utils.getValue(this.style, 'imageHeight', Constants.DEFAULT_IMAGESIZE);
'imageWidth',
mxConstants.DEFAULT_IMAGESIZE
);
const ih = mxUtils.getValue(
this.style,
'imageHeight',
mxConstants.DEFAULT_IMAGESIZE
);
// Places the icon // Places the icon
const ix = (w - iw) / 2; const ix = (w - iw) / 2;
const iy = h - ih; const iy = h - ih;
return new mxRectangle(x + ix, y + iy, iw, ih); return new Rectangle(x + ix, y + iy, iw, ih);
}; };
// Makes the shadow brighter // Makes the shadow brighter
mxConstants.SHADOWCOLOR = '#C0C0C0'; Constants.SHADOWCOLOR = '#C0C0C0';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Uncomment the following if you want the container // Uncomment the following if you want the container
// to fit the size of the graph // to fit the size of the graph
// graph.setResizeContainer(true); // graph.setResizeContainer(true);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -89,6 +73,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,7 +1,7 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
import { intersects } from '@mxgraph/core/src/util/Utils'; import { intersects } from '@maxgraph/core/util/Utils';
export default { export default {
title: 'Connections/FixedPoints', title: 'Connections/FixedPoints',
@ -9,22 +9,22 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxRubberband, Rubberband,
mxConnectionHandler, ConnectionHandler,
mxConnectionConstraint, ConnectionConstraint,
mxConstraintHandler, ConstraintHandler,
mxPoint, Point,
mxCellState, CellState,
mxEdgeHandler EdgeHandler,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -34,17 +34,15 @@ const Template = ({ label, ...args }) => {
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
container.style.cursor = 'default'; container.style.cursor = 'default';
class MyCustomConstraintHandler extends mxConstraintHandler { class MyCustomConstraintHandler extends ConstraintHandler {
// Snaps to fixed points // Snaps to fixed points
intersects(icon, point, source, existingEdge) { intersects(icon, point, source, existingEdge) {
return ( return !source || existingEdge || intersects(icon.bounds, point);
!source || existingEdge || intersects(icon.bounds, point)
);
} }
} }
class MyCustomConnectionHandler extends mxConnectionHandler { class MyCustomConnectionHandler extends ConnectionHandler {
// connectImage = new mxImage('images/connector.gif', 16, 16); // connectImage = new ImageBox('images/connector.gif', 16, 16);
isConnectableCell(cell) { isConnectableCell(cell) {
return false; return false;
@ -59,21 +57,15 @@ const Template = ({ label, ...args }) => {
*/ */
updateEdgeState(pt, constraint) { updateEdgeState(pt, constraint) {
if (pt != null && this.previous != null) { if (pt != null && this.previous != null) {
const constraints = this.graph.getAllConnectionConstraints( const constraints = this.graph.getAllConnectionConstraints(this.previous);
this.previous
);
let nearestConstraint = null; let nearestConstraint = null;
let dist = null; let dist = null;
for (let i = 0; i < constraints.length; i++) { for (let i = 0; i < constraints.length; i++) {
const cp = this.graph.getConnectionPoint( const cp = this.graph.getConnectionPoint(this.previous, constraints[i]);
this.previous,
constraints[i]
);
if (cp != null) { if (cp != null) {
const tmp = const tmp = (cp.x - pt.x) * (cp.x - pt.x) + (cp.y - pt.y) * (cp.y - pt.y);
(cp.x - pt.x) * (cp.x - pt.x) + (cp.y - pt.y) * (cp.y - pt.y);
if (dist == null || tmp < dist) { if (dist == null || tmp < dist) {
nearestConstraint = constraints[i]; nearestConstraint = constraints[i];
@ -90,7 +82,7 @@ const Template = ({ label, ...args }) => {
// this.edgeState.style.edgeStyle = 'orthogonalEdgeStyle'; // this.edgeState.style.edgeStyle = 'orthogonalEdgeStyle';
// And to use the new edge style in the new edge inserted into the graph, // And to use the new edge style in the new edge inserted into the graph,
// update the cell style as follows: // update the cell style as follows:
// this.edgeState.cell.style = mxUtils.setStyle(this.edgeState.cell.style, 'edgeStyle', this.edgeState.style.edgeStyle); // this.edgeState.cell.style = utils.setStyle(this.edgeState.cell.style, 'edgeStyle', this.edgeState.style.edgeStyle);
} }
return super.updateEdgeState(pt, constraint); return super.updateEdgeState(pt, constraint);
} }
@ -106,22 +98,18 @@ const Template = ({ label, ...args }) => {
'edgeStyle=orthogonalEdgeStyle' 'edgeStyle=orthogonalEdgeStyle'
); );
return new mxCellState( return new CellState(this.graph.view, edge, this.graph.getCellStyle(edge));
this.graph.view,
edge,
this.graph.getCellStyle(edge)
);
} }
} }
class MyCustomEdgeHandler extends mxEdgeHandler { class MyCustomEdgeHandler extends EdgeHandler {
// Disables floating connections (only use with no connect image) // Disables floating connections (only use with no connect image)
isConnectableCell(cell) { isConnectableCell(cell) {
return graph.connectionHandler.isConnectableCell(cell); return graph.connectionHandler.isConnectableCell(cell);
} }
} }
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
createConnectionHandler() { createConnectionHandler() {
const r = new MyCustomConnectionHandler(); const r = new MyCustomConnectionHandler();
r.constraintHandler = new MyCustomConstraintHandler(this); r.constraintHandler = new MyCustomConstraintHandler(this);
@ -137,14 +125,14 @@ const Template = ({ label, ...args }) => {
getAllConnectionConstraints(terminal) { getAllConnectionConstraints(terminal) {
if (terminal != null && terminal.cell.isVertex()) { if (terminal != null && terminal.cell.isVertex()) {
return [ return [
new mxConnectionConstraint(new mxPoint(0, 0), true), new ConnectionConstraint(new Point(0, 0), true),
new mxConnectionConstraint(new mxPoint(0.5, 0), true), new ConnectionConstraint(new Point(0.5, 0), true),
new mxConnectionConstraint(new mxPoint(1, 0), true), new ConnectionConstraint(new Point(1, 0), true),
new mxConnectionConstraint(new mxPoint(0, 0.5), true), new ConnectionConstraint(new Point(0, 0.5), true),
new mxConnectionConstraint(new mxPoint(1, 0.5), true), new ConnectionConstraint(new Point(1, 0.5), true),
new mxConnectionConstraint(new mxPoint(0, 1), true), new ConnectionConstraint(new Point(0, 1), true),
new mxConnectionConstraint(new mxPoint(0.5, 1), true), new ConnectionConstraint(new Point(0.5, 1), true),
new mxConnectionConstraint(new mxPoint(1, 1), true), new ConnectionConstraint(new Point(1, 1), true),
]; ];
} }
return null; return null;
@ -156,8 +144,7 @@ const Template = ({ label, ...args }) => {
graph.setConnectable(true); graph.setConnectable(true);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -208,16 +195,16 @@ const Template = ({ label, ...args }) => {
// Use this code to snap the source point for new connections without a connect preview, // Use this code to snap the source point for new connections without a connect preview,
// ie. without an overridden graph.connectionHandler.createEdgeState // ie. without an overridden graph.connectionHandler.createEdgeState
/* /*
let mxConnectionHandlerMouseMove = mxConnectionHandler.prototype.mouseMove; let mxConnectionHandlerMouseMove = ConnectionHandler.prototype.mouseMove;
mxConnectionHandler.prototype.mouseMove = function(sender, me) ConnectionHandler.prototype.mouseMove = function(sender, me)
{ {
this.sourceConstraint = null; this.sourceConstraint = null;
mxConnectionHandlerMouseMove.apply(this, arguments); mxConnectionHandlerMouseMove.apply(this, arguments);
}; };
let mxConnectionHandlerGetSourcePerimeterPoint = mxConnectionHandler.prototype.getSourcePerimeterPoint; let mxConnectionHandlerGetSourcePerimeterPoint = ConnectionHandler.prototype.getSourcePerimeterPoint;
mxConnectionHandler.prototype.getSourcePerimeterPoint = function(state, pt, me) ConnectionHandler.prototype.getSourcePerimeterPoint = function(state, pt, me)
{ {
let result = null; let result = null;
@ -262,6 +249,6 @@ const Template = ({ label, ...args }) => {
*/ */
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,22 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Layouts/Folding', title: 'Layouts/Folding',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Constants, EdgeStyle, StackLayout, LayoutManager } = maxgraph;
mxGraph,
mxConstants,
mxEdgeStyle,
mxStackLayout,
mxLayoutManager
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -27,10 +21,10 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Enables crisp rendering of rectangles in SVG // Enables crisp rendering of rectangles in SVG
mxConstants.ENTITY_SEGMENT = 20; Constants.ENTITY_SEGMENT = 20;
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setDropEnabled(true); graph.setDropEnabled(true);
// Disables global features // Disables global features
@ -43,7 +37,7 @@ const Template = ({ label, ...args }) => {
// Sets global styles // Sets global styles
let style = graph.getStylesheet().getDefaultEdgeStyle(); let style = graph.getStylesheet().getDefaultEdgeStyle();
style.edge = mxEdgeStyle.EntityRelation; style.edge = EdgeStyle.EntityRelation;
style.rounded = true; style.rounded = true;
style = graph.getStylesheet().getDefaultVertexStyle(); style = graph.getStylesheet().getDefaultVertexStyle();
@ -52,17 +46,17 @@ const Template = ({ label, ...args }) => {
style.startSize = 30; style.startSize = 30;
style = []; style = [];
style.shape = mxConstants.SHAPE_RECTANGLE; style.shape = Constants.SHAPE_RECTANGLE;
style.strokeColor = 'none'; style.strokeColor = 'none';
style.fillColor = 'none'; style.fillColor = 'none';
style.foldable = false; style.foldable = false;
graph.getStylesheet().putCellStyle('column', style); graph.getStylesheet().putCellStyle('column', style);
// Installs auto layout for all levels // Installs auto layout for all levels
const layout = new mxStackLayout(graph, true); const layout = new StackLayout(graph, true);
layout.border = graph.border; layout.border = graph.border;
const layoutMgr = new mxLayoutManager(graph); const layoutMgr = new LayoutManager(graph);
layoutMgr.getLayout = function(cell) { layoutMgr.getLayout = function (cell) {
if (!cell.collapsed) { if (!cell.collapsed) {
if (cell.parent !== graph.model.root) { if (cell.parent !== graph.model.root) {
layout.resizeParent = true; layout.resizeParent = true;
@ -140,6 +134,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,26 +8,26 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxEvent, InternalEvent,
mxRubberband, Rubberband,
mxLog, mxLog,
mxGraphView, GraphView,
mxPoint, Point,
mxDomHelpers, mxDomHelpers,
mxEventUtils EventUtils,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -39,73 +39,69 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
div.appendChild(container); div.appendChild(container);
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
// Creates the graph inside the given container // Creates the graph inside the given container
var graph = new mxGraph(container); var graph = new Graph(container);
graph.graphHandler.scaleGrid = true; graph.graphHandler.scaleGrid = true;
graph.setPanning(true); graph.setPanning(true);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
let repaintGrid; let repaintGrid;
// Create grid dynamically (requires canvas) // Create grid dynamically (requires canvas)
(function() (function () {
{ try {
try
{
var canvas = document.createElement('canvas'); var canvas = document.createElement('canvas');
canvas.style.position = 'absolute'; canvas.style.position = 'absolute';
canvas.style.top = '0px'; canvas.style.top = '0px';
canvas.style.left = '0px'; canvas.style.left = '0px';
canvas.style.zIndex = -1; canvas.style.zIndex = -1;
graph.container.appendChild(canvas); graph.container.appendChild(canvas);
var ctx = canvas.getContext('2d'); var ctx = canvas.getContext('2d');
// Modify event filtering to accept canvas as container // Modify event filtering to accept canvas as container
var mxGraphViewIsContainerEvent = mxGraphView.prototype.isContainerEvent; var mxGraphViewIsContainerEvent = GraphView.prototype.isContainerEvent;
mxGraphView.prototype.isContainerEvent = function(evt) GraphView.prototype.isContainerEvent = function (evt) {
{ return (
return mxGraphViewIsContainerEvent.apply(this, arguments) || mxGraphViewIsContainerEvent.apply(this, arguments) ||
mxEventUtils.getSource(evt) == canvas; EventUtils.getSource(evt) == canvas
);
}; };
var s = 0; var s = 0;
var gs = 0; var gs = 0;
var tr = new mxPoint(); var tr = new Point();
var w = 0; var w = 0;
var h = 0; var h = 0;
repaintGrid = function() repaintGrid = function () {
{ if (ctx != null) {
if (ctx != null)
{
var bounds = graph.getGraphBounds(); var bounds = graph.getGraphBounds();
var width = Math.max(bounds.x + bounds.width, graph.container.clientWidth); var width = Math.max(bounds.x + bounds.width, graph.container.clientWidth);
var height = Math.max(bounds.y + bounds.height, graph.container.clientHeight); var height = Math.max(bounds.y + bounds.height, graph.container.clientHeight);
var sizeChanged = width != w || height != h; var sizeChanged = width != w || height != h;
if (graph.view.scale != s || graph.view.translate.x != tr.x || graph.view.translate.y != tr.y || if (
gs != graph.gridSize || sizeChanged) graph.view.scale != s ||
{ graph.view.translate.x != tr.x ||
graph.view.translate.y != tr.y ||
gs != graph.gridSize ||
sizeChanged
) {
tr = graph.view.translate.clone(); tr = graph.view.translate.clone();
s = graph.view.scale; s = graph.view.scale;
gs = graph.gridSize; gs = graph.gridSize;
w = width; w = width;
h = height; h = height;
// Clears the background if required // Clears the background if required
if (!sizeChanged) if (!sizeChanged) {
{
ctx.clearRect(0, 0, w, h); ctx.clearRect(0, 0, w, h);
} } else {
else
{
canvas.setAttribute('width', w); canvas.setAttribute('width', w);
canvas.setAttribute('height', h); canvas.setAttribute('height', h);
} }
@ -117,8 +113,7 @@ const Template = ({ label, ...args }) => {
var minStepping = graph.gridSize; var minStepping = graph.gridSize;
var stepping = minStepping * s; var stepping = minStepping * s;
if (stepping < minStepping) if (stepping < minStepping) {
{
var count = Math.round(Math.ceil(minStepping / stepping) / 2) * 2; var count = Math.round(Math.ceil(minStepping / stepping) / 2) * 2;
stepping = count * stepping; stepping = count * stepping;
} }
@ -139,21 +134,19 @@ const Template = ({ label, ...args }) => {
// Draws the actual grid // Draws the actual grid
ctx.strokeStyle = '#f6f6f6'; ctx.strokeStyle = '#f6f6f6';
ctx.beginPath(); ctx.beginPath();
for (var x = xs; x <= xe; x += stepping) for (var x = xs; x <= xe; x += stepping) {
{
x = Math.round((x - tx) / stepping) * stepping + tx; x = Math.round((x - tx) / stepping) * stepping + tx;
var ix = Math.round(x); var ix = Math.round(x);
ctx.moveTo(ix + 0.5, iys + 0.5); ctx.moveTo(ix + 0.5, iys + 0.5);
ctx.lineTo(ix + 0.5, iye + 0.5); ctx.lineTo(ix + 0.5, iye + 0.5);
} }
for (var y = ys; y <= ye; y += stepping) for (var y = ys; y <= ye; y += stepping) {
{
y = Math.round((y - ty) / stepping) * stepping + ty; y = Math.round((y - ty) / stepping) * stepping + ty;
var iy = Math.round(y); var iy = Math.round(y);
ctx.moveTo(ixs + 0.5, iy + 0.5); ctx.moveTo(ixs + 0.5, iy + 0.5);
ctx.lineTo(ixe + 0.5, iy + 0.5); ctx.lineTo(ixe + 0.5, iy + 0.5);
} }
@ -163,58 +156,53 @@ const Template = ({ label, ...args }) => {
} }
} }
}; };
} } catch (e) {
catch (e)
{
mxLog.show(); mxLog.show();
mxLog.debug('Using background image'); mxLog.debug('Using background image');
container.style.backgroundImage = 'url(\'editors/images/grid.gif\')'; container.style.backgroundImage = "url('editors/images/grid.gif')";
} }
var mxGraphViewValidateBackground = mxGraphView.prototype.validateBackground; var mxGraphViewValidateBackground = GraphView.prototype.validateBackground;
mxGraphView.prototype.validateBackground = function() GraphView.prototype.validateBackground = function () {
{
mxGraphViewValidateBackground.apply(this, arguments); mxGraphViewValidateBackground.apply(this, arguments);
repaintGrid(); repaintGrid();
}; };
})(); })();
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
var parent = graph.getDefaultParent(); var parent = graph.getDefaultParent();
// Adds cells to the model in a single step // Adds cells to the model in a single step
graph.getModel().beginUpdate(); graph.getModel().beginUpdate();
try try {
{
var v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30); var v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
var v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30); var v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
var e1 = graph.insertEdge(parent, null, '', v1, v2); var e1 = graph.insertEdge(parent, null, '', v1, v2);
} } finally {
finally
{
// Updates the display // Updates the display
graph.getModel().endUpdate(); graph.getModel().endUpdate();
} }
graph.centerZoom = false; graph.centerZoom = false;
const controller = document.createElement('div'); const controller = document.createElement('div');
div.appendChild(controller); div.appendChild(controller);
controller.appendChild(mxDomHelpers.button('+', function() controller.appendChild(
{ mxDomHelpers.button('+', function () {
graph.zoomIn(); graph.zoomIn();
})); })
);
controller.appendChild(mxDomHelpers.button('-', function()
{ controller.appendChild(
graph.zoomOut(); mxDomHelpers.button('-', function () {
})); graph.zoomOut();
})
);
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,18 +8,13 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Rubberband, GraphHandler, mxPopupMenuHandler } = maxgraph;
mxGraph,
mxRubberband,
mxGraphHandler,
mxPopupMenuHandler
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -30,27 +25,24 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Overrides check for valid roots // Overrides check for valid roots
mxGraph.prototype.isValidRoot = function() { Graph.prototype.isValidRoot = function () {
return false; return false;
}; };
// Don't clear selection if multiple cells selected // Don't clear selection if multiple cells selected
const graphHandlerMouseDown = mxGraphHandler.prototype.mouseDown; const graphHandlerMouseDown = GraphHandler.prototype.mouseDown;
mxGraphHandler.prototype.mouseDown = function(sender, me) { GraphHandler.prototype.mouseDown = function (sender, me) {
graphHandlerMouseDown.apply(this, arguments); graphHandlerMouseDown.apply(this, arguments);
if ( if (this.graph.isCellSelected(me.getCell()) && this.graph.getSelectionCount() > 1) {
this.graph.isCellSelected(me.getCell()) &&
this.graph.getSelectionCount() > 1
) {
this.delayedSelection = false; this.delayedSelection = false;
} }
}; };
// Selects descendants before children selection mode // Selects descendants before children selection mode
const graphHandlerGetInitialCellForEvent = const graphHandlerGetInitialCellForEvent =
mxGraphHandler.prototype.getInitialCellForEvent; GraphHandler.prototype.getInitialCellForEvent;
mxGraphHandler.prototype.getInitialCellForEvent = function(me) { GraphHandler.prototype.getInitialCellForEvent = function (me) {
const model = this.graph.getModel(); const model = this.graph.getModel();
const psel = this.graph.getSelectionCell().getParent(); const psel = this.graph.getSelectionCell().getParent();
let cell = graphHandlerGetInitialCellForEvent.apply(this, arguments); let cell = graphHandlerGetInitialCellForEvent.apply(this, arguments);
@ -72,9 +64,8 @@ const Template = ({ label, ...args }) => {
}; };
// Selection is delayed to mouseup if child selected // Selection is delayed to mouseup if child selected
const graphHandlerIsDelayedSelection = const graphHandlerIsDelayedSelection = GraphHandler.prototype.isDelayedSelection;
mxGraphHandler.prototype.isDelayedSelection; GraphHandler.prototype.isDelayedSelection = function (cell) {
mxGraphHandler.prototype.isDelayedSelection = function(cell) {
let result = graphHandlerIsDelayedSelection.apply(this, arguments); let result = graphHandlerIsDelayedSelection.apply(this, arguments);
const model = this.graph.getModel(); const model = this.graph.getModel();
const psel = this.graph.getSelectionCell().getParent(); const psel = this.graph.getSelectionCell().getParent();
@ -94,7 +85,7 @@ const Template = ({ label, ...args }) => {
}; };
// Delayed selection of parent group // Delayed selection of parent group
mxGraphHandler.prototype.selectDelayed = function(me) { GraphHandler.prototype.selectDelayed = function (me) {
let cell = me.getCell(); let cell = me.getCell();
if (cell == null) { if (cell == null) {
@ -117,7 +108,7 @@ const Template = ({ label, ...args }) => {
}; };
// Returns last selected ancestor // Returns last selected ancestor
mxPopupMenuHandler.prototype.getCellForPopupEvent = function(me) { mxPopupMenuHandler.prototype.getCellForPopupEvent = function (me) {
let cell = me.getCell(); let cell = me.getCell();
const model = this.graph.getModel(); const model = this.graph.getModel();
let parent = cell.getParent(); let parent = cell.getParent();
@ -134,7 +125,7 @@ const Template = ({ label, ...args }) => {
}; };
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.constrainChildren = false; graph.constrainChildren = false;
graph.extendParents = false; graph.extendParents = false;
graph.extendParentsOnAdd = false; graph.extendParentsOnAdd = false;
@ -144,8 +135,7 @@ const Template = ({ label, ...args }) => {
// graph.setResizeContainer(true); // graph.setResizeContainer(true);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -162,6 +152,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,21 +8,21 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxGraphHandler, GraphHandler,
mxEvent, InternalEvent,
mxConstants, Constants,
mxEdgeHandler, EdgeHandler,
mxEdgeStyle, EdgeStyle,
mxRubberband Rubberband,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -33,40 +33,39 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Enables guides // Enables guides
mxGraphHandler.prototype.guidesEnabled = true; GraphHandler.prototype.guidesEnabled = true;
// Alt disables guides // Alt disables guides
mxGraphHandler.prototype.useGuidesForEvent = function(me) { GraphHandler.prototype.useGuidesForEvent = function (me) {
return !mxEvent.isAltDown(me.getEvent()); return !InternalEvent.isAltDown(me.getEvent());
}; };
// Defines the guides to be red (default) // Defines the guides to be red (default)
mxConstants.GUIDE_COLOR = '#FF0000'; Constants.GUIDE_COLOR = '#FF0000';
// Defines the guides to be 1 pixel (default) // Defines the guides to be 1 pixel (default)
mxConstants.GUIDE_STROKEWIDTH = 1; Constants.GUIDE_STROKEWIDTH = 1;
// Enables snapping waypoints to terminals // Enables snapping waypoints to terminals
mxEdgeHandler.prototype.snapToTerminals = true; EdgeHandler.prototype.snapToTerminals = true;
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setConnectable(true); graph.setConnectable(true);
graph.gridSize = 30; graph.gridSize = 30;
// Changes the default style for edges "in-place" and assigns // Changes the default style for edges "in-place" and assigns
// an alternate edge style which is applied in mxGraph.flip // an alternate edge style which is applied in Graph.flip
// when the user double clicks on the adjustment control point // when the user double clicks on the adjustment control point
// of the edge. The ElbowConnector edge style switches to TopToBottom // of the edge. The ElbowConnector edge style switches to TopToBottom
// if the horizontal style is true. // if the horizontal style is true.
const style = graph.getStylesheet().getDefaultEdgeStyle(); const style = graph.getStylesheet().getDefaultEdgeStyle();
style.rounded = true; style.rounded = true;
style.edge = mxEdgeStyle.ElbowConnector; style.edge = EdgeStyle.ElbowConnector;
graph.alternateEdgeStyle = 'elbow=vertical'; graph.alternateEdgeStyle = 'elbow=vertical';
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -85,7 +84,7 @@ const Template = ({ label, ...args }) => {
} }
// Handles cursor keys // Handles cursor keys
const nudge = function(keyCode) { const nudge = function (keyCode) {
if (!graph.isSelectionEmpty()) { if (!graph.isSelectionEmpty()) {
let dx = 0; let dx = 0;
let dy = 0; let dy = 0;
@ -111,26 +110,26 @@ const Template = ({ label, ...args }) => {
// Ignores enter keystroke. Remove this line if you want the // Ignores enter keystroke. Remove this line if you want the
// enter keystroke to stop editing // enter keystroke to stop editing
keyHandler.enter = function() {}; keyHandler.enter = function () {};
keyHandler.bindKey(37, function() { keyHandler.bindKey(37, function () {
nudge(37); nudge(37);
}); });
keyHandler.bindKey(38, function() { keyHandler.bindKey(38, function () {
nudge(38); nudge(38);
}); });
keyHandler.bindKey(39, function() { keyHandler.bindKey(39, function () {
nudge(39); nudge(39);
}); });
keyHandler.bindKey(40, function() { keyHandler.bindKey(40, function () {
nudge(40); nudge(40);
}); });
}; };
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,29 +8,29 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxCylinder, CylinderShape,
mxDomHelpers, mxDomHelpers,
mxCellRenderer, CellRenderer,
mxPoint, Point,
mxRectangle, Rectangle,
mxVertexHandler, VertexHandler,
mxEvent, InternalEvent,
mxRubberband, Rubberband,
mxUtils, utils,
mxHandle VertexHandle,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -43,17 +43,15 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
div.appendChild(container); div.appendChild(container);
class MyShape extends mxCylinder { class MyShape extends CylinderShape {
defaultPos1 = 20; defaultPos1 = 20;
defaultPos2 = 60; defaultPos2 = 60;
getLabelBounds(rect) { getLabelBounds(rect) {
const pos1 = const pos1 = utils.getValue(this.style, 'pos1', this.defaultPos1) * this.scale;
mxUtils.getValue(this.style, 'pos1', this.defaultPos1) * this.scale; const pos2 = utils.getValue(this.style, 'pos2', this.defaultPos2) * this.scale;
const pos2 = return new Rectangle(
mxUtils.getValue(this.style, 'pos2', this.defaultPos2) * this.scale;
return new mxRectangle(
rect.x, rect.x,
rect.y + pos1, rect.y + pos1,
rect.width, rect.width,
@ -62,8 +60,8 @@ const Template = ({ label, ...args }) => {
} }
redrawPath(path, x, y, w, h, isForeground) { redrawPath(path, x, y, w, h, isForeground) {
const pos1 = mxUtils.getValue(this.style, 'pos1', this.defaultPos1); const pos1 = utils.getValue(this.style, 'pos1', this.defaultPos1);
const pos2 = mxUtils.getValue(this.style, 'pos2', this.defaultPos2); const pos2 = utils.getValue(this.style, 'pos2', this.defaultPos2);
if (isForeground) { if (isForeground) {
if (pos1 < h) { if (pos1 < h) {
@ -80,9 +78,9 @@ const Template = ({ label, ...args }) => {
} }
} }
} }
mxCellRenderer.registerShape('myShape', MyShape); CellRenderer.registerShape('myShape', MyShape);
class MyCustomVertexHandler extends mxVertexHandler { class MyCustomVertexHandler extends VertexHandler {
livePreview = true; livePreview = true;
rotationEnabled = true; rotationEnabled = true;
@ -90,19 +88,15 @@ const Template = ({ label, ...args }) => {
createCustomHandles() { createCustomHandles() {
if (this.state.style.shape === 'myShape') { if (this.state.style.shape === 'myShape') {
// Implements the handle for the first divider // Implements the handle for the first divider
const firstHandle = new mxHandle(this.state); const firstHandle = new VertexHandle(this.state);
firstHandle.getPosition = function(bounds) { firstHandle.getPosition = function (bounds) {
const pos2 = Math.max( const pos2 = Math.max(
0, 0,
Math.min( Math.min(
bounds.height, bounds.height,
parseFloat( parseFloat(
mxUtils.getValue( utils.getValue(this.state.style, 'pos2', MyShape.prototype.defaultPos2)
this.state.style,
'pos2',
MyShape.prototype.defaultPos2
)
) )
) )
); );
@ -111,29 +105,21 @@ const Template = ({ label, ...args }) => {
Math.min( Math.min(
pos2, pos2,
parseFloat( parseFloat(
mxUtils.getValue( utils.getValue(this.state.style, 'pos1', MyShape.prototype.defaultPos1)
this.state.style,
'pos1',
MyShape.prototype.defaultPos1
)
) )
) )
); );
return new mxPoint(bounds.getCenterX(), bounds.y + pos1); return new Point(bounds.getCenterX(), bounds.y + pos1);
}; };
firstHandle.setPosition = function(bounds, pt) { firstHandle.setPosition = function (bounds, pt) {
const pos2 = Math.max( const pos2 = Math.max(
0, 0,
Math.min( Math.min(
bounds.height, bounds.height,
parseFloat( parseFloat(
mxUtils.getValue( utils.getValue(this.state.style, 'pos2', MyShape.prototype.defaultPos2)
this.state.style,
'pos2',
MyShape.prototype.defaultPos2
)
) )
) )
); );
@ -143,26 +129,22 @@ const Template = ({ label, ...args }) => {
); );
}; };
firstHandle.execute = function() { firstHandle.execute = function () {
this.copyStyle('pos1'); this.copyStyle('pos1');
}; };
firstHandle.ignoreGrid = true; firstHandle.ignoreGrid = true;
// Implements the handle for the second divider // Implements the handle for the second divider
const secondHandle = new mxHandle(this.state); const secondHandle = new VertexHandle(this.state);
secondHandle.getPosition = function(bounds) { secondHandle.getPosition = function (bounds) {
const pos1 = Math.max( const pos1 = Math.max(
0, 0,
Math.min( Math.min(
bounds.height, bounds.height,
parseFloat( parseFloat(
mxUtils.getValue( utils.getValue(this.state.style, 'pos1', MyShape.prototype.defaultPos1)
this.state.style,
'pos1',
MyShape.prototype.defaultPos1
)
) )
) )
); );
@ -171,29 +153,21 @@ const Template = ({ label, ...args }) => {
Math.min( Math.min(
bounds.height, bounds.height,
parseFloat( parseFloat(
mxUtils.getValue( utils.getValue(this.state.style, 'pos2', MyShape.prototype.defaultPos2)
this.state.style,
'pos2',
MyShape.prototype.defaultPos2
)
) )
) )
); );
return new mxPoint(bounds.getCenterX(), bounds.y + pos2); return new Point(bounds.getCenterX(), bounds.y + pos2);
}; };
secondHandle.setPosition = function(bounds, pt) { secondHandle.setPosition = function (bounds, pt) {
const pos1 = Math.max( const pos1 = Math.max(
0, 0,
Math.min( Math.min(
bounds.height, bounds.height,
parseFloat( parseFloat(
mxUtils.getValue( utils.getValue(this.state.style, 'pos1', MyShape.prototype.defaultPos1)
this.state.style,
'pos1',
MyShape.prototype.defaultPos1
)
) )
) )
); );
@ -203,7 +177,7 @@ const Template = ({ label, ...args }) => {
); );
}; };
secondHandle.execute = function() { secondHandle.execute = function () {
this.copyStyle('pos2'); this.copyStyle('pos2');
}; };
@ -216,15 +190,14 @@ const Template = ({ label, ...args }) => {
} }
} }
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
createVertexHandler(state) { createVertexHandler(state) {
return new MyCustomVertexHandler(state); return new MyCustomVertexHandler(state);
} }
} }
// Disables the built-in context menu // Disables the built-in context menu
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new MyCustomGraph(container); const graph = new MyCustomGraph(container);
@ -234,8 +207,7 @@ const Template = ({ label, ...args }) => {
graph.centerZoom = false; graph.centerZoom = false;
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -263,17 +235,17 @@ const Template = ({ label, ...args }) => {
div.appendChild(buttons); div.appendChild(buttons);
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('+', function() { mxDomHelpers.button('+', function () {
graph.zoomIn(); graph.zoomIn();
}) })
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('-', function() { mxDomHelpers.button('-', function () {
graph.zoomOut(); graph.zoomOut();
}) })
); );
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,8 +1,8 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
import { popup } from '@mxgraph/core/src/util/gui/mxWindow'; import { popup } from '@maxgraph/core/util/gui/mxWindow';
import { getPrettyXml } from '@mxgraph/core/src/util/XmlUtils'; import { getPrettyXml } from '@maxgraph/core/util/XmlUtils';
export default { export default {
title: 'Connections/HelloPort', title: 'Connections/HelloPort',
@ -10,21 +10,21 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxRubberband, Rubberband,
mxEdgeStyle, EdgeStyle,
mxPoint, Point,
mxConstants, Constants,
mxDomHelpers, mxDomHelpers,
mxClient mxClient,
} = mxgraph; } = maxgraph;
mxClient.setImageBasePath('/images'); mxClient.setImageBasePath('/images');
@ -40,17 +40,17 @@ const Template = ({ label, ...args }) => {
div.appendChild(container); div.appendChild(container);
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setConnectable(true); graph.setConnectable(true);
graph.setTooltips(true); graph.setTooltips(true);
// Sets the default edge style // Sets the default edge style
const style = graph.getStylesheet().getDefaultEdgeStyle(); const style = graph.getStylesheet().getDefaultEdgeStyle();
style.edge = mxEdgeStyle.ElbowConnector; style.edge = EdgeStyle.ElbowConnector;
// Ports are not used as terminals for edges, they are // Ports are not used as terminals for edges, they are
// only used to compute the graphical connection point // only used to compute the graphical connection point
graph.isPort = function(cell) { graph.isPort = function (cell) {
const geo = this.getCellGeometry(cell); const geo = this.getCellGeometry(cell);
return geo != null ? geo.relative : false; return geo != null ? geo.relative : false;
@ -58,26 +58,23 @@ const Template = ({ label, ...args }) => {
// Implements a tooltip that shows the actual // Implements a tooltip that shows the actual
// source and target of an edge // source and target of an edge
graph.getTooltipForCell = function(cell) { graph.getTooltipForCell = function (cell) {
if (cell.isEdge()) { if (cell.isEdge()) {
return `${this.convertValueToString( return `${this.convertValueToString(
cell.getTerminal(true) cell.getTerminal(true)
)} => ${this.convertValueToString( )} => ${this.convertValueToString(cell.getTerminal(false))}`;
cell.getTerminal(false)
)}`;
} }
return mxGraph.prototype.getTooltipForCell.apply(this, arguments); return Graph.prototype.getTooltipForCell.apply(this, arguments);
}; };
// Removes the folding icon and disables any folding // Removes the folding icon and disables any folding
graph.isCellFoldable = function(cell) { graph.isCellFoldable = function (cell) {
return false; return false;
}; };
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -89,10 +86,10 @@ const Template = ({ label, ...args }) => {
const v1 = graph.insertVertex(parent, null, 'Hello', 20, 80, 80, 30); const v1 = graph.insertVertex(parent, null, 'Hello', 20, 80, 80, 30);
v1.setConnectable(false); v1.setConnectable(false);
const v11 = graph.insertVertex(v1, null, '', 1, 1, 10, 10); const v11 = graph.insertVertex(v1, null, '', 1, 1, 10, 10);
v11.geometry.offset = new mxPoint(-5, -5); v11.geometry.offset = new Point(-5, -5);
v11.geometry.relative = true; v11.geometry.relative = true;
const v12 = graph.insertVertex(v1, null, '', 1, 0, 10, 10); const v12 = graph.insertVertex(v1, null, '', 1, 0, 10, 10);
v12.geometry.offset = new mxPoint(-5, -5); v12.geometry.offset = new Point(-5, -5);
v12.geometry.relative = true; v12.geometry.relative = true;
const v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30); const v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
const v3 = graph.insertVertex(parent, null, 'World2', 200, 20, 80, 30); const v3 = graph.insertVertex(parent, null, 'World2', 200, 20, 80, 30);
@ -106,7 +103,7 @@ const Template = ({ label, ...args }) => {
const controller = document.createElement('div'); const controller = document.createElement('div');
div.appendChild(controller); div.appendChild(controller);
const button = mxDomHelpers.button('View XML', function() { const button = mxDomHelpers.button('View XML', function () {
const encoder = new mxCodec(); const encoder = new mxCodec();
const node = encoder.encode(graph.getModel()); const node = encoder.encode(graph.getModel());
popup(getPrettyXml(node), true); popup(getPrettyXml(node), true);
@ -115,6 +112,6 @@ const Template = ({ label, ...args }) => {
controller.appendChild(button); controller.appendChild(button);
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -18,8 +18,8 @@ export default {
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { mxGraph, mxEvent, mxRubberband } = mxgraph; const { Graph, InternalEvent, Rubberband } = maxgraph;
console.log(maxgraph, Graph);
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
container.style.overflow = 'hidden'; container.style.overflow = 'hidden';
@ -28,11 +28,11 @@ const Template = ({ label, ...args }) => {
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
container.style.cursor = 'default'; container.style.cursor = 'default';
if (!args.contextMenu) mxEvent.disableContextMenu(container); if (!args.contextMenu) InternalEvent.disableContextMenu(container);
const graph = new mxGraph(container); const graph = new Graph(container);
if (args.rubberBand) new mxRubberband(graph); if (args.rubberBand) new Rubberband(graph);
const parent = graph.getDefaultParent(); const parent = graph.getDefaultParent();

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,26 +8,26 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxDomUtils, mxDomUtils,
mxFastOrganicLayout, mxFastOrganicLayout,
mxHierarchicalLayout, mxHierarchicalLayout,
mxPerimeter, Perimeter,
mxEvent, InternalEvent,
mxRubberband, Rubberband,
mxConstants Constants,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -41,15 +41,14 @@ const Template = ({ label, ...args }) => {
div.appendChild(container); div.appendChild(container);
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Adds rubberband selection // Adds rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Changes the default vertex style in-place // Changes the default vertex style in-place
let style = graph.getStylesheet().getDefaultVertexStyle(); let style = graph.getStylesheet().getDefaultVertexStyle();
style.perimiter = mxPerimeter.RectanglePerimeter; style.perimiter = Perimeter.RectanglePerimeter;
style.gradientColor = 'white'; style.gradientColor = 'white';
style.perimeterSpacing = 6; style.perimeterSpacing = 6;
style.rounded = true; style.rounded = true;
@ -72,7 +71,7 @@ const Template = ({ label, ...args }) => {
// Adds a button to execute the layout // Adds a button to execute the layout
let button = document.createElement('button'); let button = document.createElement('button');
mxDomUtils.write(button, 'Hierarchical'); mxDomUtils.write(button, 'Hierarchical');
mxEvent.addListener(button, 'click', function(evt) { InternalEvent.addListener(button, 'click', function (evt) {
layout.execute(parent); layout.execute(parent);
}); });
buttons.appendChild(button); buttons.appendChild(button);
@ -81,7 +80,7 @@ const Template = ({ label, ...args }) => {
button = document.createElement('button'); button = document.createElement('button');
mxDomUtils.write(button, 'Organic'); mxDomUtils.write(button, 'Organic');
mxEvent.addListener(button, 'click', function(evt) { InternalEvent.addListener(button, 'click', function (evt) {
organic.execute(parent); organic.execute(parent);
}); });
@ -122,6 +121,6 @@ const Template = ({ label, ...args }) => {
} }
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,21 +8,21 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxEvent, InternalEvent,
mxRubberband, Rubberband,
mxImage, ImageBox,
mxRectangle, Rectangle,
mxUtils, utils,
mxConnectionHandler ConnectionHandler,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -34,11 +34,7 @@ const Template = ({ label, ...args }) => {
// Defines an icon for creating new connections in the connection handler. // Defines an icon for creating new connections in the connection handler.
// This will automatically disable the highlighting of the source vertex. // This will automatically disable the highlighting of the source vertex.
mxConnectionHandler.prototype.connectImage = new mxImage( ConnectionHandler.prototype.connectImage = new ImageBox('images/connector.gif', 16, 16);
'images/connector.gif',
16,
16
);
// Defines a new class for all icons // Defines a new class for all icons
class mxIconSet { class mxIconSet {
@ -47,7 +43,7 @@ const Template = ({ label, ...args }) => {
const { graph } = state.view; const { graph } = state.view;
// Icon1 // Icon1
let img = mxUtils.createImage('images/copy.png'); let img = utils.createImage('images/copy.png');
img.setAttribute('title', 'Duplicate'); img.setAttribute('title', 'Duplicate');
Object.assign(img.style, { Object.assign(img.style, {
cursor: 'pointer', cursor: 'pointer',
@ -58,10 +54,10 @@ const Template = ({ label, ...args }) => {
top: `${state.y + state.height}px`, top: `${state.y + state.height}px`,
}); });
mxEvent.addGestureListeners(img, evt => { InternalEvent.addGestureListeners(img, (evt) => {
const s = graph.gridSize; const s = graph.gridSize;
graph.setSelectionCells(graph.moveCells([state.cell], s, s, true)); graph.setSelectionCells(graph.moveCells([state.cell], s, s, true));
mxEvent.consume(evt); InternalEvent.consume(evt);
this.destroy(); this.destroy();
}); });
@ -69,7 +65,7 @@ const Template = ({ label, ...args }) => {
this.images.push(img); this.images.push(img);
// Delete // Delete
img = mxUtils.createImage('images/delete2.png'); img = utils.createImage('images/delete2.png');
img.setAttribute('title', 'Delete'); img.setAttribute('title', 'Delete');
Object.assign(img.style, { Object.assign(img.style, {
cursor: 'pointer', cursor: 'pointer',
@ -80,14 +76,14 @@ const Template = ({ label, ...args }) => {
top: `${state.y - 16}px`, top: `${state.y - 16}px`,
}); });
mxEvent.addGestureListeners(img, evt => { InternalEvent.addGestureListeners(img, (evt) => {
// Disables dragging the image // Disables dragging the image
mxEvent.consume(evt); InternalEvent.consume(evt);
}); });
mxEvent.addListener(img, 'click', evt => { InternalEvent.addListener(img, 'click', (evt) => {
graph.removeCells([state.cell]); graph.removeCells([state.cell]);
mxEvent.consume(evt); InternalEvent.consume(evt);
this.destroy(); this.destroy();
}); });
@ -106,12 +102,11 @@ const Template = ({ label, ...args }) => {
} }
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setConnectable(true); graph.setConnectable(true);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Defines the tolerance before removing the icons // Defines the tolerance before removing the icons
const ICON_TOLERANCE = 20; const ICON_TOLERANCE = 20;
@ -135,13 +130,13 @@ const Template = ({ label, ...args }) => {
(me.getState() === this.currentState || me.getState() == null) (me.getState() === this.currentState || me.getState() == null)
) { ) {
const tol = ICON_TOLERANCE; const tol = ICON_TOLERANCE;
const tmp = new mxRectangle( const tmp = new Rectangle(
me.getGraphX() - tol, me.getGraphX() - tol,
me.getGraphY() - tol, me.getGraphY() - tol,
2 * tol, 2 * tol,
2 * tol 2 * tol
); );
if (mxUtils.intersects(tmp, this.currentState)) { if (utils.intersects(tmp, this.currentState)) {
return; return;
} }
} }
@ -149,10 +144,7 @@ const Template = ({ label, ...args }) => {
let tmp = graph.view.getState(me.getCell()); let tmp = graph.view.getState(me.getCell());
// Ignore everything but vertices // Ignore everything but vertices
if ( if (graph.isMouseDown || (tmp != null && !tmp.cell.isVertex())) {
graph.isMouseDown ||
(tmp != null && !tmp.cell.isVertex())
) {
tmp = null; tmp = null;
} }
@ -210,6 +202,6 @@ const Template = ({ label, ...args }) => {
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,18 +8,13 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Constants, Rubberband, CloneUtils } = maxgraph;
mxGraph,
mxConstants,
mxRubberband,
mxCloneUtils
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -30,7 +25,7 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
function updateStyle(state, hover) { function updateStyle(state, hover) {
if (hover) { if (hover) {
@ -42,9 +37,7 @@ const Template = ({ label, ...args }) => {
// once it is set, whereas the above overrides the default value // once it is set, whereas the above overrides the default value
state.style.rounded = hover ? '1' : '0'; state.style.rounded = hover ? '1' : '0';
state.style.strokeWidth = hover ? '4' : '1'; state.style.strokeWidth = hover ? '4' : '1';
state.style.fontStyle = hover state.style.fontStyle = hover ? Constants.FONT_BOLD : '0';
? mxConstants.FONT_BOLD
: '0';
} }
// Changes fill color to red on mouseover // Changes fill color to red on mouseover
@ -65,10 +58,7 @@ const Template = ({ label, ...args }) => {
let tmp = graph.view.getState(me.getCell()); let tmp = graph.view.getState(me.getCell());
// Ignores everything but vertices // Ignores everything but vertices
if ( if (graph.isMouseDown || (tmp != null && !tmp.cell.isVertex())) {
graph.isMouseDown ||
(tmp != null && !tmp.cell.isVertex())
) {
tmp = null; tmp = null;
} }
@ -88,7 +78,7 @@ const Template = ({ label, ...args }) => {
dragEnter(evt, state) { dragEnter(evt, state) {
if (state != null) { if (state != null) {
this.previousStyle = state.style; this.previousStyle = state.style;
state.style = mxCloneUtils.clone(state.style); state.style = CloneUtils.clone(state.style);
updateStyle(state, true); updateStyle(state, true);
state.shape.apply(state); state.shape.apply(state);
state.shape.redraw(); state.shape.redraw();
@ -115,8 +105,7 @@ const Template = ({ label, ...args }) => {
}); });
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -134,6 +123,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,23 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Icon_Images/Images', title: 'Icon_Images/Images',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, CloneUtils, ImageBox, Rectangle, Constants, Perimeter } = maxgraph;
mxGraph,
mxCloneUtils,
mxImage,
mxRectangle,
mxConstants,
mxPerimeter
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -28,16 +21,14 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Sets a background image and restricts child movement to its bounds // Sets a background image and restricts child movement to its bounds
graph.setBackgroundImage( graph.setBackgroundImage(new ImageBox('images/gradient_background.jpg', 360, 200));
new mxImage('images/gradient_background.jpg', 360, 200) graph.maximumGraphBounds = new Rectangle(0, 0, 360, 200);
);
graph.maximumGraphBounds = new mxRectangle(0, 0, 360, 200);
// Resizes the container but never make it bigger than the background // Resizes the container but never make it bigger than the background
graph.minimumContainerSize = new mxRectangle(0, 0, 360, 200); graph.minimumContainerSize = new Rectangle(0, 0, 360, 200);
graph.setResizeContainer(true); graph.setResizeContainer(true);
// Disables basic selection and cell handling // Disables basic selection and cell handling
@ -99,19 +90,19 @@ const Template = ({ label, ...args }) => {
function configureStylesheet(graph) { function configureStylesheet(graph) {
let style = {}; let style = {};
style.shape = mxConstants.SHAPE_IMAGE; style.shape = Constants.SHAPE_IMAGE;
style.perimiter = mxPerimeter.RectanglePerimeter; style.perimiter = Perimeter.RectanglePerimeter;
style.image = 'images/icons48/keys.png'; style.image = 'images/icons48/keys.png';
style.fontColor = '#FFFFFF'; style.fontColor = '#FFFFFF';
graph.getStylesheet().putCellStyle('image', style); graph.getStylesheet().putCellStyle('image', style);
style = mxCloneUtils.clone(style); style = CloneUtils.clone(style);
style.shape = mxConstants.SHAPE_LABEL; style.shape = Constants.SHAPE_LABEL;
style.strokeColor = '#000000'; style.strokeColor = '#000000';
style.align = mxConstants.ALIGN_CENTER; style.align = Constants.ALIGN_CENTER;
style.verticalAlign = mxConstants.ALIGN_TOP; style.verticalAlign = Constants.ALIGN_TOP;
style.imageAlign = mxConstants.ALIGN_CENTER; style.imageAlign = Constants.ALIGN_CENTER;
style.imageVerticalAlign = mxConstants.ALIGN_TOP; style.imageVerticalAlign = Constants.ALIGN_TOP;
style.image = 'images/icons48/gear.png'; style.image = 'images/icons48/gear.png';
style.imageWidth = '48'; style.imageWidth = '48';
style.imageHeight = '48'; style.imageHeight = '48';
@ -119,31 +110,31 @@ const Template = ({ label, ...args }) => {
style.spacing = '8'; style.spacing = '8';
graph.getStylesheet().putCellStyle('bottom', style); graph.getStylesheet().putCellStyle('bottom', style);
style = mxCloneUtils.clone(style); style = CloneUtils.clone(style);
style.imageVerticalAlign = mxConstants.ALIGN_BOTTOM; style.imageVerticalAlign = Constants.ALIGN_BOTTOM;
style.image = 'images/icons48/server.png'; style.image = 'images/icons48/server.png';
delete style.spacingTop; delete style.spacingTop;
graph.getStylesheet().putCellStyle('top', style); graph.getStylesheet().putCellStyle('top', style);
style = mxCloneUtils.clone(style); style = CloneUtils.clone(style);
style.align = mxConstants.ALIGN_LEFT; style.align = Constants.ALIGN_LEFT;
style.imageAlign = mxConstants.ALIGN_LEFT; style.imageAlign = Constants.ALIGN_LEFT;
style.verticalAlign = mxConstants.ALIGN_MIDDLE; style.verticalAlign = Constants.ALIGN_MIDDLE;
style.imageVerticalAlign = mxConstants.ALIGN_MIDDLE; style.imageVerticalAlign = Constants.ALIGN_MIDDLE;
style.image = 'images/icons48/earth.png'; style.image = 'images/icons48/earth.png';
style.spacingLeft = '55'; style.spacingLeft = '55';
style.spacing = '4'; style.spacing = '4';
graph.getStylesheet().putCellStyle('right', style); graph.getStylesheet().putCellStyle('right', style);
style = mxCloneUtils.clone(style); style = CloneUtils.clone(style);
style.align = mxConstants.ALIGN_RIGHT; style.align = Constants.ALIGN_RIGHT;
style.imageAlign = mxConstants.ALIGN_RIGHT; style.imageAlign = Constants.ALIGN_RIGHT;
delete style.spacingLeft; delete style.spacingLeft;
style.spacingRight = '55'; style.spacingRight = '55';
graph.getStylesheet().putCellStyle('left', style); graph.getStylesheet().putCellStyle('left', style);
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,21 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Icon_Images/Indicators', title: 'Icon_Images/Indicators',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, EdgeStyle, Constants, mxKeyHandler } = maxgraph;
mxGraph,
mxEdgeStyle,
mxConstants,
mxKeyHandler
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -26,7 +21,7 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setConnectable(true); graph.setConnectable(true);
new mxKeyHandler(graph); new mxKeyHandler(graph);
@ -50,8 +45,8 @@ const Template = ({ label, ...args }) => {
// Creates a style with an indicator // Creates a style with an indicator
style = graph.getStylesheet().getDefaultEdgeStyle(); style = graph.getStylesheet().getDefaultEdgeStyle();
style.edge = mxEdgeStyle.ElbowConnector; style.edge = EdgeStyle.ElbowConnector;
style.elbow = mxConstants.ELBOW_VERTICAL; style.elbow = Constants.ELBOW_VERTICAL;
style.rounded = true; style.rounded = true;
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
@ -88,6 +83,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,27 +1,27 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { popup } from '@mxgraph/core/src/util/gui/mxWindow'; import { popup } from '@maxgraph/core/util/gui/mxWindow';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Xml_Json/JsonData', title: 'Xml_Json/JsonData',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxObjectCodec, mxObjectCodec,
mxDomHelpers, mxDomHelpers,
mxCodecRegistry, mxCodecRegistry,
mxEvent, InternalEvent,
mxClient, mxClient,
mxCodec, mxCodec,
mxDomUtils, mxDomUtils,
mxUtils utils,
} = mxgraph; } = maxgraph;
mxClient.setImageBasePath('/images'); mxClient.setImageBasePath('/images');
@ -41,12 +41,12 @@ const Template = ({ label, ...args }) => {
this.value = value; this.value = value;
} }
const codec = new mxObjectCodec(new CustomData()); const codec = new mxObjectCodec(new CustomData());
codec.encode = function(enc, obj) { codec.encode = function (enc, obj) {
const node = enc.document.createElement('CustomData'); const node = enc.document.createElement('CustomData');
mxDomUtils.setTextContent(node, JSON.stringify(obj)); mxDomUtils.setTextContent(node, JSON.stringify(obj));
return node; return node;
}; };
codec.decode = function(dec, node, into) { codec.decode = function (dec, node, into) {
const obj = JSON.parse(mxDomUtils.getTextContent(node)); const obj = JSON.parse(mxDomUtils.getTextContent(node));
obj.constructor = CustomData; obj.constructor = CustomData;
@ -55,15 +55,13 @@ const Template = ({ label, ...args }) => {
mxCodecRegistry.register(codec); mxCodecRegistry.register(codec);
// Disables the built-in context menu // Disables the built-in context menu
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new RubberBand(graph);
new RubberBand(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -86,14 +84,14 @@ const Template = ({ label, ...args }) => {
div.appendChild(buttons); div.appendChild(buttons);
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Show JSON', function() { mxDomHelpers.button('Show JSON', function () {
const encoder = new mxCodec(); const encoder = new mxCodec();
const node = encoder.encode(graph.getModel()); const node = encoder.encode(graph.getModel());
popup(mxUtils.getXml(node), true); popup(utils.getXml(node), true);
}) })
); );
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,18 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Labels/LabelPosition', title: 'Labels/LabelPosition',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph } = maxgraph;
mxGraph
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -23,7 +21,7 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -36,7 +34,7 @@ const Template = ({ label, ...args }) => {
// label positions using the label position styles. Vertical // label positions using the label position styles. Vertical
// and horizontal label position styles can be combined. // and horizontal label position styles can be combined.
// Note: Alternatively, vertex labels can be set be overriding // Note: Alternatively, vertex labels can be set be overriding
// mxCellRenderer.getLabelBounds. // CellRenderer.getLabelBounds.
graph.getModel().beginUpdate(); graph.getModel().beginUpdate();
try { try {
graph.insertVertex( graph.insertVertex(
@ -85,6 +83,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,19 +8,13 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Rubberband, mxKeyHandler, Constants, Rectangle } = maxgraph;
mxGraph,
mxRubberband,
mxKeyHandler,
mxConstants,
mxRectangle
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -31,13 +25,12 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setTooltips(true); graph.setTooltips(true);
graph.htmlLabels = true; graph.htmlLabels = true;
graph.vertexLabelsMovable = true; graph.vertexLabelsMovable = true;
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
new mxKeyHandler(graph); new mxKeyHandler(graph);
@ -48,32 +41,30 @@ const Template = ({ label, ...args }) => {
graph.autoSizeCellsOnAdd = true; graph.autoSizeCellsOnAdd = true;
// Allows moving of relative cells // Allows moving of relative cells
graph.isCellLocked = function(cell) { graph.isCellLocked = function (cell) {
return this.isCellsLocked(); return this.isCellsLocked();
}; };
graph.isCellResizable = function(cell) { graph.isCellResizable = function (cell) {
const geo = cell.getGeometry(); const geo = cell.getGeometry();
return geo == null || !geo.relative; return geo == null || !geo.relative;
}; };
// Truncates the label to the size of the vertex // Truncates the label to the size of the vertex
graph.getLabel = function(cell) { graph.getLabel = function (cell) {
const label = this.labelsVisible ? this.convertValueToString(cell) : ''; const label = this.labelsVisible ? this.convertValueToString(cell) : '';
const geometry = cell.getGeometry(); const geometry = cell.getGeometry();
if ( if (
!cell.isCollapsed() && !cell.isCollapsed() &&
geometry != null && geometry != null &&
(geometry.offset == null || (geometry.offset == null || (geometry.offset.x == 0 && geometry.offset.y == 0)) &&
(geometry.offset.x == 0 && geometry.offset.y == 0)) &&
cell.isVertex() && cell.isVertex() &&
geometry.width >= 2 geometry.width >= 2
) { ) {
const style = this.getCellStyle(cell); const style = this.getCellStyle(cell);
const fontSize = const fontSize = style.fontSize || Constants.DEFAULT_FONTSIZE;
style.fontSize || mxConstants.DEFAULT_FONTSIZE;
const max = geometry.width / (fontSize * 0.625); const max = geometry.width / (fontSize * 0.625);
if (max < label.length) { if (max < label.length) {
@ -85,19 +76,18 @@ const Template = ({ label, ...args }) => {
}; };
// Enables wrapping for vertex labels // Enables wrapping for vertex labels
graph.isWrapping = function(cell) { graph.isWrapping = function (cell) {
return cell.isCollapsed(); return cell.isCollapsed();
}; };
// Enables clipping of vertex labels if no offset is defined // Enables clipping of vertex labels if no offset is defined
graph.isLabelClipped = function(cell) { graph.isLabelClipped = function (cell) {
const geometry = cell.getGeometry(); const geometry = cell.getGeometry();
return ( return (
geometry != null && geometry != null &&
!geometry.relative && !geometry.relative &&
(geometry.offset == null || (geometry.offset == null || (geometry.offset.x == 0 && geometry.offset.y == 0))
(geometry.offset.x == 0 && geometry.offset.y == 0))
); );
}; };
@ -108,39 +98,11 @@ const Template = ({ label, ...args }) => {
// Adds cells to the model in a single step // Adds cells to the model in a single step
graph.getModel().beginUpdate(); graph.getModel().beginUpdate();
try { try {
const v1 = graph.insertVertex( const v1 = graph.insertVertex(parent, null, 'vertexLabelsMovable', 20, 20, 80, 30);
parent,
null,
'vertexLabelsMovable',
20,
20,
80,
30
);
// Places sublabels inside the vertex // Places sublabels inside the vertex
const label11 = graph.insertVertex( const label11 = graph.insertVertex(v1, null, 'Label1', 0.5, 1, 0, 0, null, true);
v1, const label12 = graph.insertVertex(v1, null, 'Label2', 0.5, 0, 0, 0, null, true);
null,
'Label1',
0.5,
1,
0,
0,
null,
true
);
const label12 = graph.insertVertex(
v1,
null,
'Label2',
0.5,
0,
0,
0,
null,
true
);
const v2 = graph.insertVertex( const v2 = graph.insertVertex(
parent, parent,
@ -151,38 +113,18 @@ const Template = ({ label, ...args }) => {
80, 80,
30 30
); );
v2.geometry.alternateBounds = new mxRectangle(0, 0, 80, 30); v2.geometry.alternateBounds = new Rectangle(0, 0, 80, 30);
const e1 = graph.insertEdge(parent, null, 'edgeLabelsMovable', v1, v2); const e1 = graph.insertEdge(parent, null, 'edgeLabelsMovable', v1, v2);
// Places sublabels inside the vertex // Places sublabels inside the vertex
const label21 = graph.insertVertex( const label21 = graph.insertVertex(v2, null, 'Label1', 0.5, 1, 0, 0, null, true);
v2, const label22 = graph.insertVertex(v2, null, 'Label2', 0.5, 0, 0, 0, null, true);
null,
'Label1',
0.5,
1,
0,
0,
null,
true
);
const label22 = graph.insertVertex(
v2,
null,
'Label2',
0.5,
0,
0,
0,
null,
true
);
} finally { } finally {
// Updates the display // Updates the display
graph.getModel().endUpdate(); graph.getModel().endUpdate();
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,22 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Layouts/Layers', title: 'Layouts/Layers',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, mxDomHelpers, Cell, GraphModel, Point } = maxgraph;
mxGraph,
mxDomHelpers,
mxCell,
mxGraphModel,
mxPoint
} = mxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -31,13 +25,13 @@ const Template = ({ label, ...args }) => {
// Creates the graph inside the given container using a model // Creates the graph inside the given container using a model
// with a custom root and two layers. Layers can also be added // with a custom root and two layers. Layers can also be added
// dynamically using let layer = model.add(root, new mxCell()). // dynamically using let layer = model.add(root, new Cell()).
const root = new mxCell(); const root = new Cell();
const layer0 = root.insert(new mxCell()); const layer0 = root.insert(new Cell());
const layer1 = root.insert(new mxCell()); const layer1 = root.insert(new Cell());
const model = new mxGraphModel(root); const model = new GraphModel(root);
const graph = new mxGraph(container, model); const graph = new Graph(container, model);
// Disables basic selection and cell handling // Disables basic selection and cell handling
graph.setEnabled(false); graph.setEnabled(false);
@ -70,17 +64,10 @@ const Template = ({ label, ...args }) => {
'fillColor=#C0C0C0' 'fillColor=#C0C0C0'
); );
const v3 = graph.insertVertex(layer0, null, 'World!', 110, 150, 80, 30); const v3 = graph.insertVertex(layer0, null, 'World!', 110, 150, 80, 30);
const e1 = graph.insertEdge( const e1 = graph.insertEdge(layer1, null, '', v1, v3, 'strokeColor=#0C0C0C');
layer1, e1.geometry.points = [new Point(60, 165)];
null,
'',
v1,
v3,
'strokeColor=#0C0C0C'
);
e1.geometry.points = [new mxPoint(60, 165)];
const e2 = graph.insertEdge(layer0, null, '', v2, v3); const e2 = graph.insertEdge(layer0, null, '', v2, v3);
e2.geometry.points = [new mxPoint(240, 165)]; e2.geometry.points = [new Point(240, 165)];
const e3 = graph.insertEdge( const e3 = graph.insertEdge(
layer0, layer0,
null, null,
@ -89,7 +76,7 @@ const Template = ({ label, ...args }) => {
v2, v2,
'edgeStyle=topToBottomEdgeStyle' 'edgeStyle=topToBottomEdgeStyle'
); );
e3.geometry.points = [new mxPoint(150, 30)]; e3.geometry.points = [new Point(150, 30)];
const e4 = graph.insertEdge( const e4 = graph.insertEdge(
layer1, layer1,
null, null,
@ -98,7 +85,7 @@ const Template = ({ label, ...args }) => {
v1, v1,
'strokeColor=#0C0C0C;edgeStyle=topToBottomEdgeStyle' 'strokeColor=#0C0C0C;edgeStyle=topToBottomEdgeStyle'
); );
e4.geometry.points = [new mxPoint(150, 40)]; e4.geometry.points = [new Point(150, 40)];
} finally { } finally {
// Updates the display // Updates the display
model.endUpdate(); model.endUpdate();
@ -108,18 +95,18 @@ const Template = ({ label, ...args }) => {
div.appendChild(buttons); div.appendChild(buttons);
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Layer 0', function() { mxDomHelpers.button('Layer 0', function () {
model.setVisible(layer0, !layer0.isVisible()); model.setVisible(layer0, !layer0.isVisible());
}) })
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Layer 1', function() { mxDomHelpers.button('Layer 1', function () {
model.setVisible(layer1, !layer1.isVisible()); model.setVisible(layer1, !layer1.isVisible());
}) })
); );
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,19 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Zoom_OffPage/LoD', title: 'Zoom_OffPage/LoD',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, mxDomHelpers } = maxgraph;
mxGraph,
mxDomHelpers
} = mxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -27,11 +24,11 @@ const Template = ({ label, ...args }) => {
div.appendChild(container); div.appendChild(container);
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.centerZoom = false; graph.centerZoom = false;
// Links level of detail to zoom level but can be independent of zoom // Links level of detail to zoom level but can be independent of zoom
const isVisible = function() { const isVisible = function () {
return this.lod == null || this.lod / 2 < graph.view.scale; return this.lod == null || this.lod / 2 < graph.view.scale;
}; };
@ -74,18 +71,18 @@ const Template = ({ label, ...args }) => {
div.appendChild(buttons); div.appendChild(buttons);
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('+', function() { mxDomHelpers.button('+', function () {
graph.zoomIn(); graph.zoomIn();
}) })
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('-', function() { mxDomHelpers.button('-', function () {
graph.zoomOut(); graph.zoomOut();
}) })
); );
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,25 +1,25 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Icon_Images/Markers', title: 'Icon_Images/Markers',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxEdgeHandler, EdgeHandler,
mxGraphHandler, GraphHandler,
mxCellRenderer, CellRenderer,
mxMarker, Marker,
mxCylinder, CylinderShape,
mxArrow, Arrow,
mxPoint Point,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -30,38 +30,27 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Enables guides // Enables guides
mxGraphHandler.prototype.guidesEnabled = true; GraphHandler.prototype.guidesEnabled = true;
mxEdgeHandler.prototype.snapToTerminals = true; EdgeHandler.prototype.snapToTerminals = true;
// Registers and defines the custom marker // Registers and defines the custom marker
mxMarker.addMarker('dash', function( Marker.addMarker(
canvas, 'dash',
shape, function (canvas, shape, type, pe, unitX, unitY, size, source, sw, filled) {
type, const nx = unitX * (size + sw + 1);
pe, const ny = unitY * (size + sw + 1);
unitX,
unitY,
size,
source,
sw,
filled
) {
const nx = unitX * (size + sw + 1);
const ny = unitY * (size + sw + 1);
return function() { return function () {
canvas.begin(); canvas.begin();
canvas.moveTo(pe.x - nx / 2 - ny / 2, pe.y - ny / 2 + nx / 2); canvas.moveTo(pe.x - nx / 2 - ny / 2, pe.y - ny / 2 + nx / 2);
canvas.lineTo( canvas.lineTo(pe.x + ny / 2 - (3 * nx) / 2, pe.y - (3 * ny) / 2 - nx / 2);
pe.x + ny / 2 - (3 * nx) / 2, canvas.stroke();
pe.y - (3 * ny) / 2 - nx / 2 };
); }
canvas.stroke(); );
};
});
// Defines custom message shape // Defines custom message shape
class MessageShape extends mxCylinder { class MessageShape extends CylinderShape {
redrawPath(path, x, y, w, h, isForeground) { redrawPath(path, x, y, w, h, isForeground) {
if (isForeground) { if (isForeground) {
path.moveTo(0, 0); path.moveTo(0, 0);
@ -76,10 +65,10 @@ const Template = ({ label, ...args }) => {
} }
} }
} }
mxCellRenderer.registerShape('message', MessageShape); CellRenderer.registerShape('message', MessageShape);
// Defines custom edge shape // Defines custom edge shape
class LinkShape extends mxArrow { class LinkShape extends Arrow {
paintEdgeShape(c, pts) { paintEdgeShape(c, pts) {
const width = 10; const width = 10;
@ -121,10 +110,10 @@ const Template = ({ label, ...args }) => {
c.stroke(); c.stroke();
} }
} }
mxCellRenderer.registerShape('link', LinkShape); CellRenderer.registerShape('link', LinkShape);
// Creates the graph // Creates the graph
const graph = new mxGraph(container); const graph = new Graph(container);
// Sets default styles // Sets default styles
let style = graph.getStylesheet().getDefaultVertexStyle(); let style = graph.getStylesheet().getDefaultVertexStyle();
@ -167,7 +156,7 @@ const Template = ({ label, ...args }) => {
14, 14,
'shape=message;labelBackgroundColor=#ffffff;labelPosition=left;spacingRight=2;align=right;fontStyle=0;' 'shape=message;labelBackgroundColor=#ffffff;labelPosition=left;spacingRight=2;align=right;fontStyle=0;'
); );
e11.geometry.offset = new mxPoint(-10, -7); e11.geometry.offset = new Point(-10, -7);
e11.geometry.relative = true; e11.geometry.relative = true;
e11.connectable = false; e11.connectable = false;
@ -215,6 +204,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,18 +8,13 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Perimeter, Constants, Rubberband } = maxgraph;
mxGraph,
mxPerimeter,
mxConstants,
mxRubberband
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -29,34 +24,33 @@ const Template = ({ label, ...args }) => {
container.style.background = 'url(/images/grid.gif)'; container.style.background = 'url(/images/grid.gif)';
container.style.cursor = 'default'; container.style.cursor = 'default';
mxConstants.SHADOWCOLOR = '#c0c0c0'; Constants.SHADOWCOLOR = '#c0c0c0';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// No size handles, please... // No size handles, please...
graph.setCellsResizable(false); graph.setCellsResizable(false);
// Makes all cells round with a white, bold label // Makes all cells round with a white, bold label
let style = graph.stylesheet.getDefaultVertexStyle(); let style = graph.stylesheet.getDefaultVertexStyle();
style.shape = mxConstants.SHAPE_ELLIPSE; style.shape = Constants.SHAPE_ELLIPSE;
style.perimiter = mxPerimeter.EllipsePerimeter; style.perimiter = Perimeter.EllipsePerimeter;
style.fontColor = 'white'; style.fontColor = 'white';
style.gradientColor = 'white'; style.gradientColor = 'white';
style.fontStyle = mxConstants.FONT_BOLD; style.fontStyle = Constants.FONT_BOLD;
style.fontSize = 14; style.fontSize = 14;
style.shadow = true; style.shadow = true;
// Makes all edge labels gray with a white background // Makes all edge labels gray with a white background
style = graph.stylesheet.getDefaultEdgeStyle(); style = graph.stylesheet.getDefaultEdgeStyle();
style.fontColor = 'gray'; style.fontColor = 'gray';
style.fontStyle = mxConstants.FONT_BOLD; style.fontStyle = Constants.FONT_BOLD;
style.fontColor = 'black'; style.fontColor = 'black';
style.strokeWidth = 2; style.strokeWidth = 2;
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -69,46 +63,10 @@ const Template = ({ label, ...args }) => {
graph.getModel().beginUpdate(); graph.getModel().beginUpdate();
try { try {
const a = graph.insertVertex( const a = graph.insertVertex(parent, 'a', 'A', 20, 20, w, h, 'fillColor=blue');
parent, const b = graph.insertVertex(parent, 'b', 'B', 20, 200, w, h, 'fillColor=blue');
'a', const c = graph.insertVertex(parent, 'c', 'C', 200, 20, w, h, 'fillColor=red');
'A', const d = graph.insertVertex(parent, 'd', 'D', 200, 200, w, h, 'fillColor=red');
20,
20,
w,
h,
'fillColor=blue'
);
const b = graph.insertVertex(
parent,
'b',
'B',
20,
200,
w,
h,
'fillColor=blue'
);
const c = graph.insertVertex(
parent,
'c',
'C',
200,
20,
w,
h,
'fillColor=red'
);
const d = graph.insertVertex(
parent,
'd',
'D',
200,
200,
w,
h,
'fillColor=red'
);
const ac = graph.insertEdge( const ac = graph.insertEdge(
parent, parent,
'ac', 'ac',
@ -139,7 +97,7 @@ const Template = ({ label, ...args }) => {
} }
// Creates the second graph model (without a container) // Creates the second graph model (without a container)
const graph2 = new mxGraph(); const graph2 = new Graph();
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -149,46 +107,10 @@ const Template = ({ label, ...args }) => {
// using custom ids for the vertices // using custom ids for the vertices
graph2.getModel().beginUpdate(); graph2.getModel().beginUpdate();
try { try {
const c = graph2.insertVertex( const c = graph2.insertVertex(parent2, 'c', 'C', 200, 20, w, h, 'fillColor=green');
parent2, const d = graph2.insertVertex(parent2, 'd', 'D', 200, 200, w, h, 'fillColor=green');
'c', const e = graph2.insertVertex(parent2, 'e', 'E', 400, 20, w, h, 'fillColor=green');
'C', const f = graph2.insertVertex(parent2, 'f', 'F', 400, 200, w, h, 'fillColor=green');
200,
20,
w,
h,
'fillColor=green'
);
const d = graph2.insertVertex(
parent2,
'd',
'D',
200,
200,
w,
h,
'fillColor=green'
);
const e = graph2.insertVertex(
parent2,
'e',
'E',
400,
20,
w,
h,
'fillColor=green'
);
const f = graph2.insertVertex(
parent2,
'f',
'F',
400,
200,
w,
h,
'fillColor=green'
);
const ce = graph2.insertEdge( const ce = graph2.insertEdge(
parent2, parent2,
'ce', 'ce',
@ -227,6 +149,6 @@ const Template = ({ label, ...args }) => {
graph.getModel().mergeChildren(parent2, parent /* , false */); graph.getModel().mergeChildren(parent2, parent /* , false */);
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,26 +1,26 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Misc/Monitor', title: 'Misc/Monitor',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxEdgeStyle, EdgeStyle,
mxDomHelpers, mxDomHelpers,
mxXmlUtils, mxXmlUtils,
mxPerimeter, Perimeter,
mxUtils, utils,
mxConstants, Constants,
mxCloneUtils, CloneUtils,
mxCodec mxCodec,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -33,50 +33,50 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
div.appendChild(container); div.appendChild(container);
mxConstants.SHADOWCOLOR = '#e0e0e0'; Constants.SHADOWCOLOR = '#e0e0e0';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = createGraph(container); const graph = createGraph(container);
// Creates a process display using the activity names as IDs to refer to the elements // Creates a process display using the activity names as IDs to refer to the elements
const xml = const xml =
'<Transactions><root><mxCell id="0"/><mxCell id="1" parent="0"/>' + '<Transactions><root><Cell id="0"/><Cell id="1" parent="0"/>' +
'<mxCell id="2" value="Claim Handling Process" style="swimlane" vertex="1" parent="1"><mxGeometry x="1" width="850" height="400" as="geometry"/></mxCell>' + '<Cell id="2" value="Claim Handling Process" style="swimlane" vertex="1" parent="1"><Geometry x="1" width="850" height="400" as="geometry"/></Cell>' +
'<mxCell id="3" value="Claim Manager" style="swimlane" vertex="1" parent="2"><mxGeometry x="30" width="820" height="200" as="geometry"/></mxCell>' + '<Cell id="3" value="Claim Manager" style="swimlane" vertex="1" parent="2"><Geometry x="30" width="820" height="200" as="geometry"/></Cell>' +
'<mxCell id="5" value="" style="start" vertex="1" parent="3"><mxGeometry x="40" y="85" width="30" height="30" as="geometry"/></mxCell>' + '<Cell id="5" value="" style="start" vertex="1" parent="3"><Geometry x="40" y="85" width="30" height="30" as="geometry"/></Cell>' +
'<mxCell id="AuthorizeClaim" value="Authorize&#xa;Claim" vertex="1" parent="3"><mxGeometry x="90" y="80" width="100" height="40" as="geometry"/></mxCell>' + '<Cell id="AuthorizeClaim" value="Authorize&#xa;Claim" vertex="1" parent="3"><Geometry x="90" y="80" width="100" height="40" as="geometry"/></Cell>' +
'<mxCell id="6" value="X" style="step" vertex="1" parent="3"><mxGeometry x="210" y="85" width="30" height="30" as="geometry"/></mxCell>' + '<Cell id="6" value="X" style="step" vertex="1" parent="3"><Geometry x="210" y="85" width="30" height="30" as="geometry"/></Cell>' +
'<mxCell id="ApproveClaim" value="Approve&#xa;Claim" vertex="1" parent="3"><mxGeometry x="260" y="80" width="100" height="40" as="geometry"/></mxCell>' + '<Cell id="ApproveClaim" value="Approve&#xa;Claim" vertex="1" parent="3"><Geometry x="260" y="80" width="100" height="40" as="geometry"/></Cell>' +
'<mxCell id="7" value="X" style="step" vertex="1" parent="3"><mxGeometry x="380" y="85" width="30" height="30" as="geometry"/></mxCell>' + '<Cell id="7" value="X" style="step" vertex="1" parent="3"><Geometry x="380" y="85" width="30" height="30" as="geometry"/></Cell>' +
'<mxCell id="8" value="" edge="1" parent="3" source="5" target="AuthorizeClaim"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="8" value="" edge="1" parent="3" source="5" target="AuthorizeClaim"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="9" value="" edge="1" parent="3" source="AuthorizeClaim" target="6"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="9" value="" edge="1" parent="3" source="AuthorizeClaim" target="6"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="10" value="" edge="1" parent="3" source="6" target="ApproveClaim"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="10" value="" edge="1" parent="3" source="6" target="ApproveClaim"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="11" value="" edge="1" parent="3" source="ApproveClaim" target="7"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="11" value="" edge="1" parent="3" source="ApproveClaim" target="7"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="12" value="" edge="1" parent="3" source="7" target="AuthorizeClaim"><mxGeometry relative="1" as="geometry"><Array as="points"><mxPoint x="140" y="40"/></Array></mxGeometry></mxCell>' + '<Cell id="12" value="" edge="1" parent="3" source="7" target="AuthorizeClaim"><Geometry relative="1" as="geometry"><Array as="points"><Point x="140" y="40"/></Array></Geometry></Cell>' +
'<mxCell id="ReviewClaim" value="Review&#xa;Claim" vertex="1" parent="3"><mxGeometry x="480" y="80" width="100" height="40" as="geometry"/></mxCell>' + '<Cell id="ReviewClaim" value="Review&#xa;Claim" vertex="1" parent="3"><Geometry x="480" y="80" width="100" height="40" as="geometry"/></Cell>' +
'<mxCell id="22" value="X" style="step" vertex="1" parent="3"><mxGeometry x="600" y="85" width="30" height="30" as="geometry"/></mxCell>' + '<Cell id="22" value="X" style="step" vertex="1" parent="3"><Geometry x="600" y="85" width="30" height="30" as="geometry"/></Cell>' +
'<mxCell id="23" value="" edge="1" parent="3" source="ReviewClaim" target="22"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="23" value="" edge="1" parent="3" source="ReviewClaim" target="22"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="ApproveReviewedClaim" value="Approve Rev.&#xa;Claim" vertex="1" parent="3"><mxGeometry x="650" y="80" width="100" height="40" as="geometry"/></mxCell>' + '<Cell id="ApproveReviewedClaim" value="Approve Rev.&#xa;Claim" vertex="1" parent="3"><Geometry x="650" y="80" width="100" height="40" as="geometry"/></Cell>' +
'<mxCell id="26" value="" edge="1" parent="3" source="22" target="ApproveReviewedClaim"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="26" value="" edge="1" parent="3" source="22" target="ApproveReviewedClaim"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="27" value="X" style="step" vertex="1" parent="3"><mxGeometry x="770" y="85" width="30" height="30" as="geometry"/></mxCell>' + '<Cell id="27" value="X" style="step" vertex="1" parent="3"><Geometry x="770" y="85" width="30" height="30" as="geometry"/></Cell>' +
'<mxCell id="28" value="" edge="1" target="27" parent="3" source="ApproveReviewedClaim"><mxGeometry relative="1" as="geometry"><mxPoint x="740" y="100" as="sourcePoint"/><mxPoint x="760" y="100" as="targetPoint"/></mxGeometry></mxCell>' + '<Cell id="28" value="" edge="1" target="27" parent="3" source="ApproveReviewedClaim"><Geometry relative="1" as="geometry"><Point x="740" y="100" as="sourcePoint"/><Point x="760" y="100" as="targetPoint"/></Geometry></Cell>' +
'<mxCell id="32" value="" edge="1" parent="3" source="27" target="ReviewClaim"><mxGeometry relative="1" as="geometry"><Array as="points"><mxPoint x="665" y="160"/></Array></mxGeometry></mxCell>' + '<Cell id="32" value="" edge="1" parent="3" source="27" target="ReviewClaim"><Geometry relative="1" as="geometry"><Array as="points"><Point x="665" y="160"/></Array></Geometry></Cell>' +
'<mxCell id="4" value="Accountant" style="swimlane" vertex="1" parent="2"><mxGeometry x="30" y="200" width="820" height="200" as="geometry"/></mxCell>' + '<Cell id="4" value="Accountant" style="swimlane" vertex="1" parent="2"><Geometry x="30" y="200" width="820" height="200" as="geometry"/></Cell>' +
'<mxCell id="EnterAccountingData" value="Enter&#xa;Data" vertex="1" parent="4"><mxGeometry x="430" y="80" width="100" height="40" as="geometry"/></mxCell>' + '<Cell id="EnterAccountingData" value="Enter&#xa;Data" vertex="1" parent="4"><Geometry x="430" y="80" width="100" height="40" as="geometry"/></Cell>' +
'<mxCell id="14" value="X" style="step" vertex="1" parent="4"><mxGeometry x="550" y="85" width="30" height="30" as="geometry"/></mxCell>' + '<Cell id="14" value="X" style="step" vertex="1" parent="4"><Geometry x="550" y="85" width="30" height="30" as="geometry"/></Cell>' +
'<mxCell id="15" value="" edge="1" parent="4" source="EnterAccountingData" target="14"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="15" value="" edge="1" parent="4" source="EnterAccountingData" target="14"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="CheckAccountingData" value="Check&#xa;Data" vertex="1" parent="4"><mxGeometry x="600" y="80" width="100" height="40" as="geometry"/></mxCell>' + '<Cell id="CheckAccountingData" value="Check&#xa;Data" vertex="1" parent="4"><Geometry x="600" y="80" width="100" height="40" as="geometry"/></Cell>' +
'<mxCell id="16" value="" edge="1" parent="4" source="14" target="CheckAccountingData"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="16" value="" edge="1" parent="4" source="14" target="CheckAccountingData"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="17" value="X" style="step" vertex="1" parent="4"><mxGeometry x="720" y="85" width="30" height="30" as="geometry"/></mxCell>' + '<Cell id="17" value="X" style="step" vertex="1" parent="4"><Geometry x="720" y="85" width="30" height="30" as="geometry"/></Cell>' +
'<mxCell id="18" value="" edge="1" parent="4" source="CheckAccountingData" target="17"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="18" value="" edge="1" parent="4" source="CheckAccountingData" target="17"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="19" value="" style="end" vertex="1" parent="4"><mxGeometry x="770" y="85" width="30" height="30" as="geometry"/></mxCell>' + '<Cell id="19" value="" style="end" vertex="1" parent="4"><Geometry x="770" y="85" width="30" height="30" as="geometry"/></Cell>' +
'<mxCell id="20" value="" edge="1" parent="4" source="17" target="19"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="20" value="" edge="1" parent="4" source="17" target="19"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="31" value="" edge="1" parent="4" source="17" target="EnterAccountingData"><mxGeometry relative="1" as="geometry"><Array as="points"><mxPoint x="625" y="160"/></Array></mxGeometry></mxCell>' + '<Cell id="31" value="" edge="1" parent="4" source="17" target="EnterAccountingData"><Geometry relative="1" as="geometry"><Array as="points"><Point x="625" y="160"/></Array></Geometry></Cell>' +
'<mxCell id="13" value="" edge="1" parent="2" source="7" target="EnterAccountingData"><mxGeometry relative="1" as="geometry"/></mxCell>' + '<Cell id="13" value="" edge="1" parent="2" source="7" target="EnterAccountingData"><Geometry relative="1" as="geometry"/></Cell>' +
'<mxCell id="24" value="" edge="1" parent="2" source="14" target="ReviewClaim" style="edgeStyle=none"><mxGeometry relative="1" as="geometry"><Array as="points"><mxPoint x="595" y="180"/><mxPoint x="480" y="180"/><mxPoint x="480" y="100"/></Array></mxGeometry></mxCell>' + '<Cell id="24" value="" edge="1" parent="2" source="14" target="ReviewClaim" style="edgeStyle=none"><Geometry relative="1" as="geometry"><Array as="points"><Point x="595" y="180"/><Point x="480" y="180"/><Point x="480" y="100"/></Array></Geometry></Cell>' +
'<mxCell id="29" value="" edge="1" parent="2" source="22" target="EnterAccountingData"><mxGeometry relative="1" as="geometry"><Array as="points"><mxPoint x="469" y="40"/></Array></mxGeometry></mxCell>' + '<Cell id="29" value="" edge="1" parent="2" source="22" target="EnterAccountingData"><Geometry relative="1" as="geometry"><Array as="points"><Point x="469" y="40"/></Array></Geometry></Cell>' +
'<mxCell id="30" value="" edge="1" parent="2" source="27" target="EnterAccountingData"><mxGeometry relative="1" as="geometry"><Array as="points"><mxPoint x="469" y="40"/></Array></mxGeometry></mxCell>' + '<Cell id="30" value="" edge="1" parent="2" source="27" target="EnterAccountingData"><Geometry relative="1" as="geometry"><Array as="points"><Point x="469" y="40"/></Array></Geometry></Cell>' +
'<mxCell id="33" value="" edge="1" parent="2" source="6" target="EnterAccountingData"><mxGeometry relative="1" as="geometry"><Array as="points"><mxPoint x="255" y="200"/></Array></mxGeometry></mxCell>' + '<Cell id="33" value="" edge="1" parent="2" source="6" target="EnterAccountingData"><Geometry relative="1" as="geometry"><Array as="points"><Point x="255" y="200"/></Array></Geometry></Cell>' +
'</root></Transactions>'; '</root></Transactions>';
const doc = mxXmlUtils.parseXml(xml); const doc = mxXmlUtils.parseXml(xml);
const codec = new mxCodec(doc); const codec = new mxCodec(doc);
@ -87,8 +87,8 @@ const Template = ({ label, ...args }) => {
// Creates a button to invoke the refresh function // Creates a button to invoke the refresh function
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Update', function(evt) { mxDomHelpers.button('Update', function (evt) {
// XML is normally fetched from URL at server using mxUtils.get - this is a client-side // XML is normally fetched from URL at server using utils.get - this is a client-side
// string with randomized states to demonstrate the idea of the workflow monitor // string with randomized states to demonstrate the idea of the workflow monitor
const xml = const xml =
`<process><update id="ApproveClaim" state="${getState()}"/><update id="AuthorizeClaim" state="${getState()}"/>` + `<process><update id="ApproveClaim" state="${getState()}"/><update id="AuthorizeClaim" state="${getState()}"/>` +
@ -124,30 +124,16 @@ const Template = ({ label, ...args }) => {
// Updates the cell color and adds some tooltip information // Updates the cell color and adds some tooltip information
if (cell != null) { if (cell != null) {
// Resets the fillcolor and the overlay // Resets the fillcolor and the overlay
graph.setCellStyles('fillColor', 'white', [ graph.setCellStyles('fillColor', 'white', [cell]);
cell,
]);
graph.removeCellOverlays(cell); graph.removeCellOverlays(cell);
// Changes the cell color for the known states // Changes the cell color for the known states
if (state == 'Running') { if (state == 'Running') {
graph.setCellStyles( graph.setCellStyles('fillColor', '#f8cecc', [cell]);
'fillColor',
'#f8cecc',
[cell]
);
} else if (state == 'Waiting') { } else if (state == 'Waiting') {
graph.setCellStyles( graph.setCellStyles('fillColor', '#fff2cc', [cell]);
'fillColor',
'#fff2cc',
[cell]
);
} else if (state == 'Completed') { } else if (state == 'Completed') {
graph.setCellStyles( graph.setCellStyles('fillColor', '#d4e1f5', [cell]);
'fillColor',
'#d4e1f5',
[cell]
);
} }
// Adds tooltip information using an overlay icon // Adds tooltip information using an overlay icon
@ -176,8 +162,8 @@ const Template = ({ label, ...args }) => {
const overlay = new CellOverlay(image, tooltip); const overlay = new CellOverlay(image, tooltip);
// Installs a handler for clicks on the overlay // Installs a handler for clicks on the overlay
overlay.addListener(mxEvent.CLICK, function(sender, evt) { overlay.addListener(InternalEvent.CLICK, function (sender, evt) {
mxUtils.alert(`${tooltip}\nLast update: ${new Date()}`); utils.alert(`${tooltip}\nLast update: ${new Date()}`);
}); });
return overlay; return overlay;
@ -187,12 +173,12 @@ const Template = ({ label, ...args }) => {
* Creates and returns an empty graph inside the given container. * Creates and returns an empty graph inside the given container.
*/ */
function createGraph(container) { function createGraph(container) {
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setTooltips(true); graph.setTooltips(true);
graph.setEnabled(false); graph.setEnabled(false);
// Disables folding // Disables folding
graph.isCellFoldable = function(cell, collapse) { graph.isCellFoldable = function (cell, collapse) {
return false; return false;
}; };
@ -203,20 +189,20 @@ const Template = ({ label, ...args }) => {
style.strokeColor = '#808080'; style.strokeColor = '#808080';
style.fillColor = 'white'; style.fillColor = 'white';
style.gradientColor = 'white'; style.gradientColor = 'white';
style.gradientDirection = mxConstants.DIRECTION_EAST; style.gradientDirection = Constants.DIRECTION_EAST;
style.rounded = true; style.rounded = true;
style.shadow = true; style.shadow = true;
style.fontStyle = 1; style.fontStyle = 1;
style = graph.getStylesheet().getDefaultEdgeStyle(); style = graph.getStylesheet().getDefaultEdgeStyle();
style.edge = mxEdgeStyle.ElbowConnector; style.edge = EdgeStyle.ElbowConnector;
style.strokeColor = '#808080'; style.strokeColor = '#808080';
style.rounded = true; style.rounded = true;
style.shadow = true; style.shadow = true;
style = []; style = [];
style.shape = mxConstants.SHAPE_SWIMLANE; style.shape = Constants.SHAPE_SWIMLANE;
style.perimiter = mxPerimeter.RectanglePerimeter; style.perimiter = Perimeter.RectanglePerimeter;
style.strokeColor = '#a0a0a0'; style.strokeColor = '#a0a0a0';
style.fontColor = '#606060'; style.fontColor = '#606060';
style.fillColor = '#E0E0DF'; style.fillColor = '#E0E0DF';
@ -232,30 +218,30 @@ const Template = ({ label, ...args }) => {
graph.getStylesheet().putCellStyle('swimlane', style); graph.getStylesheet().putCellStyle('swimlane', style);
style = []; style = [];
style.shape = mxConstants.SHAPE_RHOMBUS; style.shape = Constants.SHAPE_RHOMBUS;
style.perimiter = mxPerimeter.RhombusPerimeter; style.perimiter = Perimeter.RhombusPerimeter;
style.strokeColor = '#91BCC0'; style.strokeColor = '#91BCC0';
style.fontColor = 'gray'; style.fontColor = 'gray';
style.fillColor = '#91BCC0'; style.fillColor = '#91BCC0';
style.gradientColor = 'white'; style.gradientColor = 'white';
style.align = mxConstants.ALIGN_CENTER; style.align = Constants.ALIGN_CENTER;
style.verticalAlign = mxConstants.ALIGN_MIDDLE; style.verticalAlign = Constants.ALIGN_MIDDLE;
style.fontSize = 16; style.fontSize = 16;
graph.getStylesheet().putCellStyle('step', style); graph.getStylesheet().putCellStyle('step', style);
style = []; style = [];
style.shape = mxConstants.SHAPE_ELLIPSE; style.shape = Constants.SHAPE_ELLIPSE;
style.perimiter = mxPerimeter.EllipsePerimeter; style.perimiter = Perimeter.EllipsePerimeter;
style.fontColor = 'gray'; style.fontColor = 'gray';
style.fillColor = '#A0C88F'; style.fillColor = '#A0C88F';
style.gradientColor = 'white'; style.gradientColor = 'white';
style.strokeColor = '#A0C88F'; style.strokeColor = '#A0C88F';
style.align = mxConstants.ALIGN_CENTER; style.align = Constants.ALIGN_CENTER;
style.verticalAlign = mxConstants.ALIGN_MIDDLE; style.verticalAlign = Constants.ALIGN_MIDDLE;
style.fontSize = 16; style.fontSize = 16;
graph.getStylesheet().putCellStyle('start', style); graph.getStylesheet().putCellStyle('start', style);
style = mxCloneUtils.clone(style); style = CloneUtils.clone(style);
style.fillColor = '#DACCBC'; style.fillColor = '#DACCBC';
style.strokeColor = '#AF7F73'; style.strokeColor = '#AF7F73';
graph.getStylesheet().putCellStyle('end', style); graph.getStylesheet().putCellStyle('end', style);
@ -282,6 +268,6 @@ const Template = ({ label, ...args }) => {
} }
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,23 +8,17 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, mxDomHelpers, mxMorphing, InternalEvent, Rubberband } = maxgraph;
mxGraph,
mxDomHelpers,
mxMorphing,
mxEvent,
mxRubberband
} = mxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -38,15 +32,13 @@ const Template = ({ label, ...args }) => {
div.appendChild(container); div.appendChild(container);
// Disables the built-in context menu // Disables the built-in context menu
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -71,7 +63,7 @@ const Template = ({ label, ...args }) => {
div.appendChild(buttons); div.appendChild(buttons);
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Morph', function() { mxDomHelpers.button('Morph', function () {
graph.clearSelection(); graph.clearSelection();
graph.getModel().beginUpdate(); graph.getModel().beginUpdate();
@ -88,7 +80,7 @@ const Template = ({ label, ...args }) => {
} finally { } finally {
// Arguments are number of steps, ease and delay // Arguments are number of steps, ease and delay
const morph = new mxMorphing(graph, 20, 1.2, 20); const morph = new mxMorphing(graph, 20, 1.2, 20);
morph.addListener(mxEvent.DONE, function() { morph.addListener(InternalEvent.DONE, function () {
graph.getModel().endUpdate(); graph.getModel().endUpdate();
}); });
morph.startAnimation(); morph.startAnimation();
@ -99,6 +91,6 @@ const Template = ({ label, ...args }) => {
); );
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,21 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Zoom_OffPage/OffPage', title: 'Zoom_OffPage/OffPage',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, CellTracker, Constants, InternalEvent } = maxgraph;
mxGraph,
mxCellTracker,
mxConstants,
mxEvent
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -26,21 +21,17 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Use complete cell as highlight region // Use complete cell as highlight region
mxConstants.ACTIVE_REGION = 1; Constants.ACTIVE_REGION = 1;
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setEnabled(false); graph.setEnabled(false);
// Highlights offpage connectors // Highlights offpage connectors
const highlight = new mxCellTracker(graph, null, function(me) { const highlight = new CellTracker(graph, null, function (me) {
const cell = me.getCell(); const cell = me.getCell();
if ( if (cell != null && cell.value != null && typeof cell.value.create === 'function') {
cell != null &&
cell.value != null &&
typeof cell.value.create === 'function'
) {
return cell; return cell;
} }
@ -49,26 +40,18 @@ const Template = ({ label, ...args }) => {
// Handles clicks on offpage connectors and // Handles clicks on offpage connectors and
// executes function in user object // executes function in user object
graph.addListener(mxEvent.CLICK, function(source, evt) { graph.addListener(InternalEvent.CLICK, function (source, evt) {
const cell = evt.getProperty('cell'); const cell = evt.getProperty('cell');
if ( if (cell != null && cell.value != null && typeof cell.value.create === 'function') {
cell != null &&
cell.value != null &&
typeof cell.value.create === 'function'
) {
cell.value.create(); cell.value.create();
} }
}); });
// Handles clicks on offpage connectors and // Handles clicks on offpage connectors and
// executes function in user object // executes function in user object
graph.getCursorForCell = function(cell) { graph.getCursorForCell = function (cell) {
if ( if (cell != null && cell.value != null && typeof cell.value.create === 'function') {
cell != null &&
cell.value != null &&
typeof cell.value.create === 'function'
) {
return 'pointer'; return 'pointer';
} }
}; };
@ -78,7 +61,7 @@ const Template = ({ label, ...args }) => {
let first = null; let first = null;
let second = null; let second = null;
first = function() { first = function () {
const value = { const value = {
toString() { toString() {
return 'Next'; return 'Next';
@ -122,21 +105,14 @@ const Template = ({ label, ...args }) => {
40, 40,
'shape=triangle;align=left;fillColor=#C3D9FF;strokeColor=#4096EE' 'shape=triangle;align=left;fillColor=#C3D9FF;strokeColor=#4096EE'
); );
const e1 = graph.insertEdge( const e1 = graph.insertEdge(parent, null, null, v1, v2, 'strokeColor=#FF1A00');
parent,
null,
null,
v1,
v2,
'strokeColor=#FF1A00'
);
} finally { } finally {
// Updates the display // Updates the display
graph.getModel().endUpdate(); graph.getModel().endUpdate();
} }
}; };
second = function() { second = function () {
const value = { const value = {
toString() { toString() {
return 'Prev'; return 'Prev';
@ -180,14 +156,7 @@ const Template = ({ label, ...args }) => {
40, 40,
'shape=triangle;align=right;fillColor=#C3D9FF;strokeColor=#4096EE;direction=west' 'shape=triangle;align=right;fillColor=#C3D9FF;strokeColor=#4096EE;direction=west'
); );
const e1 = graph.insertEdge( const e1 = graph.insertEdge(parent, null, null, v1, v2, 'strokeColor=#008C00');
parent,
null,
null,
v1,
v2,
'strokeColor=#008C00'
);
} finally { } finally {
// Updates the display // Updates the display
graph.getModel().endUpdate(); graph.getModel().endUpdate();
@ -197,6 +166,6 @@ const Template = ({ label, ...args }) => {
first(); first();
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,28 +8,28 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxConstants, Constants,
mxEvent, InternalEvent,
mxClient, mxClient,
mxPoint, Point,
mxOutline, Outline,
mxEdgeStyle, EdgeStyle,
mxKeyHandler, mxKeyHandler,
mxCompactTreeLayout, CompactTreeLayout,
mxLayoutManager, LayoutManager,
mxCellOverlay, CellOverlay,
mxImage, ImageBox,
mxUtils, utils,
mxToolbar mxToolbar,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -43,24 +43,22 @@ const Template = ({ label, ...args }) => {
div.appendChild(container); div.appendChild(container);
// Makes the shadow brighter // Makes the shadow brighter
mxConstants.SHADOWCOLOR = '#C0C0C0'; Constants.SHADOWCOLOR = '#C0C0C0';
const outline = document.getElementById('outlineContainer'); const outline = document.getElementById('outlineContainer');
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
// Sets a gradient background // Sets a gradient background
if (mxClient.IS_GC || mxClient.IS_SF) { if (mxClient.IS_GC || mxClient.IS_SF) {
container.style.background = container.style.background =
'-webkit-gradient(linear, 0% 0%, 0% 100%, from(#FFFFFF), to(#E7E7E7))'; '-webkit-gradient(linear, 0% 0%, 0% 100%, from(#FFFFFF), to(#E7E7E7))';
} else if (mxClient.IS_NS) { } else if (mxClient.IS_NS) {
container.style.background = container.style.background = '-moz-linear-gradient(top, #FFFFFF, #E7E7E7)';
'-moz-linear-gradient(top, #FFFFFF, #E7E7E7)';
} }
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Enables automatic sizing for vertices after editing and // Enables automatic sizing for vertices after editing and
// panning by using the left mouse button. // panning by using the left mouse button.
@ -78,7 +76,7 @@ const Template = ({ label, ...args }) => {
// Creates the outline (navigator, overview) for moving // Creates the outline (navigator, overview) for moving
// around the graph in the top, right corner of the window. // around the graph in the top, right corner of the window.
const outln = new mxOutline(graph, outline); const outln = new Outline(graph, outline);
// Disables tooltips on touch devices // Disables tooltips on touch devices
graph.setTooltips(!mxClient.IS_TOUCH); graph.setTooltips(!mxClient.IS_TOUCH);
@ -87,8 +85,8 @@ const Template = ({ label, ...args }) => {
let style = graph.getStylesheet().getDefaultVertexStyle(); let style = graph.getStylesheet().getDefaultVertexStyle();
style.shape = 'label'; style.shape = 'label';
style.verticalAlign = mxConstants.ALIGN_MIDDLE; style.verticalAlign = Constants.ALIGN_MIDDLE;
style.align = mxConstants.ALIGN_LEFT; style.align = Constants.ALIGN_LEFT;
style.spacingLeft = 54; style.spacingLeft = 54;
style.gradientColor = '#7d85df'; style.gradientColor = '#7d85df';
@ -121,7 +119,7 @@ const Template = ({ label, ...args }) => {
style.entryPerimeter = 0; // disabled style.entryPerimeter = 0; // disabled
// Disable the following for straight lines // Disable the following for straight lines
style.edge = mxEdgeStyle.TopToBottom; style.edge = EdgeStyle.TopToBottom;
// Stops editing on enter or escape keypress // Stops editing on enter or escape keypress
const keyHandler = new mxKeyHandler(graph); const keyHandler = new mxKeyHandler(graph);
@ -129,7 +127,7 @@ const Template = ({ label, ...args }) => {
// Enables automatic layout on the graph and installs // Enables automatic layout on the graph and installs
// a tree layout for all groups who's children are // a tree layout for all groups who's children are
// being changed, added or removed. // being changed, added or removed.
const layout = new mxCompactTreeLayout(graph, false); const layout = new CompactTreeLayout(graph, false);
layout.useBoundingBox = false; layout.useBoundingBox = false;
layout.edgeRouting = false; layout.edgeRouting = false;
layout.levelDistance = 60; layout.levelDistance = 60;
@ -137,26 +135,26 @@ const Template = ({ label, ...args }) => {
// Allows the layout to move cells even though cells // Allows the layout to move cells even though cells
// aren't movable in the graph // aren't movable in the graph
layout.isVertexMovable = function(cell) { layout.isVertexMovable = function (cell) {
return true; return true;
}; };
const layoutMgr = new mxLayoutManager(graph); const layoutMgr = new LayoutManager(graph);
layoutMgr.getLayout = function(cell) { layoutMgr.getLayout = function (cell) {
if (cell.getChildCount() > 0) { if (cell.getChildCount() > 0) {
return layout; return layout;
} }
}; };
// Installs a popupmenu handler using local function (see below). // Installs a popupmenu handler using local function (see below).
graph.popupMenuHandler.factoryMethod = function(menu, cell, evt) { graph.popupMenuHandler.factoryMethod = function (menu, cell, evt) {
return createPopupMenu(graph, menu, cell, evt); return createPopupMenu(graph, menu, cell, evt);
}; };
// Fix for wrong preferred size // Fix for wrong preferred size
const oldGetPreferredSizeForCell = graph.getPreferredSizeForCell; const oldGetPreferredSizeForCell = graph.getPreferredSizeForCell;
graph.getPreferredSizeForCell = function(cell) { graph.getPreferredSizeForCell = function (cell) {
const result = oldGetPreferredSizeForCell.apply(this, arguments); const result = oldGetPreferredSizeForCell.apply(this, arguments);
if (result != null) { if (result != null) {
@ -167,13 +165,13 @@ const Template = ({ label, ...args }) => {
}; };
// Sets the maximum text scale to 1 // Sets the maximum text scale to 1
graph.cellRenderer.getTextScale = function(state) { graph.cellRenderer.getTextScale = function (state) {
return Math.min(1, state.view.scale); return Math.min(1, state.view.scale);
}; };
// Dynamically adds text to the label as we zoom in // Dynamically adds text to the label as we zoom in
// (without affecting the preferred size for new cells) // (without affecting the preferred size for new cells)
graph.cellRenderer.getLabelValue = function(state) { graph.cellRenderer.getLabelValue = function (state) {
let result = state.cell.value; let result = state.cell.value;
if (state.cell.isVertex()) { if (state.cell.isVertex()) {
@ -219,28 +217,28 @@ const Template = ({ label, ...args }) => {
div.appendChild(content); div.appendChild(content);
const tb = new mxToolbar(content); const tb = new mxToolbar(content);
tb.addItem('Zoom In', 'images/zoom_in32.png', function(evt) { tb.addItem('Zoom In', 'images/zoom_in32.png', function (evt) {
graph.zoomIn(); graph.zoomIn();
}); });
tb.addItem('Zoom Out', 'images/zoom_out32.png', function(evt) { tb.addItem('Zoom Out', 'images/zoom_out32.png', function (evt) {
graph.zoomOut(); graph.zoomOut();
}); });
tb.addItem('Actual Size', 'images/view_1_132.png', function(evt) { tb.addItem('Actual Size', 'images/view_1_132.png', function (evt) {
graph.zoomActual(); graph.zoomActual();
}); });
tb.addItem('Print', 'images/print32.png', function(evt) { tb.addItem('Print', 'images/print32.png', function (evt) {
const preview = new PrintPreview(graph, 1); const preview = new PrintPreview(graph, 1);
preview.open(); preview.open();
}); });
tb.addItem('Poster Print', 'images/press32.png', function(evt) { tb.addItem('Poster Print', 'images/press32.png', function (evt) {
const pageCount = mxUtils.prompt('Enter maximum page count', '1'); const pageCount = utils.prompt('Enter maximum page count', '1');
if (pageCount != null) { if (pageCount != null) {
const scale = mxUtils.getScaleForPageCount(pageCount, graph); const scale = utils.getScaleForPageCount(pageCount, graph);
const preview = new PrintPreview(graph, scale); const preview = new PrintPreview(graph, scale);
preview.open(); preview.open();
} }
@ -252,21 +250,17 @@ const Template = ({ label, ...args }) => {
if (cell != null) { if (cell != null) {
if (cell.isVertex()) { if (cell.isVertex()) {
menu.addItem( menu.addItem('Add child', '/images/overlays/check.png', function () {
'Add child', addChild(graph, cell);
'/images/overlays/check.png', });
function() {
addChild(graph, cell);
}
);
} }
menu.addItem('Edit label', '/images/text.gif', function() { menu.addItem('Edit label', '/images/text.gif', function () {
graph.startEditingAtCell(cell); graph.startEditingAtCell(cell);
}); });
if (cell.id != 'treeRoot' && cell.isVertex()) { if (cell.id != 'treeRoot' && cell.isVertex()) {
menu.addItem('Delete', '/images/delete.gif', function() { menu.addItem('Delete', '/images/delete.gif', function () {
deleteSubtree(graph, cell); deleteSubtree(graph, cell);
}); });
} }
@ -274,26 +268,26 @@ const Template = ({ label, ...args }) => {
menu.addSeparator(); menu.addSeparator();
} }
menu.addItem('Fit', '/images/zoom.gif', function() { menu.addItem('Fit', '/images/zoom.gif', function () {
graph.fit(); graph.fit();
}); });
menu.addItem('Actual', '/images/zoomactual.gif', function() { menu.addItem('Actual', '/images/zoomactual.gif', function () {
graph.zoomActual(); graph.zoomActual();
}); });
menu.addSeparator(); menu.addSeparator();
menu.addItem('Print', '/images/print.gif', function() { menu.addItem('Print', '/images/print.gif', function () {
const preview = new PrintPreview(graph, 1); const preview = new PrintPreview(graph, 1);
preview.open(); preview.open();
}); });
menu.addItem('Poster Print', '/images/print.gif', function() { menu.addItem('Poster Print', '/images/print.gif', function () {
const pageCount = mxUtils.prompt('Enter maximum page count', '1'); const pageCount = utils.prompt('Enter maximum page count', '1');
if (pageCount != null) { if (pageCount != null) {
const scale = mxUtils.getScaleForPageCount(pageCount, graph); const scale = utils.getScaleForPageCount(pageCount, graph);
const preview = new PrintPreview(graph, scale); const preview = new PrintPreview(graph, scale);
preview.open(); preview.open();
} }
@ -301,36 +295,24 @@ const Template = ({ label, ...args }) => {
} }
function addOverlays(graph, cell, addDeleteIcon) { function addOverlays(graph, cell, addDeleteIcon) {
let overlay = new mxCellOverlay( let overlay = new CellOverlay(new ImageBox('images/add.png', 24, 24), 'Add child');
new mxImage('images/add.png', 24, 24),
'Add child'
);
overlay.cursor = 'hand'; overlay.cursor = 'hand';
overlay.align = mxConstants.ALIGN_CENTER; overlay.align = Constants.ALIGN_CENTER;
overlay.addListener( overlay.addListener(InternalEvent.CLICK, (sender, evt) => {
mxEvent.CLICK, addChild(graph, cell);
(sender, evt) => { });
addChild(graph, cell);
}
);
graph.addCellOverlay(cell, overlay); graph.addCellOverlay(cell, overlay);
if (addDeleteIcon) { if (addDeleteIcon) {
overlay = new mxCellOverlay( overlay = new CellOverlay(new ImageBox('images/close.png', 30, 30), 'Delete');
new mxImage('images/close.png', 30, 30),
'Delete'
);
overlay.cursor = 'hand'; overlay.cursor = 'hand';
overlay.offset = new mxPoint(-4, 8); overlay.offset = new Point(-4, 8);
overlay.align = mxConstants.ALIGN_RIGHT; overlay.align = Constants.ALIGN_RIGHT;
overlay.verticalAlign = mxConstants.ALIGN_TOP; overlay.verticalAlign = Constants.ALIGN_TOP;
overlay.addListener( overlay.addListener(InternalEvent.CLICK, (sender, evt) => {
mxEvent.CLICK, deleteSubtree(graph, cell);
(sender, evt) => { });
deleteSubtree(graph, cell);
}
);
graph.addCellOverlay(cell, overlay); graph.addCellOverlay(cell, overlay);
} }
@ -362,7 +344,7 @@ const Template = ({ label, ...args }) => {
// of 20 pixels in negative, vertical direction. // of 20 pixels in negative, vertical direction.
edge.geometry.x = 1; edge.geometry.x = 1;
edge.geometry.y = 0; edge.geometry.y = 0;
edge.geometry.offset = new mxPoint(0, -20); edge.geometry.offset = new Point(0, -20);
addOverlays(graph, vertex, true); addOverlays(graph, vertex, true);
} finally { } finally {
@ -375,7 +357,7 @@ const Template = ({ label, ...args }) => {
function deleteSubtree(graph, cell) { function deleteSubtree(graph, cell) {
// Gets the subtree from cell downwards // Gets the subtree from cell downwards
const cells = []; const cells = [];
graph.traverse(cell, true, function(vertex) { graph.traverse(cell, true, function (vertex) {
cells.push(vertex); cells.push(vertex);
return true; return true;
@ -385,6 +367,6 @@ const Template = ({ label, ...args }) => {
} }
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,27 +1,27 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Connections/Orthogonal', title: 'Connections/Orthogonal',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxRubberband, Rubberband,
mxConnectionHandler, ConnectionHandler,
mxGraphHandler, GraphHandler,
mxGuide, Guide,
mxPoint, Point,
mxCellState, CellState,
mxEdgeHandler, EdgeHandler,
mxGraphView, GraphView,
mxEvent InternalEvent,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -32,21 +32,21 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Enables guides // Enables guides
mxGraphHandler.prototype.guidesEnabled = true; GraphHandler.prototype.guidesEnabled = true;
// Alt disables guides // Alt disables guides
mxGuide.prototype.isEnabledForEvent = function(evt) { Guide.prototype.isEnabledForEvent = function (evt) {
return !mxEvent.isAltDown(evt); return !InternalEvent.isAltDown(evt);
}; };
// Enables snapping waypoints to terminals // Enables snapping waypoints to terminals
mxEdgeHandler.prototype.snapToTerminals = true; EdgeHandler.prototype.snapToTerminals = true;
// Enables orthogonal connect preview in IE // Enables orthogonal connect preview in IE
mxConnectionHandler.prototype.movePreviewAway = false; ConnectionHandler.prototype.movePreviewAway = false;
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.disconnectOnMove = false; graph.disconnectOnMove = false;
graph.foldingEnabled = false; graph.foldingEnabled = false;
graph.cellsResizable = false; graph.cellsResizable = false;
@ -54,46 +54,29 @@ const Template = ({ label, ...args }) => {
graph.setConnectable(true); graph.setConnectable(true);
// Implements perimeter-less connection points as fixed points (computed before the edge style). // Implements perimeter-less connection points as fixed points (computed before the edge style).
graph.view.updateFixedTerminalPoint = function( graph.view.updateFixedTerminalPoint = function (edge, terminal, source, constraint) {
edge, GraphView.prototype.updateFixedTerminalPoint.apply(this, arguments);
terminal,
source,
constraint
) {
mxGraphView.prototype.updateFixedTerminalPoint.apply(this, arguments);
const pts = edge.absolutePoints; const pts = edge.absolutePoints;
const pt = pts[source ? 0 : pts.length - 1]; const pt = pts[source ? 0 : pts.length - 1];
if ( if (terminal != null && pt == null && this.getPerimeterFunction(terminal) == null) {
terminal != null &&
pt == null &&
this.getPerimeterFunction(terminal) == null
) {
edge.setAbsoluteTerminalPoint( edge.setAbsoluteTerminalPoint(
new mxPoint( new Point(this.getRoutingCenterX(terminal), this.getRoutingCenterY(terminal)),
this.getRoutingCenterX(terminal),
this.getRoutingCenterY(terminal)
),
source source
); );
} }
}; };
// Changes the default edge style // Changes the default edge style
graph.getStylesheet().getDefaultEdgeStyle().edgeStyle = graph.getStylesheet().getDefaultEdgeStyle().edgeStyle = 'orthogonalEdgeStyle';
'orthogonalEdgeStyle';
delete graph.getStylesheet().getDefaultEdgeStyle().endArrow; delete graph.getStylesheet().getDefaultEdgeStyle().endArrow;
// Implements the connect preview // Implements the connect preview
graph.connectionHandler.createEdgeState = function(me) { graph.connectionHandler.createEdgeState = function (me) {
const edge = graph.createEdge(null, null, null, null, null); const edge = graph.createEdge(null, null, null, null, null);
return new mxCellState( return new CellState(this.graph.view, edge, this.graph.getCellStyle(edge));
this.graph.view,
edge,
this.graph.getCellStyle(edge)
);
}; };
// Uncomment the following if you want the container // Uncomment the following if you want the container
@ -101,8 +84,7 @@ const Template = ({ label, ...args }) => {
// graph.setResizeContainer(true); // graph.setResizeContainer(true);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -124,7 +106,7 @@ const Template = ({ label, ...args }) => {
'portConstraint=northsouth;', 'portConstraint=northsouth;',
true true
); );
v11.geometry.offset = new mxPoint(-5, -5); v11.geometry.offset = new Point(-5, -5);
const v12 = graph.insertVertex( const v12 = graph.insertVertex(
v1, v1,
null, null,
@ -137,7 +119,7 @@ const Template = ({ label, ...args }) => {
'routingCenterX=-0.5;routingCenterY=0;', 'routingCenterX=-0.5;routingCenterY=0;',
true true
); );
v12.geometry.offset = new mxPoint(-10, -5); v12.geometry.offset = new Point(-10, -5);
const v13 = graph.insertVertex( const v13 = graph.insertVertex(
v1, v1,
null, null,
@ -150,7 +132,7 @@ const Template = ({ label, ...args }) => {
'routingCenterX=0.5;routingCenterY=0;', 'routingCenterX=0.5;routingCenterY=0;',
true true
); );
v13.geometry.offset = new mxPoint(0, -5); v13.geometry.offset = new Point(0, -5);
const v2 = graph.addCell(graph.getModel().cloneCell(v1)); const v2 = graph.addCell(graph.getModel().cloneCell(v1));
v2.geometry.x = 200; v2.geometry.x = 200;
@ -173,6 +155,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,23 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Effects/Overlays', title: 'Effects/Overlays',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, CellOverlay, InternalEvent, CellTracker, utils, ImageBox } = maxgraph;
mxGraph,
mxCellOverlay,
mxEvent,
mxCellTracker,
mxUtils,
mxImage
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -28,20 +21,20 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Disables basic selection and cell handling // Disables basic selection and cell handling
graph.setEnabled(false); graph.setEnabled(false);
// Highlights the vertices when the mouse enters // Highlights the vertices when the mouse enters
const highlight = new mxCellTracker(graph, '#00FF00'); const highlight = new CellTracker(graph, '#00FF00');
// Enables tooltips for the overlays // Enables tooltips for the overlays
graph.setTooltips(true); graph.setTooltips(true);
// Installs a handler for click events in the graph // Installs a handler for click events in the graph
// that toggles the overlay for the respective cell // that toggles the overlay for the respective cell
graph.addListener(mxEvent.CLICK, (sender, evt) => { graph.addListener(InternalEvent.CLICK, (sender, evt) => {
const cell = evt.getProperty('cell'); const cell = evt.getProperty('cell');
if (cell != null) { if (cell != null) {
@ -49,14 +42,14 @@ const Template = ({ label, ...args }) => {
if (overlays == null) { if (overlays == null) {
// Creates a new overlay with an image and a tooltip // Creates a new overlay with an image and a tooltip
const overlay = new mxCellOverlay( const overlay = new CellOverlay(
new mxImage('/images/check.png', 16, 16), new ImageBox('/images/check.png', 16, 16),
'Overlay tooltip' 'Overlay tooltip'
); );
// Installs a handler for clicks on the overlay // Installs a handler for clicks on the overlay
overlay.addListener(mxEvent.CLICK, (sender, evt2) => { overlay.addListener(InternalEvent.CLICK, (sender, evt2) => {
mxUtils.alert('Overlay clicked'); utils.alert('Overlay clicked');
}); });
// Sets the overlay for the cell in the graph // Sets the overlay for the cell in the graph
@ -69,7 +62,7 @@ const Template = ({ label, ...args }) => {
// Installs a handler for double click events in the graph // Installs a handler for double click events in the graph
// that shows an alert box // that shows an alert box
graph.addListener(mxEvent.DOUBLE_CLICK, (sender, evt) => { graph.addListener(InternalEvent.DOUBLE_CLICK, (sender, evt) => {
const cell = evt.getProperty('cell'); const cell = evt.getProperty('cell');
alert(`Doubleclick: ${cell != null ? 'Cell' : 'Graph'}`); alert(`Doubleclick: ${cell != null ? 'Cell' : 'Graph'}`);
evt.consume(); evt.consume();
@ -101,6 +94,6 @@ const Template = ({ label, ...args }) => {
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,23 +8,17 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Rectangle, Rubberband, mxDomHelpers, InternalEvent } = maxgraph;
mxGraph,
mxRectangle,
mxRubberband,
mxDomHelpers,
mxEvent
} = mxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -37,11 +31,10 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
div.appendChild(container); div.appendChild(container);
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.view.setScale(0.15); graph.view.setScale(0.15);
graph.pageBreaksVisible = true; graph.pageBreaksVisible = true;
graph.pageBreakDashed = true; graph.pageBreakDashed = true;
@ -60,8 +53,7 @@ const Template = ({ label, ...args }) => {
graph.graphHandler.scaleGrid = true; graph.graphHandler.scaleGrid = true;
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -90,38 +82,38 @@ const Template = ({ label, ...args }) => {
div.appendChild(buttons); div.appendChild(buttons);
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Toggle Page Breaks', function(evt) { mxDomHelpers.button('Toggle Page Breaks', function (evt) {
graph.pageBreaksVisible = !graph.pageBreaksVisible; graph.pageBreaksVisible = !graph.pageBreaksVisible;
graph.sizeDidChange(); graph.sizeDidChange();
}) })
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Zoom In', function(evt) { mxDomHelpers.button('Zoom In', function (evt) {
graph.zoomIn(); graph.zoomIn();
}) })
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Zoom Out', function(evt) { mxDomHelpers.button('Zoom Out', function (evt) {
graph.zoomOut(); graph.zoomOut();
}) })
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Print', function(evt) { mxDomHelpers.button('Print', function (evt) {
// Matches actual printer paper size and avoids blank pages // Matches actual printer paper size and avoids blank pages
const scale = 0.5; const scale = 0.5;
// Applies scale to page // Applies scale to page
const pf = mxRectangle.fromRectangle( const pf = Rectangle.fromRectangle(
graph.pageFormat || mxConstants.PAGE_FORMAT_A4_PORTRAIT graph.pageFormat || Constants.PAGE_FORMAT_A4_PORTRAIT
); );
pf.width = Math.round(pf.width * scale * graph.pageScale); pf.width = Math.round(pf.width * scale * graph.pageScale);
pf.height = Math.round(pf.height * scale * graph.pageScale); pf.height = Math.round(pf.height * scale * graph.pageScale);
// Finds top left corner of top left page // Finds top left corner of top left page
const bounds = mxRectangle.fromRectangle(graph.getGraphBounds()); const bounds = Rectangle.fromRectangle(graph.getGraphBounds());
bounds.x -= graph.view.translate.x * graph.view.scale; bounds.x -= graph.view.translate.x * graph.view.scale;
bounds.y -= graph.view.translate.y * graph.view.scale; bounds.y -= graph.view.translate.y * graph.view.scale;
@ -134,7 +126,7 @@ const Template = ({ label, ...args }) => {
preview.autoOrigin = false; preview.autoOrigin = false;
const oldRenderPage = preview.renderPage; const oldRenderPage = preview.renderPage;
preview.renderPage = function(w, h, x, y, content, pageNumber) { preview.renderPage = function (w, h, x, y, content, pageNumber) {
const div = oldRenderPage.apply(this, arguments); const div = oldRenderPage.apply(this, arguments);
const header = document.createElement('div'); const header = document.createElement('div');
@ -172,12 +164,12 @@ const Template = ({ label, ...args }) => {
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Reset View', function(evt) { mxDomHelpers.button('Reset View', function (evt) {
graph.view.scaleAndTranslate(0.15, 0, 0); graph.view.scaleAndTranslate(0.15, 0, 0);
}) })
); );
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,18 +8,13 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Rubberband, GraphView, utils } = maxgraph;
mxGraph,
mxRubberband,
mxGraphView,
mxUtils
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -31,14 +26,8 @@ const Template = ({ label, ...args }) => {
// Redirects the perimeter to the label bounds if intersection // Redirects the perimeter to the label bounds if intersection
// between edge and label is found // between edge and label is found
const mxGraphViewGetPerimeterPoint = const mxGraphViewGetPerimeterPoint = GraphView.prototype.getPerimeterPoint;
mxGraphView.prototype.getPerimeterPoint; GraphView.prototype.getPerimeterPoint = function (terminal, next, orthogonal, border) {
mxGraphView.prototype.getPerimeterPoint = function(
terminal,
next,
orthogonal,
border
) {
let point = mxGraphViewGetPerimeterPoint.apply(this, arguments); let point = mxGraphViewGetPerimeterPoint.apply(this, arguments);
if (point != null) { if (point != null) {
@ -49,7 +38,7 @@ const Template = ({ label, ...args }) => {
const b = terminal.text.boundingBox.clone(); const b = terminal.text.boundingBox.clone();
b.grow(3); b.grow(3);
if (mxUtils.rectangleIntersectsSegment(b, point, next)) { if (utils.rectangleIntersectsSegment(b, point, next)) {
point = perimeter(b, terminal, next, orthogonal); point = perimeter(b, terminal, next, orthogonal);
} }
} }
@ -59,7 +48,7 @@ const Template = ({ label, ...args }) => {
}; };
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setVertexLabelsMovable(true); graph.setVertexLabelsMovable(true);
graph.setConnectable(true); graph.setConnectable(true);
@ -68,8 +57,7 @@ const Template = ({ label, ...args }) => {
// graph.setResizeContainer(true); // graph.setResizeContainer(true);
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -116,6 +104,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,20 +8,20 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxConnectionHandler, ConnectionHandler,
mxImage, ImageBox,
mxRubberband, Rubberband,
mxKeyHandler, mxKeyHandler,
mxDomHelpers mxDomHelpers,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -36,27 +36,22 @@ const Template = ({ label, ...args }) => {
// Defines an icon for creating new connections in the connection handler. // Defines an icon for creating new connections in the connection handler.
// This will automatically disable the highlighting of the source vertex. // This will automatically disable the highlighting of the source vertex.
mxConnectionHandler.prototype.connectImage = new mxImage( ConnectionHandler.prototype.connectImage = new ImageBox('images/connector.gif', 16, 16);
'images/connector.gif',
16,
16
);
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Enable tooltips, disables mutligraphs, enable loops // Enable tooltips, disables mutligraphs, enable loops
graph.setMultigraph(false); graph.setMultigraph(false);
graph.setAllowLoops(true); graph.setAllowLoops(true);
// Enables rubberband selection and key handling // Enables rubberband selection and key handling
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
const keyHandler = new mxKeyHandler(graph); const keyHandler = new mxKeyHandler(graph);
// Assigns the delete key // Assigns the delete key
keyHandler.bindKey(46, function(evt) { keyHandler.bindKey(46, function (evt) {
if (graph.isEnabled()) { if (graph.isEnabled()) {
graph.removeCells(); graph.removeCells();
} }
@ -66,7 +61,7 @@ const Template = ({ label, ...args }) => {
// aka "private" variable // aka "private" variable
let currentPermission = null; let currentPermission = null;
const apply = function(permission) { const apply = function (permission) {
graph.clearSelection(); graph.clearSelection();
permission.apply(graph); permission.apply(graph);
graph.setEnabled(true); graph.setEnabled(true);
@ -83,37 +78,37 @@ const Template = ({ label, ...args }) => {
const buttons = document.createElement('div'); const buttons = document.createElement('div');
div.appendChild(buttons); div.appendChild(buttons);
let button = mxDomHelpers.button('Allow All', function(evt) { let button = mxDomHelpers.button('Allow All', function (evt) {
apply(new Permission()); apply(new Permission());
}); });
buttons.appendChild(button); buttons.appendChild(button);
button = mxDomHelpers.button('Connect Only', function(evt) { button = mxDomHelpers.button('Connect Only', function (evt) {
apply(new Permission(false, true, false, false, true)); apply(new Permission(false, true, false, false, true));
}); });
buttons.appendChild(button); buttons.appendChild(button);
button = mxDomHelpers.button('Edges Only', function(evt) { button = mxDomHelpers.button('Edges Only', function (evt) {
apply(new Permission(false, false, true, false, false)); apply(new Permission(false, false, true, false, false));
}); });
buttons.appendChild(button); buttons.appendChild(button);
button = mxDomHelpers.button('Vertices Only', function(evt) { button = mxDomHelpers.button('Vertices Only', function (evt) {
apply(new Permission(false, false, false, true, false)); apply(new Permission(false, false, false, true, false));
}); });
buttons.appendChild(button); buttons.appendChild(button);
button = mxDomHelpers.button('Select Only', function(evt) { button = mxDomHelpers.button('Select Only', function (evt) {
apply(new Permission(false, false, false, false, false)); apply(new Permission(false, false, false, false, false));
}); });
buttons.appendChild(button); buttons.appendChild(button);
button = mxDomHelpers.button('Locked', function(evt) { button = mxDomHelpers.button('Locked', function (evt) {
apply(new Permission(true, false)); apply(new Permission(true, false));
}); });
buttons.appendChild(button); buttons.appendChild(button);
button = mxDomHelpers.button('Disabled', function(evt) { button = mxDomHelpers.button('Disabled', function (evt) {
graph.clearSelection(); graph.clearSelection();
graph.setEnabled(false); graph.setEnabled(false);
graph.setTooltips(false); graph.setTooltips(false);
@ -128,48 +123,37 @@ const Template = ({ label, ...args }) => {
// specification for more functions to extend (eg. // specification for more functions to extend (eg.
// isSelectable). // isSelectable).
const oldDisconnectable = graph.isCellDisconnectable; const oldDisconnectable = graph.isCellDisconnectable;
graph.isCellDisconnectable = function(cell, terminal, source) { graph.isCellDisconnectable = function (cell, terminal, source) {
return ( return oldDisconnectable.apply(this, arguments) && currentPermission.editEdges;
oldDisconnectable.apply(this, arguments) && currentPermission.editEdges
);
}; };
const oldTerminalPointMovable = graph.isTerminalPointMovable; const oldTerminalPointMovable = graph.isTerminalPointMovable;
graph.isTerminalPointMovable = function(cell) { graph.isTerminalPointMovable = function (cell) {
return ( return oldTerminalPointMovable.apply(this, arguments) && currentPermission.editEdges;
oldTerminalPointMovable.apply(this, arguments) &&
currentPermission.editEdges
);
}; };
const oldBendable = graph.isCellBendable; const oldBendable = graph.isCellBendable;
graph.isCellBendable = function(cell) { graph.isCellBendable = function (cell) {
return oldBendable.apply(this, arguments) && currentPermission.editEdges; return oldBendable.apply(this, arguments) && currentPermission.editEdges;
}; };
const oldLabelMovable = graph.isLabelMovable; const oldLabelMovable = graph.isLabelMovable;
graph.isLabelMovable = function(cell) { graph.isLabelMovable = function (cell) {
return ( return oldLabelMovable.apply(this, arguments) && currentPermission.editEdges;
oldLabelMovable.apply(this, arguments) && currentPermission.editEdges
);
}; };
const oldMovable = graph.isCellMovable; const oldMovable = graph.isCellMovable;
graph.isCellMovable = function(cell) { graph.isCellMovable = function (cell) {
return ( return oldMovable.apply(this, arguments) && currentPermission.editVertices;
oldMovable.apply(this, arguments) && currentPermission.editVertices
);
}; };
const oldResizable = graph.isCellResizable; const oldResizable = graph.isCellResizable;
graph.isCellResizable = function(cell) { graph.isCellResizable = function (cell) {
return ( return oldResizable.apply(this, arguments) && currentPermission.editVertices;
oldResizable.apply(this, arguments) && currentPermission.editVertices
);
}; };
const oldEditable = graph.isCellEditable; const oldEditable = graph.isCellEditable;
graph.isCellEditable = function(cell) { graph.isCellEditable = function (cell) {
return ( return (
(oldEditable.apply(this, arguments) && (oldEditable.apply(this, arguments) &&
cell.isVertex() && cell.isVertex() &&
@ -179,7 +163,7 @@ const Template = ({ label, ...args }) => {
}; };
const oldDeletable = graph.isCellDeletable; const oldDeletable = graph.isCellDeletable;
graph.isCellDeletable = function(cell) { graph.isCellDeletable = function (cell) {
return ( return (
(oldDeletable.apply(this, arguments) && (oldDeletable.apply(this, arguments) &&
cell.isVertex() && cell.isVertex() &&
@ -189,10 +173,8 @@ const Template = ({ label, ...args }) => {
}; };
const oldCloneable = graph.isCellCloneable; const oldCloneable = graph.isCellCloneable;
graph.isCellCloneable = function(cell) { graph.isCellCloneable = function (cell) {
return ( return oldCloneable.apply(this, arguments) && currentPermission.cloneCells;
oldCloneable.apply(this, arguments) && currentPermission.cloneCells
);
}; };
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
@ -212,7 +194,7 @@ const Template = ({ label, ...args }) => {
} }
return div; return div;
} };
class Permission { class Permission {
constructor(locked, createEdges, editEdges, editVertices, cloneCells) { constructor(locked, createEdges, editEdges, editVertices, cloneCells) {
@ -229,4 +211,4 @@ class Permission {
} }
} }
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,28 +1,28 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Connections/PortRefs', title: 'Connections/PortRefs',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxRubberband, Rubberband,
mxPoint, Point,
mxEdgeHandler, EdgeHandler,
mxConstraintHandler, ConstraintHandler,
mxImage, ImageBox,
mxShape, Shape,
mxTriangle, TriangleShape,
mxConstants, Constants,
mxConnectionConstraint, ConnectionConstraint,
mxClient mxClient,
} = mxgraph; } = maxgraph;
mxClient.setImageBasePath('/images'); mxClient.setImageBasePath('/images');
@ -35,22 +35,18 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Replaces the port image // Replaces the port image
mxConstraintHandler.prototype.pointImage = new mxImage( ConstraintHandler.prototype.pointImage = new ImageBox('/images/dot.gif', 10, 10);
'/images/dot.gif',
10,
10
);
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setConnectable(true); graph.setConnectable(true);
// Disables automatic handling of ports. This disables the reset of the // Disables automatic handling of ports. This disables the reset of the
// respective style in mxGraph.cellConnected. Note that this feature may // respective style in Graph.cellConnected. Note that this feature may
// be useful if floating and fixed connections are combined. // be useful if floating and fixed connections are combined.
graph.setPortsEnabled(false); graph.setPortsEnabled(false);
// Enables rubberband selection // Enables rubberband selection
new mxRubberband(graph); new Rubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -94,34 +90,30 @@ const Template = ({ label, ...args }) => {
}; };
// Extends shapes classes to return their ports // Extends shapes classes to return their ports
mxShape.prototype.getPorts = function() { Shape.prototype.getPorts = function () {
return ports; return ports;
}; };
mxTriangle.prototype.getPorts = function() { TriangleShape.prototype.getPorts = function () {
return ports2; return ports2;
}; };
// Disables floating connections (only connections via ports allowed) // Disables floating connections (only connections via ports allowed)
graph.connectionHandler.isConnectableCell = function(cell) { graph.connectionHandler.isConnectableCell = function (cell) {
return false; return false;
}; };
mxEdgeHandler.prototype.isConnectableCell = function(cell) { EdgeHandler.prototype.isConnectableCell = function (cell) {
return graph.connectionHandler.isConnectableCell(cell); return graph.connectionHandler.isConnectableCell(cell);
}; };
// Disables existing port functionality // Disables existing port functionality
graph.view.getTerminalPort = function(state, terminal, source) { graph.view.getTerminalPort = function (state, terminal, source) {
return terminal; return terminal;
}; };
// Returns all possible ports for a given terminal // Returns all possible ports for a given terminal
graph.getAllConnectionConstraints = function(terminal, source) { graph.getAllConnectionConstraints = function (terminal, source) {
if ( if (terminal != null && terminal.shape != null && terminal.shape.stencil != null) {
terminal != null &&
terminal.shape != null &&
terminal.shape.stencil != null
) {
// for stencils with existing constraints... // for stencils with existing constraints...
if (terminal.shape.stencil != null) { if (terminal.shape.stencil != null) {
return terminal.shape.stencil.constraints; return terminal.shape.stencil.constraints;
@ -134,8 +126,8 @@ const Template = ({ label, ...args }) => {
for (const id in ports) { for (const id in ports) {
const port = ports[id]; const port = ports[id];
const cstr = new mxConnectionConstraint( const cstr = new ConnectionConstraint(
new mxPoint(port.x, port.y), new Point(port.x, port.y),
port.perimeter port.perimeter
); );
cstr.id = id; cstr.id = id;
@ -150,16 +142,9 @@ const Template = ({ label, ...args }) => {
}; };
// Sets the port for the given connection // Sets the port for the given connection
graph.setConnectionConstraint = function( graph.setConnectionConstraint = function (edge, terminal, source, constraint) {
edge,
terminal,
source,
constraint
) {
if (constraint != null) { if (constraint != null) {
const key = source const key = source ? 'sourcePort' : 'targetPort';
? 'sourcePort'
: 'targetPort';
if (constraint == null || constraint.id == null) { if (constraint == null || constraint.id == null) {
this.setCellStyles(key, null, [edge]); this.setCellStyles(key, null, [edge]);
@ -170,14 +155,12 @@ const Template = ({ label, ...args }) => {
}; };
// Returns the port for the given connection // Returns the port for the given connection
graph.getConnectionConstraint = function(edge, terminal, source) { graph.getConnectionConstraint = function (edge, terminal, source) {
const key = source const key = source ? 'sourcePort' : 'targetPort';
? 'sourcePort'
: 'targetPort';
const id = edge.style[key]; const id = edge.style[key];
if (id != null) { if (id != null) {
const c = new mxConnectionConstraint(null, null); const c = new ConnectionConstraint(null, null);
c.id = id; c.id = id;
return c; return c;
@ -188,15 +171,12 @@ const Template = ({ label, ...args }) => {
// Returns the actual point for a port by redirecting the constraint to the port // Returns the actual point for a port by redirecting the constraint to the port
const graphGetConnectionPoint = graph.getConnectionPoint; const graphGetConnectionPoint = graph.getConnectionPoint;
graph.getConnectionPoint = function(vertex, constraint) { graph.getConnectionPoint = function (vertex, constraint) {
if (constraint.id != null && vertex != null && vertex.shape != null) { if (constraint.id != null && vertex != null && vertex.shape != null) {
const port = vertex.shape.getPorts()[constraint.id]; const port = vertex.shape.getPorts()[constraint.id];
if (port != null) { if (port != null) {
constraint = new mxConnectionConstraint( constraint = new ConnectionConstraint(new Point(port.x, port.y), port.perimeter);
new mxPoint(port.x, port.y),
port.perimeter
);
} }
} }
@ -227,22 +207,8 @@ const Template = ({ label, ...args }) => {
60, 60,
'shape=triangle;perimeter=trianglePerimeter;direction=south' 'shape=triangle;perimeter=trianglePerimeter;direction=south'
); );
const e1 = graph.insertEdge( const e1 = graph.insertEdge(parent, null, '', v1, v2, 'sourcePort=s;targetPort=nw');
parent, const e2 = graph.insertEdge(parent, null, '', v1, v3, 'sourcePort=e;targetPort=out3');
null,
'',
v1,
v2,
'sourcePort=s;targetPort=nw'
);
const e2 = graph.insertEdge(
parent,
null,
'',
v1,
v3,
'sourcePort=e;targetPort=out3'
);
} finally { } finally {
// Updates the display // Updates the display
graph.getModel().endUpdate(); graph.getModel().endUpdate();
@ -251,10 +217,10 @@ const Template = ({ label, ...args }) => {
// Comming soon... Integration with orthogonal edge style // Comming soon... Integration with orthogonal edge style
// Sets default edge style to use port constraints (needs to be moved up when uncommented) // Sets default edge style to use port constraints (needs to be moved up when uncommented)
// graph.getStylesheet().getDefaultEdgeStyle()['edgeStyle'] = 'orthogonalEdgeStyle'; // graph.getStylesheet().getDefaultEdgeStyle()['edgeStyle'] = 'orthogonalEdgeStyle';
/* let mxUtilsGetPortConstraints = mxUtils.getPortConstraints; /* let mxUtilsGetPortConstraints = utils.getPortConstraints;
mxUtils.getPortConstraints = function(terminal, edge, source, defaultValue) utils.getPortConstraints = function(terminal, edge, source, defaultValue)
{ {
let key = (source) ? mxConstants.STYLE_SOURCE_PORT : mxConstants.STYLE_TARGET_PORT; let key = (source) ? Constants.STYLE_SOURCE_PORT : Constants.STYLE_TARGET_PORT;
let id = edge.style[key]; let id = edge.style[key];
let port = terminal.shape.getPorts()[id]; let port = terminal.shape.getPorts()[id];
@ -272,11 +238,11 @@ const Template = ({ label, ...args }) => {
{ {
let edge = graph.createEdge(null, null, null, null, null); let edge = graph.createEdge(null, null, null, null, null);
return new mxCellState(this.graph.view, edge, this.graph.getCellStyle(edge)); return new CellState(this.graph.view, edge, this.graph.getCellStyle(edge));
}; };
*/ */
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,19 +8,13 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Rubberband, Constants, mxRadialTreeLayout, Perimeter } = maxgraph;
mxGraph,
mxRubberband,
mxConstants,
mxRadialTreeLayout,
mxPerimeter
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -31,15 +25,14 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Adds rubberband selection // Adds rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Changes the default vertex style in-place // Changes the default vertex style in-place
let style = graph.getStylesheet().getDefaultVertexStyle(); let style = graph.getStylesheet().getDefaultVertexStyle();
style.perimiter = mxPerimeter.RectanglePerimeter; style.perimiter = Perimeter.RectanglePerimeter;
style.gradientColor = 'white'; style.gradientColor = 'white';
style.perimeterSpacing = 6; style.perimeterSpacing = 6;
style.rounded = true; style.rounded = true;
@ -100,6 +93,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,24 +1,24 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Labels/SecondLabel', title: 'Labels/SecondLabel',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxRectangleShape, RectangleShape,
mxDomHelpers, mxDomHelpers,
mxText, Text,
mxPoint, Point,
mxRectangle, Rectangle,
mxConstants Constants,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -32,19 +32,14 @@ const Template = ({ label, ...args }) => {
div.appendChild(container); div.appendChild(container);
// Simple solution to add additional text to the rectangle shape definition: // Simple solution to add additional text to the rectangle shape definition:
(function() { (function () {
const mxRectangleShapeIsHtmlAllowed = const mxRectangleShapeIsHtmlAllowed = RectangleShape.prototype.isHtmlAllowed;
mxRectangleShape.prototype.isHtmlAllowed; RectangleShape.prototype.isHtmlAllowed = function () {
mxRectangleShape.prototype.isHtmlAllowed = function() { return mxRectangleShapeIsHtmlAllowed.apply(this, arguments) && this.state == null;
return (
mxRectangleShapeIsHtmlAllowed.apply(this, arguments) &&
this.state == null
);
}; };
const mxRectangleShapePaintForeground = const mxRectangleShapePaintForeground = RectangleShape.prototype.paintForeground;
mxRectangleShape.prototype.paintForeground; RectangleShape.prototype.paintForeground = function (c, x, y, w, h) {
mxRectangleShape.prototype.paintForeground = function(c, x, y, w, h) {
if ( if (
this.state != null && this.state != null &&
this.state.cell.geometry != null && this.state.cell.geometry != null &&
@ -59,17 +54,17 @@ const Template = ({ label, ...args }) => {
})(); })();
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Disables the folding icon // Disables the folding icon
graph.isCellFoldable = function(cell) { graph.isCellFoldable = function (cell) {
return false; return false;
}; };
let secondLabelVisible = true; let secondLabelVisible = true;
// Hook for returning shape number for a given cell // Hook for returning shape number for a given cell
graph.getSecondLabel = function(cell) { graph.getSecondLabel = function (cell) {
if (!cell.isEdge()) { if (!cell.isEdge()) {
// Possible to return any string here // Possible to return any string here
return `The ID of this cell is ${cell.id}`; return `The ID of this cell is ${cell.id}`;
@ -82,7 +77,7 @@ const Template = ({ label, ...args }) => {
// Overrides method to hide relative child vertices // Overrides method to hide relative child vertices
// TODO this function is not used // TODO this function is not used
const isVisible = function() { const isVisible = function () {
return ( return (
!cell.isVertex() || !cell.isVertex() ||
cell.geometry == null || cell.geometry == null ||
@ -93,7 +88,7 @@ const Template = ({ label, ...args }) => {
// Creates the shape for the shape number and puts it into the draw pane // Creates the shape for the shape number and puts it into the draw pane
const { redrawShape } = graph.cellRenderer; const { redrawShape } = graph.cellRenderer;
graph.cellRenderer.redrawShape = function(state, force, rendering) { graph.cellRenderer.redrawShape = function (state, force, rendering) {
const result = redrawShape.apply(this, arguments); const result = redrawShape.apply(this, arguments);
if ( if (
@ -104,28 +99,24 @@ const Template = ({ label, ...args }) => {
) { ) {
const secondLabel = graph.getSecondLabel(state.cell); const secondLabel = graph.getSecondLabel(state.cell);
if ( if (secondLabel != null && state.shape != null && state.secondLabel == null) {
secondLabel != null && state.secondLabel = new Text(
state.shape != null &&
state.secondLabel == null
) {
state.secondLabel = new mxText(
secondLabel, secondLabel,
new mxRectangle(), new Rectangle(),
mxConstants.ALIGN_LEFT, Constants.ALIGN_LEFT,
mxConstants.ALIGN_BOTTOM Constants.ALIGN_BOTTOM
); );
// Styles the label // Styles the label
state.secondLabel.color = 'black'; state.secondLabel.color = 'black';
state.secondLabel.family = 'Verdana'; state.secondLabel.family = 'Verdana';
state.secondLabel.size = 8; state.secondLabel.size = 8;
state.secondLabel.fontStyle = mxConstants.FONT_ITALIC; state.secondLabel.fontStyle = Constants.FONT_ITALIC;
state.secondLabel.background = 'yellow'; state.secondLabel.background = 'yellow';
state.secondLabel.border = 'black'; state.secondLabel.border = 'black';
state.secondLabel.valign = 'bottom'; state.secondLabel.valign = 'bottom';
state.secondLabel.dialect = state.shape.dialect; state.secondLabel.dialect = state.shape.dialect;
state.secondLabel.dialect = mxConstants.DIALECT_STRICTHTML; state.secondLabel.dialect = Constants.DIALECT_STRICTHTML;
state.secondLabel.wrap = true; state.secondLabel.wrap = true;
graph.cellRenderer.initializeLabel(state, state.secondLabel); graph.cellRenderer.initializeLabel(state, state.secondLabel);
} }
@ -133,7 +124,7 @@ const Template = ({ label, ...args }) => {
if (state.secondLabel != null) { if (state.secondLabel != null) {
const scale = graph.getView().getScale(); const scale = graph.getView().getScale();
const bounds = new mxRectangle( const bounds = new Rectangle(
state.x + state.width - 8 * scale, state.x + state.width - 8 * scale,
state.y + 8 * scale, state.y + 8 * scale,
35, 35,
@ -151,7 +142,7 @@ const Template = ({ label, ...args }) => {
// Destroys the shape number // Destroys the shape number
const { destroy } = graph.cellRenderer; const { destroy } = graph.cellRenderer;
graph.cellRenderer.destroy = function(state) { graph.cellRenderer.destroy = function (state) {
destroy.apply(this, arguments); destroy.apply(this, arguments);
if (state.secondLabel != null) { if (state.secondLabel != null) {
@ -160,7 +151,7 @@ const Template = ({ label, ...args }) => {
} }
}; };
graph.cellRenderer.getShapesForState = function(state) { graph.cellRenderer.getShapesForState = function (state) {
return [state.shape, state.text, state.secondLabel, state.control]; return [state.shape, state.text, state.secondLabel, state.control];
}; };
@ -186,7 +177,7 @@ const Template = ({ label, ...args }) => {
'align=left;verticalAlign=top;labelBackgroundColor=red;labelBorderColor=black', 'align=left;verticalAlign=top;labelBackgroundColor=red;labelBorderColor=black',
true true
); );
v11.geometry.offset = new mxPoint(-8, -8); v11.geometry.offset = new Point(-8, -8);
const v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30); const v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
// Another alternative solution of creating a second label as a relative child vertex // Another alternative solution of creating a second label as a relative child vertex
// but this time with an automatic size so that the cell is actually selectable and // but this time with an automatic size so that the cell is actually selectable and
@ -202,7 +193,7 @@ const Template = ({ label, ...args }) => {
'align=left;verticalAlign=top;fillColor=red;rounded=1;spacingLeft=4;spacingRight=4', 'align=left;verticalAlign=top;fillColor=red;rounded=1;spacingLeft=4;spacingRight=4',
true true
); );
v21.geometry.offset = new mxPoint(-8, -8); v21.geometry.offset = new Point(-8, -8);
graph.updateCellSize(v21); graph.updateCellSize(v21);
const e1 = graph.insertEdge(parent, null, '', v1, v2); const e1 = graph.insertEdge(parent, null, '', v1, v2);
} finally { } finally {
@ -215,7 +206,7 @@ const Template = ({ label, ...args }) => {
// Adds a button to execute the layout // Adds a button to execute the layout
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Toggle Child Vertices', function(evt) { mxDomHelpers.button('Toggle Child Vertices', function (evt) {
relativeChildVerticesVisible = !relativeChildVerticesVisible; relativeChildVerticesVisible = !relativeChildVerticesVisible;
graph.refresh(); graph.refresh();
}) })
@ -223,13 +214,13 @@ const Template = ({ label, ...args }) => {
// Adds a button to execute the layout // Adds a button to execute the layout
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Toggle IDs', function(evt) { mxDomHelpers.button('Toggle IDs', function (evt) {
secondLabelVisible = !secondLabelVisible; secondLabelVisible = !secondLabelVisible;
graph.refresh(); graph.refresh();
}) })
); );
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -6,16 +6,11 @@ export default {
title: 'Shapes/Shape', title: 'Shapes/Shape',
argTypes: { argTypes: {
...globalTypes, ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, CylinderShape, Constants, CellRenderer } = maxgraph;
mxGraph,
mxCylinder,
mxConstants,
mxCellRenderer
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -36,17 +31,17 @@ const Template = ({ label, ...args }) => {
The code below defines the shape. The BoxShape function The code below defines the shape. The BoxShape function
it the constructor which creates a new object instance. it the constructor which creates a new object instance.
The next lines use an mxCylinder instance to augment the The next lines use an CylinderShape instance to augment the
prototype of the shape ("inheritance") and reset the prototype of the shape ("inheritance") and reset the
constructor to the topmost function of the c'tor chain. constructor to the topmost function of the c'tor chain.
*/ */
class BoxShape extends mxCylinder { class BoxShape extends CylinderShape {
// Defines the extrusion of the box as a "static class variable" // Defines the extrusion of the box as a "static class variable"
extrude = 10; extrude = 10;
/* /*
Next, the mxCylinder's redrawPath method is "overridden". Next, the CylinderShape's redrawPath method is "overridden".
This method has a isForeground argument to separate two This method has a isForeground argument to separate two
paths, one for the background (which must be closed and paths, one for the background (which must be closed and
might be filled) and one for the foreground, which is might be filled) and one for the foreground, which is
@ -85,10 +80,10 @@ const Template = ({ label, ...args }) => {
} }
} }
} }
mxCellRenderer.registerShape('box', BoxShape); CellRenderer.registerShape('box', BoxShape);
// Creates the graph inside the DOM node. // Creates the graph inside the DOM node.
const graph = new mxGraph(container); const graph = new Graph(container);
// Disables basic selection and cell handling // Disables basic selection and cell handling
graph.setEnabled(false); graph.setEnabled(false);
@ -123,6 +118,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,5 +1,5 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { load } from "@mxgraph/core/src/util/network/mxXmlRequest"; import { load } from '@mxgraph/core/src/util/network/mxXmlRequest';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -9,33 +9,33 @@ export default {
...globalTypes, ...globalTypes,
contextMenu: { contextMenu: {
type: 'boolean', type: 'boolean',
defaultValue: false defaultValue: false,
}, },
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxConnectionHandler, ConnectionHandler,
mxDomHelpers, mxDomHelpers,
mxEdgeHandler, EdgeHandler,
mxEvent, InternalEvent,
mxPoint, Point,
mxCellHighlight, CellHighlight,
mxConstants, Constants,
mxVertexHandler, VertexHandler,
mxRubberband, Rubberband,
mxShape, Shape,
mxStencil, StencilShape,
mxStencilRegistry, StencilRegistry,
mxCellRenderer, CellRenderer,
mxUtils utils,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -49,31 +49,31 @@ const Template = ({ label, ...args }) => {
div.appendChild(container); div.appendChild(container);
// Sets the global shadow color // Sets the global shadow color
mxConstants.SHADOWCOLOR = '#C0C0C0'; Constants.SHADOWCOLOR = '#C0C0C0';
mxConstants.SHADOW_OPACITY = 0.5; Constants.SHADOW_OPACITY = 0.5;
mxConstants.SHADOW_OFFSET_X = 4; Constants.SHADOW_OFFSET_X = 4;
mxConstants.SHADOW_OFFSET_Y = 4; Constants.SHADOW_OFFSET_Y = 4;
mxConstants.HANDLE_FILLCOLOR = '#99ccff'; Constants.HANDLE_FILLCOLOR = '#99ccff';
mxConstants.HANDLE_STROKECOLOR = '#0088cf'; Constants.HANDLE_STROKECOLOR = '#0088cf';
mxConstants.VERTEX_SELECTION_COLOR = '#00a8ff'; Constants.VERTEX_SELECTION_COLOR = '#00a8ff';
// Enables connections along the outline // Enables connections along the outline
mxConnectionHandler.prototype.outlineConnect = true; ConnectionHandler.prototype.outlineConnect = true;
mxEdgeHandler.prototype.manageLabelHandle = true; EdgeHandler.prototype.manageLabelHandle = true;
mxEdgeHandler.prototype.outlineConnect = true; EdgeHandler.prototype.outlineConnect = true;
mxCellHighlight.prototype.keepOnTop = true; CellHighlight.prototype.keepOnTop = true;
// Enable rotation handle // Enable rotation handle
mxVertexHandler.prototype.rotationEnabled = true; VertexHandler.prototype.rotationEnabled = true;
// Uses the shape for resize previews // Uses the shape for resize previews
mxVertexHandler.prototype.createSelectionShape = function(bounds) { VertexHandler.prototype.createSelectionShape = function (bounds) {
const key = this.state.style.shape; const key = this.state.style.shape;
const stencil = mxStencilRegistry.getStencil(key); const stencil = StencilRegistry.getStencil(key);
let shape = null; let shape = null;
if (stencil != null) { if (stencil != null) {
shape = new mxShape(stencil); shape = new Shape(stencil);
shape.apply(this.state); shape.apply(this.state);
} else { } else {
shape = new this.state.shape.constructor(); shape = new this.state.shape.constructor();
@ -81,7 +81,7 @@ const Template = ({ label, ...args }) => {
shape.outline = true; shape.outline = true;
shape.bounds = bounds; shape.bounds = bounds;
shape.stroke = mxConstants.HANDLE_STROKECOLOR; shape.stroke = Constants.HANDLE_STROKECOLOR;
shape.strokewidth = this.getSelectionStrokeWidth(); shape.strokewidth = this.getSelectionStrokeWidth();
shape.isDashed = this.isSelectionDashed(); shape.isDashed = this.isSelectionDashed();
shape.isShadow = false; shape.isShadow = false;
@ -92,7 +92,7 @@ const Template = ({ label, ...args }) => {
// Defines a custom stencil via the canvas API as defined here: // Defines a custom stencil via the canvas API as defined here:
// http://jgraph.github.io/mxgraph/docs/js-api/files/util/mxXmlCanvas2D-js.html // http://jgraph.github.io/mxgraph/docs/js-api/files/util/mxXmlCanvas2D-js.html
class CustomShape extends mxShape { class CustomShape extends Shape {
paintBackground(c, x, y, w, h) { paintBackground(c, x, y, w, h) {
c.translate(x, y); c.translate(x, y);
@ -122,7 +122,7 @@ const Template = ({ label, ...args }) => {
} }
// Replaces existing actor shape // Replaces existing actor shape
mxCellRenderer.registerShape('customShape', CustomShape); CellRenderer.registerShape('customShape', CustomShape);
// Loads the stencils into the registry // Loads the stencils into the registry
const req = load('stencils.xml'); const req = load('stencils.xml');
@ -130,26 +130,22 @@ const Template = ({ label, ...args }) => {
let shape = root.firstChild; let shape = root.firstChild;
while (shape != null) { while (shape != null) {
if (shape.nodeType === mxConstants.NODETYPE_ELEMENT) { if (shape.nodeType === Constants.NODETYPE_ELEMENT) {
mxStencilRegistry.addStencil( StencilRegistry.addStencil(shape.getAttribute('name'), new StencilShape(shape));
shape.getAttribute('name'),
new mxStencil(shape)
);
} }
shape = shape.nextSibling; shape = shape.nextSibling;
} }
if (!args.contextMenu) if (!args.contextMenu) InternalEvent.disableContextMenu(container);
mxEvent.disableContextMenu(container);
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
graph.setConnectable(true); graph.setConnectable(true);
graph.setTooltips(true); graph.setTooltips(true);
graph.setPanning(true); graph.setPanning(true);
graph.getTooltipForCell = function(cell) { graph.getTooltipForCell = function (cell) {
if (cell != null) { if (cell != null) {
return cell.style; return cell.style;
} }
@ -166,8 +162,7 @@ const Template = ({ label, ...args }) => {
style.shadow = '1'; style.shadow = '1';
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This // Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
@ -176,40 +171,13 @@ const Template = ({ label, ...args }) => {
// Adds cells to the model in a single step // Adds cells to the model in a single step
graph.getModel().beginUpdate(); graph.getModel().beginUpdate();
try { try {
const v1 = graph.insertVertex( const v1 = graph.insertVertex(parent, null, 'A1', 20, 20, 40, 80, 'shape=and');
parent, const v2 = graph.insertVertex(parent, null, 'A2', 20, 220, 40, 80, 'shape=and');
null, const v3 = graph.insertVertex(parent, null, 'X1', 160, 110, 80, 80, 'shape=xor');
'A1',
20,
20,
40,
80,
'shape=and'
);
const v2 = graph.insertVertex(
parent,
null,
'A2',
20,
220,
40,
80,
'shape=and'
);
const v3 = graph.insertVertex(
parent,
null,
'X1',
160,
110,
80,
80,
'shape=xor'
);
const e1 = graph.insertEdge(parent, null, '', v1, v3); const e1 = graph.insertEdge(parent, null, '', v1, v3);
e1.geometry.points = [new mxPoint(90, 60), new mxPoint(90, 130)]; e1.geometry.points = [new Point(90, 60), new Point(90, 130)];
const e2 = graph.insertEdge(parent, null, '', v2, v3); const e2 = graph.insertEdge(parent, null, '', v2, v3);
e2.geometry.points = [new mxPoint(90, 260), new mxPoint(90, 170)]; e2.geometry.points = [new Point(90, 260), new Point(90, 170)];
const v4 = graph.insertVertex( const v4 = graph.insertVertex(
parent, parent,
@ -242,9 +210,9 @@ const Template = ({ label, ...args }) => {
'shape=xor;flipH=1' 'shape=xor;flipH=1'
); );
const e3 = graph.insertEdge(parent, null, '', v4, v6); const e3 = graph.insertEdge(parent, null, '', v4, v6);
e3.geometry.points = [new mxPoint(490, 60), new mxPoint(130, 130)]; e3.geometry.points = [new Point(490, 60), new Point(130, 130)];
const e4 = graph.insertEdge(parent, null, '', v5, v6); const e4 = graph.insertEdge(parent, null, '', v5, v6);
e4.geometry.points = [new mxPoint(490, 260), new mxPoint(130, 170)]; e4.geometry.points = [new Point(490, 260), new Point(130, 170)];
const v7 = graph.insertVertex( const v7 = graph.insertVertex(
parent, parent,
@ -257,12 +225,12 @@ const Template = ({ label, ...args }) => {
'shape=or;direction=south' 'shape=or;direction=south'
); );
const e5 = graph.insertEdge(parent, null, '', v6, v7); const e5 = graph.insertEdge(parent, null, '', v6, v7);
e5.geometry.points = [new mxPoint(310, 150)]; e5.geometry.points = [new Point(310, 150)];
const e6 = graph.insertEdge(parent, null, '', v3, v7); const e6 = graph.insertEdge(parent, null, '', v3, v7);
e6.geometry.points = [new mxPoint(270, 150)]; e6.geometry.points = [new Point(270, 150)];
const e7 = graph.insertEdge(parent, null, '', v7, v5); const e7 = graph.insertEdge(parent, null, '', v7, v5);
e7.geometry.points = [new mxPoint(290, 370)]; e7.geometry.points = [new Point(290, 370)];
} finally { } finally {
// Updates the display // Updates the display
graph.getModel().endUpdate(); graph.getModel().endUpdate();
@ -272,13 +240,13 @@ const Template = ({ label, ...args }) => {
div.appendChild(buttons); div.appendChild(buttons);
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('FlipH', function() { mxDomHelpers.button('FlipH', function () {
graph.toggleCellStyles('flipH'); graph.toggleCellStyles('flipH');
}) })
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('FlipV', function() { mxDomHelpers.button('FlipV', function () {
graph.toggleCellStyles('flipV'); graph.toggleCellStyles('flipV');
}) })
); );
@ -289,7 +257,7 @@ const Template = ({ label, ...args }) => {
buttons.appendChild(document.createTextNode('\u00a0')); buttons.appendChild(document.createTextNode('\u00a0'));
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Rotate', function() { mxDomHelpers.button('Rotate', function () {
const cell = graph.getSelectionCell(); const cell = graph.getSelectionCell();
if (cell != null) { if (cell != null) {
@ -311,9 +279,7 @@ const Template = ({ label, ...args }) => {
const state = graph.view.getState(cell); const state = graph.view.getState(cell);
if (state != null) { if (state != null) {
let dir = let dir = state.style.direction || 'east'; /* default */
state.style.direction ||
'east'; /* default */
if (dir === 'east') { if (dir === 'east') {
dir = 'south'; dir = 'south';
@ -341,17 +307,17 @@ const Template = ({ label, ...args }) => {
buttons.appendChild(document.createTextNode('\u00a0')); buttons.appendChild(document.createTextNode('\u00a0'));
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('And', function() { mxDomHelpers.button('And', function () {
graph.setCellStyles('shape', 'and'); graph.setCellStyles('shape', 'and');
}) })
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Or', function() { mxDomHelpers.button('Or', function () {
graph.setCellStyles('shape', 'or'); graph.setCellStyles('shape', 'or');
}) })
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Xor', function() { mxDomHelpers.button('Xor', function () {
graph.setCellStyles('shape', 'xor'); graph.setCellStyles('shape', 'xor');
}) })
); );
@ -362,14 +328,11 @@ const Template = ({ label, ...args }) => {
buttons.appendChild(document.createTextNode('\u00a0')); buttons.appendChild(document.createTextNode('\u00a0'));
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('Style', function() { mxDomHelpers.button('Style', function () {
const cell = graph.getSelectionCell(); const cell = graph.getSelectionCell();
if (cell != null) { if (cell != null) {
const style = mxUtils.prompt( const style = utils.prompt('Style', cell.getStyle());
'Style',
cell.getStyle()
);
if (style != null) { if (style != null) {
graph.getModel().setStyle(cell, style); graph.getModel().setStyle(cell, style);
@ -379,17 +342,17 @@ const Template = ({ label, ...args }) => {
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('+', function() { mxDomHelpers.button('+', function () {
graph.zoomIn(); graph.zoomIn();
}) })
); );
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('-', function() { mxDomHelpers.button('-', function () {
graph.zoomOut(); graph.zoomOut();
}) })
); );
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,21 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Styles/Stylesheet', title: 'Styles/Stylesheet',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, Perimeter, Constants, EdgeStyle } = maxgraph;
mxGraph,
mxPerimeter,
mxConstants,
mxEdgeStyle
} = mxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -26,15 +21,15 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Creates the graph inside the DOM node. // Creates the graph inside the DOM node.
const graph = new mxGraph(container); const graph = new Graph(container);
// Disables basic selection and cell handling // Disables basic selection and cell handling
graph.setEnabled(false); graph.setEnabled(false);
// Returns a special label for edges. Note: This does // Returns a special label for edges. Note: This does
// a supercall to use the default implementation. // a supercall to use the default implementation.
graph.getLabel = function(cell) { graph.getLabel = function (cell) {
const label = mxGraph.prototype.getLabel.apply(this, arguments); const label = Graph.prototype.getLabel.apply(this, arguments);
if (cell.isEdge()) { if (cell.isEdge()) {
return `Transfer ${label}`; return `Transfer ${label}`;
@ -44,7 +39,7 @@ const Template = ({ label, ...args }) => {
// Installs a custom global tooltip // Installs a custom global tooltip
graph.setTooltips(true); graph.setTooltips(true);
graph.getTooltip = function(state) { graph.getTooltip = function (state) {
const { cell } = state; const { cell } = state;
const model = this.getModel(); const model = this.getModel();
@ -59,27 +54,27 @@ const Template = ({ label, ...args }) => {
// Creates the default style for vertices // Creates the default style for vertices
let style = []; let style = [];
style.shape = mxConstants.SHAPE_RECTANGLE; style.shape = Constants.SHAPE_RECTANGLE;
style.perimiter = mxPerimeter.RectanglePerimeter; style.perimiter = Perimeter.RectanglePerimeter;
style.strokeColor = 'gray'; style.strokeColor = 'gray';
style.rounded = true; style.rounded = true;
style.fillColor = '#EEEEEE'; style.fillColor = '#EEEEEE';
style.gradientColor = 'white'; style.gradientColor = 'white';
style.fontColor = '#774400'; style.fontColor = '#774400';
style.align = mxConstants.ALIGN_CENTER; style.align = Constants.ALIGN_CENTER;
style.verticalAlign = mxConstants.ALIGN_MIDDLE; style.verticalAlign = Constants.ALIGN_MIDDLE;
style.fontSize = '12'; style.fontSize = '12';
style.fontStyle = 1; style.fontStyle = 1;
graph.getStylesheet().putDefaultVertexStyle(style); graph.getStylesheet().putDefaultVertexStyle(style);
// Creates the default style for edges // Creates the default style for edges
style = []; style = [];
style.shape = mxConstants.SHAPE_CONNECTOR; style.shape = Constants.SHAPE_CONNECTOR;
style.strokeColor = '#6482B9'; style.strokeColor = '#6482B9';
style.align = mxConstants.ALIGN_CENTER; style.align = Constants.ALIGN_CENTER;
style.verticalAlign = mxConstants.ALIGN_MIDDLE; style.verticalAlign = Constants.ALIGN_MIDDLE;
style.edge = mxEdgeStyle.ElbowConnector; style.edge = EdgeStyle.ElbowConnector;
style.endArrow = mxConstants.ARROW_CLASSIC; style.endArrow = Constants.ARROW_CLASSIC;
style.fontSize = '10'; style.fontSize = '10';
graph.getStylesheet().putDefaultEdgeStyle(style); graph.getStylesheet().putDefaultEdgeStyle(style);
@ -90,51 +85,11 @@ const Template = ({ label, ...args }) => {
// Adds cells to the model in a single step // Adds cells to the model in a single step
graph.getModel().beginUpdate(); graph.getModel().beginUpdate();
try { try {
const v1 = graph.insertVertex( const v1 = graph.insertVertex(parent, null, 'Interval 1', 20, 20, 180, 30);
parent, const v2 = graph.insertVertex(parent, null, 'Interval 2', 140, 80, 280, 30);
null, const v3 = graph.insertVertex(parent, null, 'Interval 3', 200, 140, 360, 30);
'Interval 1', const v4 = graph.insertVertex(parent, null, 'Interval 4', 480, 200, 120, 30);
20, const v5 = graph.insertVertex(parent, null, 'Interval 5', 60, 260, 400, 30);
20,
180,
30
);
const v2 = graph.insertVertex(
parent,
null,
'Interval 2',
140,
80,
280,
30
);
const v3 = graph.insertVertex(
parent,
null,
'Interval 3',
200,
140,
360,
30
);
const v4 = graph.insertVertex(
parent,
null,
'Interval 4',
480,
200,
120,
30
);
const v5 = graph.insertVertex(
parent,
null,
'Interval 5',
60,
260,
400,
30
);
const e1 = graph.insertEdge(parent, null, '1', v1, v2); const e1 = graph.insertEdge(parent, null, '1', v1, v2);
e1.getGeometry().points = [{ x: 160, y: 60 }]; e1.getGeometry().points = [{ x: 160, y: 60 }];
const e2 = graph.insertEdge(parent, null, '2', v1, v5); const e2 = graph.insertEdge(parent, null, '2', v1, v5);
@ -151,6 +106,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,29 +1,29 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Layouts/SwimLanes', title: 'Layouts/SwimLanes',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxEditor, mxEditor,
mxConnectionHandler, ConnectionHandler,
mxImage, ImageBox,
mxPerimeter, Perimeter,
mxPoint, Point,
mxConstants, Constants,
mxCloneUtils, CloneUtils,
mxEdgeStyle, EdgeStyle,
mxEvent, InternalEvent,
mxSwimlaneManager, SwimlaneManager,
mxStackLayout, StackLayout,
mxLayoutManager LayoutManager,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -35,16 +35,12 @@ const Template = ({ label, ...args }) => {
// Defines an icon for creating new connections in the connection handler. // Defines an icon for creating new connections in the connection handler.
// This will automatically disable the highlighting of the source vertex. // This will automatically disable the highlighting of the source vertex.
mxConnectionHandler.prototype.connectImage = new mxImage( ConnectionHandler.prototype.connectImage = new ImageBox('images/connector.gif', 16, 16);
'images/connector.gif',
16,
16
);
// Creates a wrapper editor around a new graph inside // Creates a wrapper editor around a new graph inside
// the given container using an XML config for the // the given container using an XML config for the
// keyboard bindings // keyboard bindings
// const config = mxUtils // const config = utils
// .load('editors/config/keyhandler-commons.xml') // .load('editors/config/keyhandler-commons.xml')
// .getDocumentElement(); // .getDocumentElement();
// const editor = new mxEditor(config); // const editor = new mxEditor(config);
@ -55,13 +51,13 @@ const Template = ({ label, ...args }) => {
// Auto-resizes the container // Auto-resizes the container
graph.border = 80; graph.border = 80;
graph.getView().translate = new mxPoint(graph.border / 2, graph.border / 2); graph.getView().translate = new Point(graph.border / 2, graph.border / 2);
graph.setResizeContainer(true); graph.setResizeContainer(true);
graph.graphHandler.setRemoveCellsFromParent(false); graph.graphHandler.setRemoveCellsFromParent(false);
// Changes the default vertex style in-place // Changes the default vertex style in-place
let style = graph.getStylesheet().getDefaultVertexStyle(); let style = graph.getStylesheet().getDefaultVertexStyle();
style.shape = mxConstants.SHAPE_SWIMLANE; style.shape = Constants.SHAPE_SWIMLANE;
style.verticalAlign = 'middle'; style.verticalAlign = 'middle';
style.labelBackgroundColor = 'white'; style.labelBackgroundColor = 'white';
style.fontSize = 11; style.fontSize = 11;
@ -71,8 +67,8 @@ const Template = ({ label, ...args }) => {
style.strokeColor = 'black'; style.strokeColor = 'black';
delete style.fillColor; delete style.fillColor;
style = mxCloneUtils.clone(style); style = CloneUtils.clone(style);
style.shape = mxConstants.SHAPE_RECTANGLE; style.shape = Constants.SHAPE_RECTANGLE;
style.fontSize = 10; style.fontSize = 10;
style.rounded = true; style.rounded = true;
style.horizontal = true; style.horizontal = true;
@ -81,23 +77,23 @@ const Template = ({ label, ...args }) => {
style.labelBackgroundColor = 'none'; style.labelBackgroundColor = 'none';
graph.getStylesheet().putCellStyle('process', style); graph.getStylesheet().putCellStyle('process', style);
style = mxCloneUtils.clone(style); style = CloneUtils.clone(style);
style.shape = mxConstants.SHAPE_ELLIPSE; style.shape = Constants.SHAPE_ELLIPSE;
style.perimiter = mxPerimeter.EllipsePerimeter; style.perimiter = Perimeter.EllipsePerimeter;
delete style.rounded; delete style.rounded;
graph.getStylesheet().putCellStyle('state', style); graph.getStylesheet().putCellStyle('state', style);
style = mxCloneUtils.clone(style); style = CloneUtils.clone(style);
style.shape = mxConstants.SHAPE_RHOMBUS; style.shape = Constants.SHAPE_RHOMBUS;
style.perimiter = mxPerimeter.RhombusPerimeter; style.perimiter = Perimeter.RhombusPerimeter;
style.verticalAlign = 'top'; style.verticalAlign = 'top';
style.spacingTop = 40; style.spacingTop = 40;
style.spacingRight = 64; style.spacingRight = 64;
graph.getStylesheet().putCellStyle('condition', style); graph.getStylesheet().putCellStyle('condition', style);
style = mxCloneUtils.clone(style); style = CloneUtils.clone(style);
style.shape = mxConstants.SHAPE_DOUBLE_ELLIPSE; style.shape = Constants.SHAPE_DOUBLE_ELLIPSE;
style.perimiter = mxPerimeter.EllipsePerimeter; style.perimiter = Perimeter.EllipsePerimeter;
style.spacingTop = 28; style.spacingTop = 28;
style.fontSize = 14; style.fontSize = 14;
style.fontStyle = 1; style.fontStyle = 1;
@ -105,16 +101,16 @@ const Template = ({ label, ...args }) => {
graph.getStylesheet().putCellStyle('end', style); graph.getStylesheet().putCellStyle('end', style);
style = graph.getStylesheet().getDefaultEdgeStyle(); style = graph.getStylesheet().getDefaultEdgeStyle();
style.edge = mxEdgeStyle.ElbowConnector; style.edge = EdgeStyle.ElbowConnector;
style.endArrow = mxConstants.ARROW_BLOCK; style.endArrow = Constants.ARROW_BLOCK;
style.rounded = true; style.rounded = true;
style.fontColor = 'black'; style.fontColor = 'black';
style.strokeColor = 'black'; style.strokeColor = 'black';
style = mxCloneUtils.clone(style); style = CloneUtils.clone(style);
style.dashed = true; style.dashed = true;
style.endArrow = mxConstants.ARROW_OPEN; style.endArrow = Constants.ARROW_OPEN;
style.startArrow = mxConstants.ARROW_OVAL; style.startArrow = Constants.ARROW_OVAL;
graph.getStylesheet().putCellStyle('crossover', style); graph.getStylesheet().putCellStyle('crossover', style);
// Installs double click on middle control point and // Installs double click on middle control point and
@ -131,13 +127,11 @@ const Template = ({ label, ...args }) => {
// End-states are no valid sources // End-states are no valid sources
const previousIsValidSource = graph.isValidSource; const previousIsValidSource = graph.isValidSource;
graph.isValidSource = function(cell) { graph.isValidSource = function (cell) {
if (previousIsValidSource.apply(this, arguments)) { if (previousIsValidSource.apply(this, arguments)) {
const style = cell.getStyle(); const style = cell.getStyle();
return ( return style == null || !(style == 'end' || style.indexOf('end') == 0);
style == null || !(style == 'end' || style.indexOf('end') == 0)
);
} }
return false; return false;
@ -149,7 +143,7 @@ const Template = ({ label, ...args }) => {
// Note: All states are start states in // Note: All states are start states in
// the example below, so we use the state // the example below, so we use the state
// style below // style below
graph.isValidTarget = function(cell) { graph.isValidTarget = function (cell) {
const style = cell.getStyle(); const style = cell.getStyle();
return ( return (
@ -166,7 +160,7 @@ const Template = ({ label, ...args }) => {
graph.setSplitEnabled(false); graph.setSplitEnabled(false);
// Returns true for valid drop operations // Returns true for valid drop operations
graph.isValidDropTarget = function(target, cells, evt) { graph.isValidDropTarget = function (target, cells, evt) {
if (this.isSplitEnabled() && this.isSplitTarget(target, cells, evt)) { if (this.isSplitEnabled() && this.isSplitTarget(target, cells, evt)) {
return true; return true;
} }
@ -188,13 +182,12 @@ const Template = ({ label, ...args }) => {
return ( return (
!pool && !pool &&
cell != lane && cell != lane &&
((lane && this.isPool(target)) || ((lane && this.isPool(target)) || (cell && this.isPool(target.getParent())))
(cell && this.isPool(target.getParent())))
); );
}; };
// Adds new method for identifying a pool // Adds new method for identifying a pool
graph.isPool = function(cell) { graph.isPool = function (cell) {
const model = this.getModel(); const model = this.getModel();
const parent = cell.getParent(); const parent = cell.getParent();
@ -202,7 +195,7 @@ const Template = ({ label, ...args }) => {
}; };
// Keeps widths on collapse/expand // Keeps widths on collapse/expand
const foldingHandler = function(sender, evt) { const foldingHandler = function (sender, evt) {
const cells = evt.getProperty('cells'); const cells = evt.getProperty('cells');
for (let i = 0; i < cells.length; i++) { for (let i = 0; i < cells.length; i++) {
@ -214,11 +207,11 @@ const Template = ({ label, ...args }) => {
} }
}; };
graph.addListener(mxEvent.FOLD_CELLS, foldingHandler); graph.addListener(InternalEvent.FOLD_CELLS, foldingHandler);
} }
// Changes swimlane orientation while collapsed // Changes swimlane orientation while collapsed
const getStyle = function() { const getStyle = function () {
// TODO super cannot be used here // TODO super cannot be used here
// let style = super.getStyle(); // let style = super.getStyle();
let style; let style;
@ -234,10 +227,10 @@ const Template = ({ label, ...args }) => {
}; };
// Applies size changes to siblings and parents // Applies size changes to siblings and parents
new mxSwimlaneManager(graph); new SwimlaneManager(graph);
// Creates a stack depending on the orientation of the swimlane // Creates a stack depending on the orientation of the swimlane
const layout = new mxStackLayout(graph, false); const layout = new StackLayout(graph, false);
// Makes sure all children fit into the parent swimlane // Makes sure all children fit into the parent swimlane
layout.resizeParent = true; layout.resizeParent = true;
@ -246,14 +239,14 @@ const Template = ({ label, ...args }) => {
layout.fill = true; layout.fill = true;
// Only update the size of swimlanes // Only update the size of swimlanes
layout.isVertexIgnored = function(vertex) { layout.isVertexIgnored = function (vertex) {
return !graph.isSwimlane(vertex); return !graph.isSwimlane(vertex);
}; };
// Keeps the lanes and pools stacked // Keeps the lanes and pools stacked
const layoutMgr = new mxLayoutManager(graph); const layoutMgr = new LayoutManager(graph);
layoutMgr.getLayout = function(cell) { layoutMgr.getLayout = function (cell) {
if ( if (
!cell.isEdge() && !cell.isEdge() &&
cell.getChildCount() > 0 && cell.getChildCount() > 0 &&
@ -271,13 +264,13 @@ const Template = ({ label, ...args }) => {
// is normally the first child of the root (ie. layer 0). // is normally the first child of the root (ie. layer 0).
const parent = graph.getDefaultParent(); const parent = graph.getDefaultParent();
const insertVertex = options => { const insertVertex = (options) => {
const v = graph.insertVertex(options); const v = graph.insertVertex(options);
v.getStyle = getStyle; v.getStyle = getStyle;
return v; return v;
}; };
const insertEdge = options => { const insertEdge = (options) => {
const e = graph.insertEdge(options); const e = graph.insertEdge(options);
e.getStyle = getStyle; e.getStyle = getStyle;
return e; return e;
@ -518,7 +511,7 @@ const Template = ({ label, ...args }) => {
}); });
e.geometry.points = [ e.geometry.points = [
new mxPoint( new Point(
step444.geometry.x + step444.geometry.width / 2, step444.geometry.x + step444.geometry.width / 2,
end3.geometry.y + end3.geometry.height / 2 end3.geometry.y + end3.geometry.height / 2
), ),
@ -544,7 +537,7 @@ const Template = ({ label, ...args }) => {
}); });
e.geometry.points = [ e.geometry.points = [
new mxPoint( new Point(
step33.geometry.x + step33.geometry.width / 2 + 20, step33.geometry.x + step33.geometry.width / 2 + 20,
step11.geometry.y + (step11.geometry.height * 4) / 5 step11.geometry.y + (step11.geometry.height * 4) / 5
), ),
@ -563,6 +556,6 @@ const Template = ({ label, ...args }) => {
}); });
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,19 +1,16 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Misc/Thread', title: 'Misc/Thread',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const { Graph, mxClient } = maxgraph;
mxGraph,
mxClient
} = mxgraph;
mxClient.setImageBasePath('/images'); mxClient.setImageBasePath('/images');
@ -26,7 +23,7 @@ const Template = ({ label, ...args }) => {
container.style.cursor = 'default'; container.style.cursor = 'default';
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Disables basic selection and cell handling // Disables basic selection and cell handling
graph.setEnabled(false); graph.setEnabled(false);
@ -66,6 +63,6 @@ const Template = ({ label, ...args }) => {
f(); f();
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,4 +1,4 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
@ -8,26 +8,26 @@ export default {
...globalTypes, ...globalTypes,
rubberBand: { rubberBand: {
type: 'boolean', type: 'boolean',
defaultValue: true defaultValue: true,
} },
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxRubberband, Rubberband,
mxConnectionHandler, ConnectionHandler,
mxImage, ImageBox,
mxToolbar, mxToolbar,
mxGraphModel, GraphModel,
mxKeyHandler, mxKeyHandler,
mxCell, Cell,
mxGeometry, Geometry,
mxDragSource, DragSource,
mxDomHelpers, mxDomHelpers,
mxGestureUtils GestureUtils,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -42,7 +42,7 @@ const Template = ({ label, ...args }) => {
// Defines an icon for creating new connections in the connection handler. // Defines an icon for creating new connections in the connection handler.
// This will automatically disable the highlighting of the source vertex. // This will automatically disable the highlighting of the source vertex.
mxConnectionHandler.prototype.connectImage = new mxImage( ConnectionHandler.prototype.connectImage = new ImageBox(
'/images/connector.gif', '/images/connector.gif',
16, 16,
16 16
@ -66,12 +66,12 @@ const Template = ({ label, ...args }) => {
// Creates the model and the graph inside the container // Creates the model and the graph inside the container
// using the fastest rendering available on the browser // using the fastest rendering available on the browser
const model = new mxGraphModel(); const model = new GraphModel();
const graph = new mxGraph(container, model); const graph = new Graph(container, model);
graph.dropEnabled = true; graph.dropEnabled = true;
// Matches DnD inside the graph // Matches DnD inside the graph
mxDragSource.prototype.getDropTarget = function(graph, x, y) { DragSource.prototype.getDropTarget = function (graph, x, y) {
let cell = graph.getCellAt(x, y); let cell = graph.getCellAt(x, y);
if (!graph.isValidDropTarget(cell)) { if (!graph.isValidDropTarget(cell)) {
cell = null; cell = null;
@ -86,22 +86,16 @@ const Template = ({ label, ...args }) => {
// Stops editing on enter or escape keypress // Stops editing on enter or escape keypress
const keyHandler = new mxKeyHandler(graph); const keyHandler = new mxKeyHandler(graph);
if (args.rubberBand) if (args.rubberBand) new Rubberband(graph);
new mxRubberband(graph);
const addVertex = (icon, w, h, style) => { const addVertex = (icon, w, h, style) => {
const vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style); const vertex = new Cell(null, new Geometry(0, 0, w, h), style);
vertex.setVertex(true); vertex.setVertex(true);
addToolbarItem(graph, toolbar, vertex, icon); addToolbarItem(graph, toolbar, vertex, icon);
}; };
addVertex( addVertex('/images/swimlane.gif', 120, 160, 'shape=swimlane;startSize=20;');
'/images/swimlane.gif',
120,
160,
'shape=swimlane;startSize=20;'
);
addVertex('/images/rectangle.gif', 100, 40, ''); addVertex('/images/rectangle.gif', 100, 40, '');
addVertex('/images/rounded.gif', 100, 40, 'shape=rounded'); addVertex('/images/rounded.gif', 100, 40, 'shape=rounded');
addVertex('/images/ellipse.gif', 40, 40, 'shape=ellipse'); addVertex('/images/ellipse.gif', 40, 40, 'shape=ellipse');
@ -111,37 +105,30 @@ const Template = ({ label, ...args }) => {
addVertex('/images/actor.gif', 30, 40, 'shape=actor'); addVertex('/images/actor.gif', 30, 40, 'shape=actor');
toolbar.addLine(); toolbar.addLine();
const button = mxDomHelpers.button( const button = mxDomHelpers.button('Create toolbar entry from selection', (evt) => {
'Create toolbar entry from selection', if (!graph.isSelectionEmpty()) {
evt => { // Creates a copy of the selection array to preserve its state
if (!graph.isSelectionEmpty()) { const cells = graph.getSelectionCells();
// Creates a copy of the selection array to preserve its state const bounds = graph.getView().getBounds(cells);
const cells = graph.getSelectionCells();
const bounds = graph.getView().getBounds(cells);
// Function that is executed when the image is dropped on // Function that is executed when the image is dropped on
// the graph. The cell argument points to the cell under // the graph. The cell argument points to the cell under
// the mousepointer if there is one. // the mousepointer if there is one.
const funct = (graph, evt, cell) => { const funct = (graph, evt, cell) => {
graph.stopEditing(false); graph.stopEditing(false);
const pt = graph.getPointForEvent(evt); const pt = graph.getPointForEvent(evt);
const dx = pt.x - bounds.x; const dx = pt.x - bounds.x;
const dy = pt.y - bounds.y; const dy = pt.y - bounds.y;
graph.setSelectionCells(graph.importCells(cells, dx, dy, cell)); graph.setSelectionCells(graph.importCells(cells, dx, dy, cell));
}; };
// Creates the image which is used as the drag icon (preview) // Creates the image which is used as the drag icon (preview)
const img = toolbar.addMode( const img = toolbar.addMode(null, '/images/outline.gif', funct);
null, GestureUtils.makeDraggable(img, graph, funct);
'/images/outline.gif',
funct
);
mxGestureUtils.makeDraggable(img, graph, funct);
}
} }
); });
tbContainer.appendChild(button); tbContainer.appendChild(button);
@ -162,10 +149,10 @@ const Template = ({ label, ...args }) => {
// Creates the image which is used as the drag icon (preview) // Creates the image which is used as the drag icon (preview)
const img = toolbar.addMode(null, image, funct); const img = toolbar.addMode(null, image, funct);
mxGestureUtils.makeDraggable(img, graph, funct); GestureUtils.makeDraggable(img, graph, funct);
} }
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,30 +1,30 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Layouts/Tree', title: 'Layouts/Tree',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxConstants, Constants,
mxCylinder, CylinderShape,
mxCellRenderer, CellRenderer,
mxGraphView, GraphView,
mxImage, ImageBox,
mxClient, mxClient,
mxEdgeStyle, EdgeStyle,
mxKeyHandler, mxKeyHandler,
mxCompactTreeLayout, CompactTreeLayout,
mxLayoutManager, LayoutManager,
mxRectangle, Rectangle,
mxPoint Point,
} = mxgraph; } = maxgraph;
const container = document.createElement('div'); const container = document.createElement('div');
container.style.position = 'relative'; container.style.position = 'relative';
@ -40,7 +40,7 @@ const Template = ({ label, ...args }) => {
Defines a custom shape for the tree node that includes the Defines a custom shape for the tree node that includes the
upper half of the outgoing edge(s). upper half of the outgoing edge(s).
*/ */
class TreeNodeShape extends mxCylinder { class TreeNodeShape extends CylinderShape {
// Defines the length of the upper edge segment. // Defines the length of the upper edge segment.
static segment = 20; static segment = 20;
@ -56,8 +56,7 @@ const Template = ({ label, ...args }) => {
redrawPath(path, x, y, w, h, isForeground) { redrawPath(path, x, y, w, h, isForeground) {
const { graph } = this.state.view; const { graph } = this.state.view;
const hasChildren = const hasChildren = graph.model.getOutgoingEdges(this.state.cell).length > 0;
graph.model.getOutgoingEdges(this.state.cell).length > 0;
if (isForeground) { if (isForeground) {
if (hasChildren) { if (hasChildren) {
@ -75,27 +74,27 @@ const Template = ({ label, ...args }) => {
} }
} }
} }
mxCellRenderer.registerShape('treenode', TreeNodeShape); CellRenderer.registerShape('treenode', TreeNodeShape);
class MyCustomGraphView extends mxGraphView { class MyCustomGraphView extends GraphView {
updateFloatingTerminalPoint(edge, start, end, source) { updateFloatingTerminalPoint(edge, start, end, source) {
// Defines a custom perimeter for the nodes in the tree // Defines a custom perimeter for the nodes in the tree
let pt = null; let pt = null;
if (source) { if (source) {
pt = new mxPoint( pt = new Point(
start.x + start.width / 2, start.x + start.width / 2,
start.y + start.height + TreeNodeShape.segment start.y + start.height + TreeNodeShape.segment
); );
} else { } else {
pt = new mxPoint(start.x + start.width / 2, start.y); pt = new Point(start.x + start.width / 2, start.y);
} }
edge.setAbsoluteTerminalPoint(pt, source); edge.setAbsoluteTerminalPoint(pt, source);
} }
} }
class MyCustomCellRenderer extends mxCellRenderer { class MyCustomCellRenderer extends CellRenderer {
getControlBounds(state) { getControlBounds(state) {
// Defines the position of the folding icon // Defines the position of the folding icon
if (state.control != null) { if (state.control != null) {
@ -104,12 +103,9 @@ const Template = ({ label, ...args }) => {
const h = state.control.bounds.height / oldScale; const h = state.control.bounds.height / oldScale;
const s = state.view.scale; const s = state.view.scale;
return new mxRectangle( return new Rectangle(
state.x + state.width / 2 - (w / 2) * s, state.x + state.width / 2 - (w / 2) * s,
state.y + state.y + state.height + TreeNodeShape.segment * s - (h / 2) * s,
state.height +
TreeNodeShape.segment * s -
(h / 2) * s,
w * s, w * s,
h * s h * s
); );
@ -121,20 +117,12 @@ const Template = ({ label, ...args }) => {
// Make the layout instance accessible by MyCustomGraph // Make the layout instance accessible by MyCustomGraph
let layout; let layout;
class MyCustomGraph extends mxGraph { class MyCustomGraph extends Graph {
// Sets the collapse and expand icons. The values below are the default // Sets the collapse and expand icons. The values below are the default
// values, but this is how to replace them if you need to. // values, but this is how to replace them if you need to.
collapsedImage = new mxImage( collapsedImage = new ImageBox(`${mxClient.imageBasePath}/collapsed.gif`, 9, 9);
`${mxClient.imageBasePath}/collapsed.gif`,
9,
9
);
expandedImage = new mxImage( expandedImage = new ImageBox(`${mxClient.imageBasePath}/expanded.gif`, 9, 9);
`${mxClient.imageBasePath}/expanded.gif`,
9,
9
);
isCellFoldable(cell) { isCellFoldable(cell) {
// Defines the condition for showing the folding icon // Defines the condition for showing the folding icon
@ -171,7 +159,7 @@ const Template = ({ label, ...args }) => {
show = show != null ? show : true; show = show != null ? show : true;
const cells = []; const cells = [];
this.traverse(cell, true, function(vertex) { this.traverse(cell, true, function (vertex) {
if (vertex !== cell) { if (vertex !== cell) {
cells.push(vertex); cells.push(vertex);
} }
@ -200,7 +188,7 @@ const Template = ({ label, ...args }) => {
style.shadow = true; style.shadow = true;
style = graph.getStylesheet().getDefaultEdgeStyle(); style = graph.getStylesheet().getDefaultEdgeStyle();
style.edge = mxEdgeStyle.TopToBottom; style.edge = EdgeStyle.TopToBottom;
style.rounded = true; style.rounded = true;
// Enables automatic sizing for vertices after editing and // Enables automatic sizing for vertices after editing and
@ -215,15 +203,15 @@ const Template = ({ label, ...args }) => {
// Enables automatic layout on the graph and installs // Enables automatic layout on the graph and installs
// a tree layout for all groups who's children are // a tree layout for all groups who's children are
// being changed, added or removed. // being changed, added or removed.
layout = new mxCompactTreeLayout(graph, false); layout = new CompactTreeLayout(graph, false);
layout.useBoundingBox = false; layout.useBoundingBox = false;
layout.edgeRouting = false; layout.edgeRouting = false;
layout.levelDistance = 30; layout.levelDistance = 30;
layout.nodeDistance = 10; layout.nodeDistance = 10;
const layoutMgr = new mxLayoutManager(graph); const layoutMgr = new LayoutManager(graph);
layoutMgr.getLayout = function(cell) { layoutMgr.getLayout = function (cell) {
if (cell.getChildCount() > 0) { if (cell.getChildCount() > 0) {
return layout; return layout;
} }
@ -237,15 +225,7 @@ const Template = ({ label, ...args }) => {
graph.getModel().beginUpdate(); graph.getModel().beginUpdate();
try { try {
const w = graph.container.offsetWidth; const w = graph.container.offsetWidth;
const root = graph.insertVertex( const root = graph.insertVertex(parent, 'treeRoot', 'Root', w / 2 - 30, 20, 60, 40);
parent,
'treeRoot',
'Root',
w / 2 - 30,
20,
60,
40
);
const v1 = graph.insertVertex(parent, 'v1', 'Child 1', 0, 0, 60, 40); const v1 = graph.insertVertex(parent, 'v1', 'Child 1', 0, 0, 60, 40);
graph.insertEdge(parent, null, '', root, v1); graph.insertEdge(parent, null, '', root, v1);
@ -268,26 +248,10 @@ const Template = ({ label, ...args }) => {
const v22 = graph.insertVertex(parent, 'v22', 'Child 2.2', 0, 0, 60, 40); const v22 = graph.insertVertex(parent, 'v22', 'Child 2.2', 0, 0, 60, 40);
graph.insertEdge(parent, null, '', v2, v22); graph.insertEdge(parent, null, '', v2, v22);
const v221 = graph.insertVertex( const v221 = graph.insertVertex(parent, 'v221', 'Child 2.2.1', 0, 0, 60, 40);
parent,
'v221',
'Child 2.2.1',
0,
0,
60,
40
);
graph.insertEdge(parent, null, '', v22, v221); graph.insertEdge(parent, null, '', v22, v221);
const v222 = graph.insertVertex( const v222 = graph.insertVertex(parent, 'v222', 'Child 2.2.2', 0, 0, 60, 40);
parent,
'v222',
'Child 2.2.2',
0,
0,
60,
40
);
graph.insertEdge(parent, null, '', v22, v222); graph.insertEdge(parent, null, '', v22, v222);
const v31 = graph.insertVertex(parent, 'v31', 'Child 3.1', 0, 0, 60, 40); const v31 = graph.insertVertex(parent, 'v31', 'Child 3.1', 0, 0, 60, 40);
@ -298,6 +262,6 @@ const Template = ({ label, ...args }) => {
} }
return container; return container;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

View File

@ -1,31 +1,31 @@
import mxgraph from '@mxgraph/core'; import maxgraph from '@maxgraph/core';
import { popup } from '@mxgraph/core/src/util/gui/mxWindow'; import { popup } from '@maxgraph/core/util/gui/mxWindow';
import { globalTypes } from '../.storybook/preview'; import { globalTypes } from '../.storybook/preview';
export default { export default {
title: 'Xml_Json/UserObject', title: 'Xml_Json/UserObject',
argTypes: { argTypes: {
...globalTypes ...globalTypes,
} },
}; };
const Template = ({ label, ...args }) => { const Template = ({ label, ...args }) => {
const { const {
mxGraph, Graph,
mxRectangle, Rectangle,
mxDomHelpers, mxDomHelpers,
mxKeyHandler, mxKeyHandler,
mxEvent, InternalEvent,
mxXmlUtils, mxXmlUtils,
mxCodec, mxCodec,
mxConstants, Constants,
mxUtils, utils,
mxEdgeStyle, EdgeStyle,
mxDomUtils, mxDomUtils,
mxForm, mxForm,
mxCellAttributeChange CellAttributeChange,
} = mxgraph; } = maxgraph;
const div = document.createElement('div'); const div = document.createElement('div');
@ -39,7 +39,7 @@ const Template = ({ label, ...args }) => {
div.appendChild(container); div.appendChild(container);
// Note that these XML nodes will be enclosing the // Note that these XML nodes will be enclosing the
// mxCell nodes for the model cells in the output // Cell nodes for the model cells in the output
const doc = mxXmlUtils.createXmlDocument(); const doc = mxXmlUtils.createXmlDocument();
const person1 = doc.createElement('Person'); const person1 = doc.createElement('Person');
@ -54,7 +54,7 @@ const Template = ({ label, ...args }) => {
relation.setAttribute('since', '1985'); relation.setAttribute('since', '1985');
// Creates the graph inside the given container // Creates the graph inside the given container
const graph = new mxGraph(container); const graph = new Graph(container);
// Optional disabling of sizing // Optional disabling of sizing
graph.setCellsResizable(false); graph.setCellsResizable(false);
@ -62,19 +62,19 @@ const Template = ({ label, ...args }) => {
// Configures the graph contains to resize and // Configures the graph contains to resize and
// add a border at the bottom, right // add a border at the bottom, right
graph.setResizeContainer(true); graph.setResizeContainer(true);
graph.minimumContainerSize = new mxRectangle(0, 0, 500, 380); graph.minimumContainerSize = new Rectangle(0, 0, 500, 380);
graph.setBorder(60); graph.setBorder(60);
// Stops editing on enter key, handles escape // Stops editing on enter key, handles escape
new mxKeyHandler(graph); new mxKeyHandler(graph);
// Overrides method to disallow edge label editing // Overrides method to disallow edge label editing
graph.isCellEditable = function(cell) { graph.isCellEditable = function (cell) {
return !cell.isEdge(); return !cell.isEdge();
}; };
// Overrides method to provide a cell label in the display // Overrides method to provide a cell label in the display
graph.convertValueToString = function(cell) { graph.convertValueToString = function (cell) {
if (mxDomUtils.isNode(cell.value)) { if (mxDomUtils.isNode(cell.value)) {
if (cell.value.nodeName.toLowerCase() == 'person') { if (cell.value.nodeName.toLowerCase() == 'person') {
const firstName = cell.getAttribute('firstName', ''); const firstName = cell.getAttribute('firstName', '');
@ -87,10 +87,7 @@ const Template = ({ label, ...args }) => {
return firstName; return firstName;
} }
if (cell.value.nodeName.toLowerCase() == 'knows') { if (cell.value.nodeName.toLowerCase() == 'knows') {
return `${cell.value.nodeName} (Since ${cell.getAttribute( return `${cell.value.nodeName} (Since ${cell.getAttribute('since', '')})`;
'since',
''
)})`;
} }
} }
@ -99,16 +96,12 @@ const Template = ({ label, ...args }) => {
// Overrides method to store a cell label in the model // Overrides method to store a cell label in the model
const { cellLabelChanged } = graph; const { cellLabelChanged } = graph;
graph.cellLabelChanged = function(cell, newValue, autoSize) { graph.cellLabelChanged = function (cell, newValue, autoSize) {
if ( if (mxDomUtils.isNode(cell.value) && cell.value.nodeName.toLowerCase() == 'person') {
mxDomUtils.isNode(cell.value) &&
cell.value.nodeName.toLowerCase() == 'person'
) {
const pos = newValue.indexOf(' '); const pos = newValue.indexOf(' ');
const firstName = pos > 0 ? newValue.substring(0, pos) : newValue; const firstName = pos > 0 ? newValue.substring(0, pos) : newValue;
const lastName = const lastName = pos > 0 ? newValue.substring(pos + 1, newValue.length) : '';
pos > 0 ? newValue.substring(pos + 1, newValue.length) : '';
// Clones the value for correct undo/redo // Clones the value for correct undo/redo
const elt = cell.value.cloneNode(true); const elt = cell.value.cloneNode(true);
@ -125,11 +118,8 @@ const Template = ({ label, ...args }) => {
// Overrides method to create the editing value // Overrides method to create the editing value
const { getEditingValue } = graph; const { getEditingValue } = graph;
graph.getEditingValue = function(cell) { graph.getEditingValue = function (cell) {
if ( if (mxDomUtils.isNode(cell.value) && cell.value.nodeName.toLowerCase() == 'person') {
mxDomUtils.isNode(cell.value) &&
cell.value.nodeName.toLowerCase() == 'person'
) {
const firstName = cell.getAttribute('firstName', ''); const firstName = cell.getAttribute('firstName', '');
const lastName = cell.getAttribute('lastName', ''); const lastName = cell.getAttribute('lastName', '');
@ -141,7 +131,7 @@ const Template = ({ label, ...args }) => {
graph.setTooltips(true); graph.setTooltips(true);
const { getTooltipForCell } = graph; const { getTooltipForCell } = graph;
graph.getTooltipForCell = function(cell) { graph.getTooltipForCell = function (cell) {
// Adds some relation details for edges // Adds some relation details for edges
if (cell.isEdge()) { if (cell.isEdge()) {
const src = this.getLabel(cell.getTerminal(true)); const src = this.getLabel(cell.getTerminal(true));
@ -154,8 +144,7 @@ const Template = ({ label, ...args }) => {
}; };
// Enables rubberband selection // Enables rubberband selection
if (args.rubberBand) if (args.rubberBand) new RubberBand(graph);
new RubberBand(graph);
const buttons = document.createElement('div'); const buttons = document.createElement('div');
div.appendChild(buttons); div.appendChild(buttons);
@ -165,10 +154,10 @@ const Template = ({ label, ...args }) => {
// Adds an option to view the XML of the graph // Adds an option to view the XML of the graph
buttons.appendChild( buttons.appendChild(
mxDomHelpers.button('View XML', function() { mxDomHelpers.button('View XML', function () {
const encoder = new mxCodec(); const encoder = new mxCodec();
const node = encoder.encode(graph.getModel()); const node = encoder.encode(graph.getModel());
popup(mxUtils.getPrettyXml(node), true); popup(utils.getPrettyXml(node), true);
}) })
); );
@ -188,7 +177,7 @@ const Template = ({ label, ...args }) => {
style = graph.getStylesheet().getDefaultEdgeStyle(); style = graph.getStylesheet().getDefaultEdgeStyle();
style.strokeColor = '#0C0C0C'; style.strokeColor = '#0C0C0C';
style.labelBackgroundColor = 'white'; style.labelBackgroundColor = 'white';
style.edge = mxEdgeStyle.ElbowConnector; style.edge = EdgeStyle.ElbowConnector;
style.rounded = true; style.rounded = true;
style.fontColor = 'black'; style.fontColor = 'black';
style.fontSize = '10'; style.fontSize = '10';
@ -209,12 +198,10 @@ const Template = ({ label, ...args }) => {
} }
// Implements a properties panel that uses // Implements a properties panel that uses
// mxCellAttributeChange to change properties // CellAttributeChange to change properties
graph graph.getSelectionModel().addListener(InternalEvent.CHANGE, function (sender, evt) {
.getSelectionModel() selectionChanged(graph);
.addListener(mxEvent.CHANGE, function(sender, evt) { });
selectionChanged(graph);
});
selectionChanged(graph); selectionChanged(graph);
@ -262,7 +249,7 @@ const Template = ({ label, ...args }) => {
function createTextField(graph, form, cell, attribute) { function createTextField(graph, form, cell, attribute) {
const input = form.addText(`${attribute.nodeName}:`, attribute.nodeValue); const input = form.addText(`${attribute.nodeName}:`, attribute.nodeValue);
const applyHandler = function() { const applyHandler = function () {
const newValue = input.value || ''; const newValue = input.value || '';
const oldValue = cell.getAttribute(attribute.nodeName, ''); const oldValue = cell.getAttribute(attribute.nodeName, '');
@ -270,11 +257,7 @@ const Template = ({ label, ...args }) => {
graph.getModel().beginUpdate(); graph.getModel().beginUpdate();
try { try {
const edit = new mxCellAttributeChange( const edit = new CellAttributeChange(cell, attribute.nodeName, newValue);
cell,
attribute.nodeName,
newValue
);
graph.getModel().execute(edit); graph.getModel().execute(edit);
graph.updateCellSize(cell); graph.updateCellSize(cell);
} finally { } finally {
@ -283,9 +266,9 @@ const Template = ({ label, ...args }) => {
} }
}; };
mxEvent.addListener(input, 'keypress', function(evt) { InternalEvent.addListener(input, 'keypress', function (evt) {
// Needs to take shift into account for textareas // Needs to take shift into account for textareas
if (evt.keyCode == /* enter */ 13 && !mxEvent.isShiftDown(evt)) { if (evt.keyCode == /* enter */ 13 && !InternalEvent.isShiftDown(evt)) {
input.blur(); input.blur();
} }
}); });
@ -296,10 +279,10 @@ const Template = ({ label, ...args }) => {
// As a workaround you should use a local variable // As a workaround you should use a local variable
// that stores the focused field and invoke blur // that stores the focused field and invoke blur
// explicitely where we do the graph.focus above. // explicitely where we do the graph.focus above.
mxEvent.addListener(input, 'blur', applyHandler); InternalEvent.addListener(input, 'blur', applyHandler);
} }
return div; return div;
} };
export const Default = Template.bind({}); export const Default = Template.bind({});

Some files were not shown because too many files have changed in this diff Show More