Skip to content

Commit

Permalink
refactor: directly use mxGraph value objects (#2745)
Browse files Browse the repository at this point in the history
The mxGraph initializer module now exports main mxGraph objects that are
used several times in the library. This make the code easier to read and
reduce the size of minified bundles.

So, when used, there is no more need to prefix the call of mxGraph
object by mxgraph. For instance, instead of writing
`mxgraph.mxConstants.XXX`, it is possible to write `mxConstants.XXX`.
Notice that in files where both values (from mxGraph) and types (from
typed-mxgraph) are imported, the types are aliased to avoid name clash.
The convention taken is to postfix the type by `Type` to make it
explicit.
  • Loading branch information
tbouffard authored Jun 14, 2023
1 parent 3d36ba7 commit c8e3a1e
Show file tree
Hide file tree
Showing 25 changed files with 288 additions and 270 deletions.
22 changes: 11 additions & 11 deletions dev/ts/component/SvgExporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { mxgraph } from '../../../src/component/mxgraph/initializer';
import type { mxGraph, mxSvgCanvas2D } from 'mxgraph';
import { mxgraph, mxClient, mxConstants, mxSvgCanvas2D, mxUtils } from '../../../src/component/mxgraph/initializer';
import type { mxGraph, mxSvgCanvas2D as mxSvgCanvas2DType } from 'mxgraph';

interface SvgExportOptions {
scale: number;
Expand All @@ -40,13 +40,13 @@ export class SvgExporter {
// chrome and webkit: tainted canvas when svg contains foreignObject
// also on brave --> probably fail on chromium based browsers
// so disable foreign objects for such browsers
const isFirefox = mxgraph.mxClient.IS_FF;
const isFirefox = mxClient.IS_FF;
return this.doSvgExport(isFirefox);
}

private doSvgExport(enableForeignObjectForLabel: boolean): string {
const svgDocument = this.computeSvg({ scale: 1, border: 25, enableForeignObjectForLabel: enableForeignObjectForLabel });
const svgAsString = mxgraph.mxUtils.getXml(svgDocument);
const svgAsString = mxUtils.getXml(svgDocument);
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
${svgAsString}
Expand All @@ -63,8 +63,8 @@ ${svgAsString}
const viewScale = this.graph.view.scale;

// Prepares SVG document that holds the output
const svgDoc = mxgraph.mxUtils.createXmlDocument();
const root = svgDoc.createElementNS(mxgraph.mxConstants.NS_SVG, 'svg');
const svgDoc = mxUtils.createXmlDocument();
const root = svgDoc.createElementNS(mxConstants.NS_SVG, 'svg');

const s = scale / viewScale;
const w = Math.max(1, Math.ceil(bounds.width * s) + 2 * border);
Expand All @@ -76,7 +76,7 @@ ${svgAsString}
root.setAttribute('viewBox', (crisp ? '-0.5 -0.5' : '0 0') + ' ' + w + ' ' + h);
svgDoc.appendChild(root);

const group = svgDoc.createElementNS(mxgraph.mxConstants.NS_SVG, 'g');
const group = svgDoc.createElementNS(mxConstants.NS_SVG, 'g');
root.appendChild(group);

const svgCanvas = this.createSvgCanvas(group);
Expand All @@ -100,15 +100,15 @@ ${svgAsString}
return svgDoc;
}

createSvgCanvas(node: Element): mxSvgCanvas2D {
createSvgCanvas(node: Element): mxSvgCanvas2DType {
const canvas = new CanvasForExport(node);
// from the draw.io code, may not be needed here
canvas.pointerEvents = true;
return canvas;
}
}

class CanvasForExport extends mxgraph.mxSvgCanvas2D {
class CanvasForExport extends mxSvgCanvas2D {
// Convert HTML entities
private htmlConverter = document.createElement('div');

Expand Down Expand Up @@ -167,7 +167,7 @@ class CanvasForExport extends mxgraph.mxSvgCanvas2D {

try {
this.htmlConverter.innerHTML = str;
str = mxgraph.mxUtils.extractTextWithWhitespace(this.htmlConverter.childNodes);
str = mxUtils.extractTextWithWhitespace(this.htmlConverter.childNodes);

// Workaround for substring breaking double byte UTF
const exp = Math.ceil((2 * w) / this.state.fontSize);
Expand All @@ -192,7 +192,7 @@ class CanvasForExport extends mxgraph.mxSvgCanvas2D {

// Uses result and adds ellipsis if more than 1 char remains
if (result.length < str.length && str.length - result.length > 1) {
str = mxgraph.mxUtils.trim(result.join('')) + '...';
str = mxUtils.trim(result.join('')) + '...';
}
} catch (e) {
console.warn('Error while computing txt label', e);
Expand Down
6 changes: 3 additions & 3 deletions dev/ts/component/ThemedBpmnVisualization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ limitations under the License.

import { BpmnVisualization, FlowKind, ShapeBpmnElementKind, ShapeUtil, StyleConfigurator, StyleDefault } from '../../../src/bpmn-visualization';
import { logStartup } from '../utils/internal-helpers';
import { mxgraph } from '../../../src/component/mxgraph/initializer';
import { mxConstants } from '../../../src/component/mxgraph/initializer';

interface Theme {
defaultFillColor: string;
Expand Down Expand Up @@ -189,8 +189,8 @@ export class ThemedBpmnVisualization extends BpmnVisualization {

// directly access the 'styles' map to update values. Using stylesheet.getCellStyle returns a copy of the style
const seqFlowStyle = stylesheet.styles[FlowKind.SEQUENCE_FLOW];
seqFlowStyle[mxgraph.mxConstants.STYLE_STROKECOLOR] = color;
seqFlowStyle[mxgraph.mxConstants.STYLE_FILLCOLOR] = color;
seqFlowStyle[mxConstants.STYLE_STROKECOLOR] = color;
seqFlowStyle[mxConstants.STYLE_FILLCOLOR] = color;

logStartup('Sequence flows style updated');
}
Expand Down
10 changes: 5 additions & 5 deletions src/component/mxgraph/BpmnGraph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import type { FitOptions, ZoomConfiguration } from '../options';
import { FitType } from '../options';
import { ensurePositiveValue, ensureValidZoomConfiguration } from '../helpers/validators';
import { debounce, throttle } from 'lodash-es';
import { mxgraph } from './initializer';
import { mxgraph, mxEvent } from './initializer';
import type { mxCellState, mxGraphView, mxPoint } from 'mxgraph';

const zoomFactorIn = 1.25;
Expand Down Expand Up @@ -158,8 +158,8 @@ export class BpmnGraph extends mxgraph.mxGraph {
*/
registerMouseWheelZoomListeners(config: ZoomConfiguration): void {
config = ensureValidZoomConfiguration(config);
mxgraph.mxEvent.addMouseWheelListener(debounce(this.createMouseWheelZoomListener(true), config.debounceDelay), this.container);
mxgraph.mxEvent.addMouseWheelListener(throttle(this.createMouseWheelZoomListener(false), config.throttleDelay), this.container);
mxEvent.addMouseWheelListener(debounce(this.createMouseWheelZoomListener(true), config.debounceDelay), this.container);
mxEvent.addMouseWheelListener(throttle(this.createMouseWheelZoomListener(false), config.throttleDelay), this.container);
}

// Update the currentZoomLevel when performScaling is false, use the currentZoomLevel to set the scale otherwise
Expand All @@ -171,13 +171,13 @@ export class BpmnGraph extends mxgraph.mxGraph {
const [offsetX, offsetY] = this.getEventRelativeCoordinates(evt);
const [newScale, dx, dy] = this.getScaleAndTranslationDeltas(offsetX, offsetY);
this.view.scaleAndTranslate(newScale, this.view.translate.x + dx, this.view.translate.y + dy);
mxgraph.mxEvent.consume(evt);
mxEvent.consume(evt);
}
}

private createMouseWheelZoomListener(performScaling: boolean) {
return (event: Event, up: boolean) => {
if (mxgraph.mxEvent.isConsumed(event)) {
if (mxEvent.isConsumed(event)) {
return;
}
const evt = event as MouseEvent;
Expand Down
14 changes: 7 additions & 7 deletions src/component/mxgraph/BpmnRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import StyleComputer from './renderer/StyleComputer';
import type { BpmnGraph } from './BpmnGraph';
import type { FitOptions, RendererOptions } from '../options';
import type { RenderedModel } from '../registry/bpmn-model-registry';
import { mxgraph } from './initializer';
import { mxPoint } from './initializer';
import type { mxCell } from 'mxgraph';

/**
Expand Down Expand Up @@ -93,10 +93,10 @@ export class BpmnRenderer {
if (edgeCenterCoordinate) {
mxEdge.geometry.relative = false;

const labelBoundsRelativeCoordinateFromParent = this.coordinatesTranslator.computeRelativeCoordinates(mxEdge.parent, new mxgraph.mxPoint(labelBounds.x, labelBounds.y));
const labelBoundsRelativeCoordinateFromParent = this.coordinatesTranslator.computeRelativeCoordinates(mxEdge.parent, new mxPoint(labelBounds.x, labelBounds.y));
const relativeLabelX = labelBoundsRelativeCoordinateFromParent.x + labelBounds.width / 2 - edgeCenterCoordinate.x;
const relativeLabelY = labelBoundsRelativeCoordinateFromParent.y - edgeCenterCoordinate.y;
mxEdge.geometry.offset = new mxgraph.mxPoint(relativeLabelX, relativeLabelY);
mxEdge.geometry.offset = new mxPoint(relativeLabelX, relativeLabelY);
}
}

Expand All @@ -108,13 +108,13 @@ export class BpmnRenderer {
if (edge.bpmnElement instanceof MessageFlow && edge.messageVisibleKind !== MessageVisibleKind.NONE) {
const cell = this.graph.insertVertex(mxEdge, messageFowIconId(mxEdge.id), undefined, 0, 0, 20, 14, this.styleComputer.computeMessageFlowIconStyle(edge));
cell.geometry.relative = true;
cell.geometry.offset = new mxgraph.mxPoint(-10, -7);
cell.geometry.offset = new mxPoint(-10, -7);
}
}

private insertWaypoints(waypoints: Waypoint[], mxEdge: mxCell): void {
if (waypoints) {
mxEdge.geometry.points = waypoints.map(waypoint => this.coordinatesTranslator.computeRelativeCoordinates(mxEdge.parent, new mxgraph.mxPoint(waypoint.x, waypoint.y)));
mxEdge.geometry.points = waypoints.map(waypoint => this.coordinatesTranslator.computeRelativeCoordinates(mxEdge.parent, new mxPoint(waypoint.x, waypoint.y)));
}
}

Expand All @@ -123,14 +123,14 @@ export class BpmnRenderer {
}

private insertVertex(parent: mxCell, id: string | null, value: string, bounds: Bounds, labelBounds: Bounds, style?: string): mxCell {
const vertexCoordinates = this.coordinatesTranslator.computeRelativeCoordinates(parent, new mxgraph.mxPoint(bounds.x, bounds.y));
const vertexCoordinates = this.coordinatesTranslator.computeRelativeCoordinates(parent, new mxPoint(bounds.x, bounds.y));
const cell = this.graph.insertVertex(parent, id, value, vertexCoordinates.x, vertexCoordinates.y, bounds.width, bounds.height, style);

if (labelBounds) {
// label coordinates are relative in the cell referential coordinates
const relativeLabelX = labelBounds.x - bounds.x;
const relativeLabelY = labelBounds.y - bounds.y;
cell.geometry.offset = new mxgraph.mxPoint(relativeLabelX, relativeLabelY);
cell.geometry.offset = new mxPoint(relativeLabelX, relativeLabelY);
}
return cell;
}
Expand Down
4 changes: 2 additions & 2 deletions src/component/mxgraph/GraphCellUpdater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { isShapeStyleUpdate, setStyle, updateFill, updateFont, updateStroke } fr
import { StyleManager } from './style/StyleManager';

import type { BpmnGraph } from './BpmnGraph';
import { mxgraph } from './initializer';
import { mxConstants } from './initializer';
import { BpmnStyleIdentifier } from './style';
import type { Overlay, StyleUpdate } from '../registry';
import type { CssRegistry } from '../registry/css-registry';
Expand Down Expand Up @@ -105,7 +105,7 @@ export default class GraphCellUpdater {
this.styleManager.ensureStyleIsStored(cell);

let cellStyle = cell.getStyle();
cellStyle = setStyle(cellStyle, mxgraph.mxConstants.STYLE_OPACITY, styleUpdate.opacity, ensureOpacityValue);
cellStyle = setStyle(cellStyle, mxConstants.STYLE_OPACITY, styleUpdate.opacity, ensureOpacityValue);
cellStyle = updateStroke(cellStyle, styleUpdate.stroke);
cellStyle = updateFont(cellStyle, styleUpdate.font);

Expand Down
8 changes: 4 additions & 4 deletions src/component/mxgraph/GraphConfigurator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import ShapeConfigurator from './config/ShapeConfigurator';
import MarkerConfigurator from './config/MarkerConfigurator';
import type { GlobalOptions } from '../options';
import { BpmnGraph } from './BpmnGraph';
import { mxgraph } from './initializer';
import { mxEvent } from './initializer';
import type { mxMouseEvent } from 'mxgraph';

/**
Expand Down Expand Up @@ -66,13 +66,13 @@ export default class GraphConfigurator {
const panningHandler = this.graph.panningHandler;
if (options?.navigation?.enabled) {
// Pan configuration
panningHandler.addListener(mxgraph.mxEvent.PAN_START, this.getPanningHandler('grab'));
panningHandler.addListener(mxgraph.mxEvent.PAN_END, this.getPanningHandler('default'));
panningHandler.addListener(mxEvent.PAN_START, this.getPanningHandler('grab'));
panningHandler.addListener(mxEvent.PAN_END, this.getPanningHandler('default'));

panningHandler.usePopupTrigger = false; // only use the left button to trigger panning
// Reimplement the function as we also want to trigger 'panning on cells' (ignoreCell to true) and only on left-click
// The mxGraph standard implementation doesn't ignore right click in this case, so do it by ourselves
panningHandler.isForcePanningEvent = (me): boolean => mxgraph.mxEvent.isLeftMouseButton(me.getEvent()) || mxgraph.mxEvent.isMultiTouchEvent(me.getEvent());
panningHandler.isForcePanningEvent = (me): boolean => mxEvent.isLeftMouseButton(me.getEvent()) || mxEvent.isMultiTouchEvent(me.getEvent());
this.graph.setPanning(true);

// Zoom configuration
Expand Down
Loading

0 comments on commit c8e3a1e

Please sign in to comment.