-
Notifications
You must be signed in to change notification settings - Fork 18
New: Add SVG export #111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AlexIchenskiy
wants to merge
1
commit into
release/1.0.0
Choose a base branch
from
new/add-svg-export
base: release/1.0.0
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
New: Add SVG export #111
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import { IRectangle } from '../../common'; | ||
|
|
||
| export class SVGDefs { | ||
| private _idBySignature = new Map<string, string>(); | ||
| private _entries: string[] = []; | ||
| private _counter = 0; | ||
| private readonly _filterRegion?: IRectangle; | ||
|
|
||
| constructor(filterRegion?: IRectangle) { | ||
| this._filterRegion = filterRegion; | ||
| } | ||
|
|
||
| get filterRegion(): IRectangle | undefined { | ||
| return this._filterRegion; | ||
| } | ||
|
Comment on lines
+7
to
+15
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can all this be replaced with |
||
|
|
||
| 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>`; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { SVGDefs } from './defs'; | ||
| import { formatNumber, svgElement, SVGAttributes } 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: SVGDefs, | ||
| 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: SVGAttributes = { | ||
| 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, | ||
| }, | ||
| }); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { SVGDefs } from './defs'; | ||
| import { ISVGShape } from './shapes'; | ||
| import { svgElement } from './utils'; | ||
|
|
||
| export const nodeImageToSVG = <N extends INodeBase, E extends IEdgeBase>( | ||
| node: INode<N, E>, | ||
| defs: SVGDefs, | ||
| 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; | ||
| } | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Btw do we want to define
ISVGDefsand this class can implement it so you can referenceISVGDefsin the rest of the code which uses the interface only. Right now, the class is being used in other types.