Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ export { IEdge, IEdgeBase, IEdgePosition, IEdgeStyle, isEdge, EdgeType } from '.
export { IGraphStyle, getDefaultGraphStyle } from './models/style';
export { ICircle, IPosition, IRectangle, Color, IColorRGB } from './common';
export { OrbView, OrbMapView, IOrbView, IOrbMapViewSettings, IOrbViewSettings } from './views';
export { graphToSVG, ISVGExportOptions } from './renderer/svg';
35 changes: 35 additions & 0 deletions src/renderer/svg/defs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { IRectangle } from '../../common';

export interface ISVGDefs {
readonly filterRegion?: IRectangle;
add(signature: string, build: (id: string) => string): string;
toSVG(): string;
}

export class SVGDefs implements ISVGDefs {
private _idBySignature = new Map<string, string>();
private _entries: string[] = [];
private _counter = 0;

constructor(public readonly filterRegion?: IRectangle) {}

add(signature: string, build: (id: string) => string): string {
const existing = this._idBySignature.get(signature);
if (existing !== undefined) {
return existing;
}

const id = `orb-def-${this._counter}`;
this._counter += 1;
this._idBySignature.set(signature, id);
this._entries.push(build(id));
return id;
}

toSVG(): string {
if (!this._entries.length) {
return '';
}
return `<defs>${this._entries.join('')}</defs>`;
}
}
154 changes: 154 additions & 0 deletions src/renderer/svg/edge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { INodeBase } from '../../models/node';
import { IEdge, IEdgeBase, EdgeStraight, EdgeCurved, EdgeLoopback } from '../../models/edge';
import { IPosition } from '../../common';
import { LabelTextBaseline } from '../canvas/label';
import { IEdgeArrow } from '../canvas/edge/shared';
import { getStraightArrowShape } from '../canvas/edge/types/edge-straight';
import { getCurvedArrowShape } from '../canvas/edge/types/edge-curved';
import { getLoopbackArrowShape } from '../canvas/edge/types/edge-loopback';
import { labelToSVG } from './label';
import { shadowFilterId, toShadow } from './shadow';
import { ISVGDefs } from './defs';
import { formatNumber, svgElement, ISVGAttributes } from './utils';

const DEFAULT_EDGE_COLOR = '#000000';

const ARROW_KEY_POINTS: IPosition[] = [
{ x: 0, y: 0 },
{ x: -1, y: 0.4 },
{ x: -1, y: -0.4 },
];

export interface IEdgeToSVGOptions {
isLabelEnabled: boolean;
isShadowEnabled: boolean;
}

export const edgeToSVG = <N extends INodeBase, E extends IEdgeBase>(
edge: IEdge<N, E>,
defs: ISVGDefs,
options?: Partial<IEdgeToSVGOptions>,
): string => {
const width = edge.getWidth();
if (!width) {
return '';
}

const isLabelEnabled = options?.isLabelEnabled ?? true;
const isShadowEnabled = options?.isShadowEnabled ?? true;
const color = (edge.getColor() ?? DEFAULT_EDGE_COLOR).toString();

const arrow = edgeArrowToSVG(edge, color);
const line = edgeLineToSVG(edge, width, color);

const shadow = isShadowEnabled && edge.hasShadow() ? toShadow(edge.getStyle()) : null;

let content = `${arrow}${line}`;
if (shadow) {
content = svgElement('g', { filter: `url(#${shadowFilterId(defs, shadow)})` }, content);
}

const label = isLabelEnabled ? edgeLabelToSVG(edge) : '';

return svgElement('g', {}, `${content}${label}`);
};

const edgeLineToSVG = <N extends INodeBase, E extends IEdgeBase>(
edge: IEdge<N, E>,
width: number,
color: string,
): string => {
const dashPattern = edge.getLineDashPattern();
const strokeAttributes: ISVGAttributes = {
stroke: color,
'stroke-width': width,
fill: 'none',
'stroke-dasharray': dashPattern ? dashPattern.join(' ') : undefined,
};

if (edge instanceof EdgeStraight) {
const source = edge.startNode.getCenter();
const target = edge.endNode.getCenter();
const d = `M ${formatNumber(source.x)} ${formatNumber(source.y)} L ${formatNumber(target.x)} ${formatNumber(
target.y,
)}`;
return svgElement('path', { d, ...strokeAttributes });
}

if (edge instanceof EdgeCurved) {
const source = edge.startNode.getCenter();
const target = edge.endNode.getCenter();
const control = edge.getCurvedControlPoint();
const d = `M ${formatNumber(source.x)} ${formatNumber(source.y)} Q ${formatNumber(control.x)} ${formatNumber(
control.y,
)} ${formatNumber(target.x)} ${formatNumber(target.y)}`;
return svgElement('path', { d, ...strokeAttributes });
}

if (edge instanceof EdgeLoopback) {
const { x, y, radius } = edge.getCircularData();
return svgElement('circle', { cx: x, cy: y, r: radius, ...strokeAttributes });
}

return '';
};

