forked from excalidraw/mermaid-to-excalidraw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
162 lines (139 loc) · 5 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import { Position } from "./interfaces.js";
// Convert mermaid entity codes to text e.g. "#9829;" to "♥"
export const entityCodesToText = (input: string): string => {
input = decodeEntities(input);
// Append & before the pattern #(\d+); or #([a-z]+); to convert to decimal code
// so it can be rendered as html character
// eg #9829; => ♥
const inputWithDecimalCode = input
.replace(/#(\d+);/g, "&#$1;")
.replace(/#([a-z]+);/g, "&$1;");
// Render the decimal code as html character, eg ♥ => ♥
const element = document.createElement("textarea");
element.innerHTML = inputWithDecimalCode;
return element.value;
};
export const getTransformAttr = (el: Element) => {
const transformAttr = el.getAttribute("transform");
const translateMatch = transformAttr?.match(
/translate\(([ \d.-]+),\s*([\d.-]+)\)/
);
let transformX = 0;
let transformY = 0;
if (translateMatch) {
transformX = Number(translateMatch[1]);
transformY = Number(translateMatch[2]);
}
return { transformX, transformY };
};
//TODO Once fixed in mermaid this will be removed
export const encodeEntities = (text: string) => {
let txt = text;
txt = txt.replace(/style.*:\S*#.*;/g, (s) => {
return s.substring(0, s.length - 1);
});
txt = txt.replace(/classDef.*:\S*#.*;/g, (s) => {
return s.substring(0, s.length - 1);
});
txt = txt.replace(/#\w+;/g, (s) => {
const innerTxt = s.substring(1, s.length - 1);
const isInt = /^\+?\d+$/.test(innerTxt);
if (isInt) {
return `fl°°${innerTxt}¶ß`;
}
return `fl°${innerTxt}¶ß`;
});
return txt;
};
export const decodeEntities = function (text: string): string {
return text.replace(/fl°°/g, "#").replace(/fl°/g, "&").replace(/¶ß/g, ";");
};
// Extract edge position start, end, and points (reflectionPoints)
interface EdgePositionData {
startX: number;
startY: number;
endX: number;
endY: number;
reflectionPoints: Position[];
}
// Compute edge postion start, end and points (reflection points)
export const computeEdgePositions = (
pathElement: SVGPathElement,
offset: Position = { x: 0, y: 0 }
): EdgePositionData => {
// Check if the element is a path else throw an error
if (pathElement.tagName.toLowerCase() !== "path") {
throw new Error(
`Invalid input: Expected an HTMLElement of tag "path", got ${pathElement.tagName}`
);
}
// Get the d attribute from the path element else throw an error
const dAttr = pathElement.getAttribute("d");
if (!dAttr) {
throw new Error('Path element does not contain a "d" attribute');
}
// Split the d attribute based on M (Move To) and L (Line To) commands
// eg "M29.383,38.5L29.383,63.5L29.383,83.2" => ["M29.383,38.5", "L29.383,63.5", "L29.383,83.2"]
const commands = dAttr.split(/(?=[LM])/);
// Get the start position from the first commands element => [29.383,38.5]
const startPosition = commands[0]
.substring(1)
.split(",")
.map((coord) => parseFloat(coord));
// Get the last position from the last commands element => [29.383,83.2]
const endPosition = commands[commands.length - 1]
.substring(1)
.split(",")
.map((coord) => parseFloat(coord));
// compute the reflection points -> [ {x: 29.383, y: 38.5}, {x: 29.383, y: 83.2} ]
// These includes the start and end points and also points which are not the same as the previous points
const reflectionPoints = commands.map((command) => {
const coords = command
.substring(1)
.split(",")
.map((coord) => parseFloat(coord));
return { x: coords[0], y: coords[1] };
});
const filterReflectionPoints = reflectionPoints
.filter((point, index, array) => {
// Always include the last point
if (index === array.length - 1) {
return true;
}
if (
index === array.length - 2 &&
(array[index - 1].x === point.x || array[index - 1].y === point.y)
) {
const lastPoint = array[array.length - 1];
/**
* Euclidean distance formula.
* If the distance between the last point and the current point (second last point) is greater than X include the last point.
*/
const distance = Math.sqrt(
Math.pow(lastPoint.x - point.x, 2) +
Math.pow(lastPoint.y - point.y, 2)
);
return distance > 20;
// return false;
}
// Always include the start point, or if the current point is not the same as the previous point
const prevPoint = array[index - 1];
return index === 0 || point.x !== prevPoint.x || point.y !== prevPoint.y;
})
.map((p) => {
// Offset the point by the provided offset
return {
x: p.x + offset.x,
y: p.y + offset.y,
};
});
console.debug({ reflectionPoints, filterReflectionPoints });
// Return the edge positions
return {
startX: startPosition[0] + offset.x,
startY: startPosition[1] + offset.y,
endX: endPosition[0] + offset.x,
endY: endPosition[1] + offset.y,
reflectionPoints: filterReflectionPoints,
};
};