const edgeArrowToSVG = <N extends INodeBase, E extends IEdgeBase>(edge: IEdge<N, E>, color: string): string => {
if (edge.getStyle().arrowSize === 0) {
return '';
}

const arrowShape = getArrowShape(edge);
if (!arrowShape) {
return '';
}

const points = transformArrowPoints(ARROW_KEY_POINTS, arrowShape);
const pointsAttribute = points.map((point) => `${formatNumber(point.x)},${formatNumber(point.y)}`).join(' ');

return svgElement('polygon', { points: pointsAttribute, fill: color });
};

const getArrowShape = <N extends INodeBase, E extends IEdgeBase>(edge: IEdge<N, E>): IEdgeArrow | null => {
if (edge instanceof EdgeStraight) {
return getStraightArrowShape(edge);
}
if (edge instanceof EdgeCurved) {
return getCurvedArrowShape(edge);
}
if (edge instanceof EdgeLoopback) {
return getLoopbackArrowShape(edge);
}
return null;
};

const transformArrowPoints = (points: IPosition[], arrow: IEdgeArrow): IPosition[] => {
return points.map((point) => {
const xt = point.x * Math.cos(arrow.angle) - point.y * Math.sin(arrow.angle);
const yt = point.x * Math.sin(arrow.angle) + point.y * Math.cos(arrow.angle);
return {
x: arrow.point.x + arrow.length * xt,
y: arrow.point.y + arrow.length * yt,
};
});
};

const edgeLabelToSVG = <N extends INodeBase, E extends IEdgeBase>(edge: IEdge<N, E>): string => {
const edgeLabel = edge.getLabel();
if (!edgeLabel) {
return '';
}

const edgeStyle = edge.getStyle();

return labelToSVG(edgeLabel, {
position: edge.getCenter(),
textBaseline: LabelTextBaseline.MIDDLE,
properties: {
fontBackgroundColor: edgeStyle.fontBackgroundColor,
fontColor: edgeStyle.fontColor,
fontFamily: edgeStyle.fontFamily,
fontSize: edgeStyle.fontSize,
},
});
};
78 changes: 78 additions & 0 deletions src/renderer/svg/image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { INodeBase, INode } from '../../models/node';
import { IEdgeBase } from '../../models/edge';
import { ISVGDefs } from './defs';
import { ISVGShape } from './shapes';
import { svgElement } from './utils';

export const nodeImageToSVG = <N extends INodeBase, E extends IEdgeBase>(
node: INode<N, E>,
defs: ISVGDefs,
shape: ISVGShape,
): string => {
const image = node.getBackgroundImage();
if (!image || !image.width || !image.height) {
return '';
}

const href = resolveImageHref(node, image);
if (!href) {
return '';
}

const center = node.getCenter();
const radius = node.getRadius();

const clipGeometry = Object.keys(shape.attributes)
.map((key) => `${key}=${shape.attributes[key]}`)
.join(',');
const clipId = defs.add(`clip:${shape.tag}:${clipGeometry}`, (id) =>
svgElement('clipPath', { id }, svgElement(shape.tag, shape.attributes)),
);

return svgElement('image', {
href,
'xlink:href': href,
x: center.x - radius,
y: center.y - radius,
width: radius * 2,
height: radius * 2,
preserveAspectRatio: 'xMidYMid slice',
'clip-path': `url(#${clipId})`,
});
};

const resolveImageHref = <N extends INodeBase, E extends IEdgeBase>(
node: INode<N, E>,
image: HTMLImageElement,
): string | undefined => {
const dataUrl = imageToDataURL(image);
if (dataUrl) {
return dataUrl;
}

const style = node.getStyle();
if (node.isSelected() && style.imageUrlSelected) {
return style.imageUrlSelected;
}
return style.imageUrl ?? image.src ?? undefined;
};

const imageToDataURL = (image: HTMLImageElement): string | undefined => {
if (typeof document === 'undefined') {
return undefined;
}

try {
const canvas = document.createElement('canvas');
canvas.width = image.naturalWidth || image.width;
canvas.height = image.naturalHeight || image.height;
const context = canvas.getContext('2d');
if (!context) {
return undefined;
}
context.drawImage(image, 0, 0);
return canvas.toDataURL();
} catch {
return undefined;
}
};
Loading
Loading