"use strict";
var __esbuild_esm_mermaid_nm;
(__esbuild_esm_mermaid_nm ||= {}).mermaid = (() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value2) => __defProp(target, "name", { value: value2, configurable: true });
var __esm = (fn3, res) => function __init() {
return fn3 && (res = (0, fn3[__getOwnPropNames(fn3)[0]])(fn3 = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from2, except, desc) => {
if (from2 && typeof from2 === "object" || typeof from2 === "function") {
for (let key of __getOwnPropNames(from2))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// ../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon/defaults.js
var defaultIconDimensions, defaultIconTransformations, defaultIconProps, defaultExtendedIconProps;
var init_defaults = __esm({
"../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon/defaults.js"() {
"use strict";
defaultIconDimensions = Object.freeze({
left: 0,
top: 0,
width: 16,
height: 16
});
defaultIconTransformations = Object.freeze({
rotate: 0,
vFlip: false,
hFlip: false
});
defaultIconProps = Object.freeze({
...defaultIconDimensions,
...defaultIconTransformations
});
defaultExtendedIconProps = Object.freeze({
...defaultIconProps,
body: "",
hidden: false
});
}
});
// ../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/customisations/defaults.js
var defaultIconSizeCustomisations, defaultIconCustomisations;
var init_defaults2 = __esm({
"../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/customisations/defaults.js"() {
"use strict";
init_defaults();
defaultIconSizeCustomisations = Object.freeze({
width: null,
height: null
});
defaultIconCustomisations = Object.freeze({
...defaultIconSizeCustomisations,
...defaultIconTransformations
});
}
});
// ../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon/name.js
var stringToIcon, validateIconName;
var init_name = __esm({
"../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon/name.js"() {
"use strict";
stringToIcon = /* @__PURE__ */ __name((value2, validate, allowSimpleName, provider = "") => {
const colonSeparated = value2.split(":");
if (value2.slice(0, 1) === "@") {
if (colonSeparated.length < 2 || colonSeparated.length > 3) return null;
provider = colonSeparated.shift().slice(1);
}
if (colonSeparated.length > 3 || !colonSeparated.length) return null;
if (colonSeparated.length > 1) {
const name$1 = colonSeparated.pop();
const prefix = colonSeparated.pop();
const result = {
provider: colonSeparated.length > 0 ? colonSeparated[0] : provider,
prefix,
name: name$1
};
return validate && !validateIconName(result) ? null : result;
}
const name = colonSeparated[0];
const dashSeparated = name.split("-");
if (dashSeparated.length > 1) {
const result = {
provider,
prefix: dashSeparated.shift(),
name: dashSeparated.join("-")
};
return validate && !validateIconName(result) ? null : result;
}
if (allowSimpleName && provider === "") {
const result = {
provider,
prefix: "",
name
};
return validate && !validateIconName(result, allowSimpleName) ? null : result;
}
return null;
}, "stringToIcon");
validateIconName = /* @__PURE__ */ __name((icon2, allowSimpleName) => {
if (!icon2) return false;
return !!((allowSimpleName && icon2.prefix === "" || !!icon2.prefix) && !!icon2.name);
}, "validateIconName");
}
});
// ../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon/transformations.js
function mergeIconTransformations(obj1, obj2) {
const result = {};
if (!obj1.hFlip !== !obj2.hFlip) result.hFlip = true;
if (!obj1.vFlip !== !obj2.vFlip) result.vFlip = true;
const rotate2 = ((obj1.rotate || 0) + (obj2.rotate || 0)) % 4;
if (rotate2) result.rotate = rotate2;
return result;
}
var init_transformations = __esm({
"../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon/transformations.js"() {
"use strict";
__name(mergeIconTransformations, "mergeIconTransformations");
}
});
// ../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon/merge.js
function mergeIconData(parent4, child) {
const result = mergeIconTransformations(parent4, child);
for (const key in defaultExtendedIconProps) if (key in defaultIconTransformations) {
if (key in parent4 && !(key in result)) result[key] = defaultIconTransformations[key];
} else if (key in child) result[key] = child[key];
else if (key in parent4) result[key] = parent4[key];
return result;
}
var init_merge = __esm({
"../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon/merge.js"() {
"use strict";
init_defaults();
init_transformations();
__name(mergeIconData, "mergeIconData");
}
});
// ../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon-set/tree.js
function getIconsTree(data5, names) {
const icons = data5.icons;
const aliases = data5.aliases || /* @__PURE__ */ Object.create(null);
const resolved = /* @__PURE__ */ Object.create(null);
function resolve2(name) {
if (icons[name]) return resolved[name] = [];
if (!(name in resolved)) {
resolved[name] = null;
const parent4 = aliases[name] && aliases[name].parent;
const value2 = parent4 && resolve2(parent4);
if (value2) resolved[name] = [parent4].concat(value2);
}
return resolved[name];
}
__name(resolve2, "resolve");
(names || Object.keys(icons).concat(Object.keys(aliases))).forEach(resolve2);
return resolved;
}
var init_tree = __esm({
"../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon-set/tree.js"() {
"use strict";
__name(getIconsTree, "getIconsTree");
}
});
// ../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon-set/get-icon.js
function internalGetIconData(data5, name, tree) {
const icons = data5.icons;
const aliases = data5.aliases || /* @__PURE__ */ Object.create(null);
let currentProps = {};
function parse7(name$1) {
currentProps = mergeIconData(icons[name$1] || aliases[name$1], currentProps);
}
__name(parse7, "parse");
parse7(name);
tree.forEach(parse7);
return mergeIconData(data5, currentProps);
}
function getIconData(data5, name) {
if (data5.icons[name]) return internalGetIconData(data5, name, []);
const tree = getIconsTree(data5, [name])[name];
return tree ? internalGetIconData(data5, name, tree) : null;
}
var init_get_icon = __esm({
"../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/icon-set/get-icon.js"() {
"use strict";
init_merge();
init_tree();
__name(internalGetIconData, "internalGetIconData");
__name(getIconData, "getIconData");
}
});
// ../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/svg/size.js
function calculateSize(size4, ratio, precision) {
if (ratio === 1) return size4;
precision = precision || 100;
if (typeof size4 === "number") return Math.ceil(size4 * ratio * precision) / precision;
if (typeof size4 !== "string") return size4;
const oldParts = size4.split(unitsSplit);
if (oldParts === null || !oldParts.length) return size4;
const newParts = [];
let code = oldParts.shift();
let isNumber = unitsTest.test(code);
while (true) {
if (isNumber) {
const num = parseFloat(code);
if (isNaN(num)) newParts.push(code);
else newParts.push(Math.ceil(num * ratio * precision) / precision);
} else newParts.push(code);
code = oldParts.shift();
if (code === void 0) return newParts.join("");
isNumber = !isNumber;
}
}
var unitsSplit, unitsTest;
var init_size = __esm({
"../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/svg/size.js"() {
"use strict";
unitsSplit = /(-?[0-9.]*[0-9]+[0-9.]*)/g;
unitsTest = /^-?[0-9.]*[0-9]+[0-9.]*$/g;
__name(calculateSize, "calculateSize");
}
});
// ../../node_modules/.pnpm/@iconify+utils@3.0.2/node_modules/@iconify/utils/lib/svg/defs.js
function splitSVGDefs(content, tag = "defs") {
let defs2 = "";
const index = content.indexOf("<" + tag);
while (index >= 0) {
const start3 = content.indexOf(">", index);
const end2 = content.indexOf("" + tag);
if (start3 === -1 || end2 === -1) break;
const endEnd = content.indexOf(">", end2);
if (endEnd === -1) break;
defs2 += content.slice(start3 + 1, end2).trim();
content = content.slice(0, index).trim() + content.slice(endEnd + 1);
}
return {
defs: defs2,
content
};
}
function mergeDefsAndContent(defs2, content) {
return defs2 ? "
' + (n2 ? i2 : w(i2, true)) + `
` : "" + (n2 ? i2 : w(i2, true)) + `
`;
}
blockquote({ tokens: e3 }) {
return `${this.parser.parse(e3)}`; } html({ text: e3 }) { return e3; } def(e3) { return ""; } heading({ tokens: e3, depth: t4 }) { return `
${this.parser.parseInline(e3)}
`; } table(e3) { let t4 = "", n2 = ""; for (let i2 = 0; i2 < e3.header.length; i2++) n2 += this.tablecell(e3.header[i2]); t4 += this.tablerow({ text: n2 }); let r2 = ""; for (let i2 = 0; i2 < e3.rows.length; i2++) { let s2 = e3.rows[i2]; n2 = ""; for (let o2 = 0; o2 < s2.length; o2++) n2 += this.tablecell(s2[o2]); r2 += this.tablerow({ text: n2 }); } return r2 && (r2 = `${r2}`), `${w(e3, true)}`;
}
br(e3) {
return "An error occurred:
" + w(n2.message + "", true) + ""; return t4 ? Promise.resolve(r2) : r2; } if (t4) return Promise.reject(n2); throw n2; }; } }; _ = new B(); __name(d, "d"); d.options = d.setOptions = function(l4) { return _.setOptions(l4), d.defaults = _.defaults, G(d.defaults), d; }; d.getDefaults = L; d.defaults = O; d.use = function(...l4) { return _.use(...l4), d.defaults = _.defaults, G(d.defaults), d; }; d.walkTokens = function(l4, e3) { return _.walkTokens(l4, e3); }; d.parseInline = _.parseInline; d.Parser = R; d.parser = R.parse; d.Renderer = P; d.TextRenderer = $; d.Lexer = b; d.lexer = b.lex; d.Tokenizer = y2; d.Hooks = S2; d.parse = d; Dt = d.options; Ht = d.setOptions; Zt = d.use; Gt = d.walkTokens; Nt = d.parseInline; Ft = R.parse; Qt = b.lex; } }); // src/rendering-util/handle-markdown-text.ts function preprocessMarkdown(markdown, { markdownAutoWrap }) { const withoutBR = markdown.replace(/
${/**
* Replace new lines with
tags.
*
* Unlike in markdown text, `\n` sequences are treated as line breaks here.
*/
text4.replace(/\\n|\n/g, "
")}
${node2.tokens?.map(output2).join("")}
`; } else if (node2.type === "space") { return ""; } else if (node2.type === "html") { return `${node2.text}`; } else if (node2.type === "escape") { return node2.text; } log.warn(`Unsupported markdown: ${node2.type}`); return node2.raw; } __name(output2, "output"); return nodes5.map(output2).join(""); } var init_handle_markdown_text = __esm({ "src/rendering-util/handle-markdown-text.ts"() { "use strict"; init_marked_esm(); init_esm(); init_logger(); __name(preprocessMarkdown, "preprocessMarkdown"); __name(nonMarkdownToLines, "nonMarkdownToLines"); __name(markdownToLines, "markdownToLines"); __name(nonMarkdownToHTML, "nonMarkdownToHTML"); __name(markdownToHTML, "markdownToHTML"); } }); // src/rendering-util/splitText.ts function splitTextToChars(text4) { if (Intl.Segmenter) { return [...new Intl.Segmenter().segment(text4)].map((s2) => s2.segment); } return [...text4]; } function splitWordToFitWidth(checkFit, word) { const characters2 = splitTextToChars(word.content); return splitWordToFitWidthRecursion(checkFit, [], characters2, word.type); } function splitWordToFitWidthRecursion(checkFit, usedChars, remainingChars, type3) { if (remainingChars.length === 0) { return [ { content: usedChars.join(""), type: type3 }, { content: "", type: type3 } ]; } const [nextChar, ...rest] = remainingChars; const newWord = [...usedChars, nextChar]; if (checkFit([{ content: newWord.join(""), type: type3 }])) { return splitWordToFitWidthRecursion(checkFit, newWord, rest, type3); } if (usedChars.length === 0 && nextChar) { usedChars.push(nextChar); remainingChars.shift(); } return [ { content: usedChars.join(""), type: type3 }, { content: remainingChars.join(""), type: type3 } ]; } function splitLineToFitWidth(line2, checkFit) { if (line2.some(({ content }) => content.includes("\n"))) { throw new Error("splitLineToFitWidth does not support newlines in the line"); } return splitLineToFitWidthRecursion(line2, checkFit); } function splitLineToFitWidthRecursion(words, checkFit, lines = [], newLine = []) { if (words.length === 0) { if (newLine.length > 0) { lines.push(newLine); } return lines.length > 0 ? lines : []; } let joiner = ""; if (words[0].content === " ") { joiner = " "; words.shift(); } const nextWord = words.shift() ?? { content: " ", type: "normal" }; const lineWithNextWord = [...newLine]; if (joiner !== "") { lineWithNextWord.push({ content: joiner, type: "normal" }); } lineWithNextWord.push(nextWord); if (checkFit(lineWithNextWord)) { return splitLineToFitWidthRecursion(words, checkFit, lines, lineWithNextWord); } if (newLine.length > 0) { lines.push(newLine); words.unshift(nextWord); } else if (nextWord.content) { const [line2, rest] = splitWordToFitWidth(checkFit, nextWord); lines.push([line2]); if (rest.content) { words.unshift(rest); } } return splitLineToFitWidthRecursion(words, checkFit, lines); } var init_splitText = __esm({ "src/rendering-util/splitText.ts"() { "use strict"; __name(splitTextToChars, "splitTextToChars"); __name(splitWordToFitWidth, "splitWordToFitWidth"); __name(splitWordToFitWidthRecursion, "splitWordToFitWidthRecursion"); __name(splitLineToFitWidth, "splitLineToFitWidth"); __name(splitLineToFitWidthRecursion, "splitLineToFitWidthRecursion"); } }); // src/rendering-util/createText.ts function applyStyle(dom, styleFn) { if (styleFn) { dom.attr("style", styleFn); } } async function addHtmlSpan(element3, node2, width3, classes3, addBackground = false, config5 = getConfig()) { const fo = element3.append("foreignObject"); fo.attr("width", `${Math.min(10 * width3, maxSafeSizeForWidth)}px`); fo.attr("height", `${Math.min(10 * width3, maxSafeSizeForWidth)}px`); const div = fo.append("xhtml:div"); const sanitizedLabel = hasKatex(node2.label) ? await renderKatexSanitized(node2.label.replace(common_default.lineBreakRegex, "\n"), config5) : sanitizeText(node2.label, config5); const labelClass = node2.isNode ? "nodeLabel" : "edgeLabel"; const span = div.append("span"); span.html(sanitizedLabel); applyStyle(span, node2.labelStyle); span.attr("class", `${labelClass} ${classes3}`); applyStyle(div, node2.labelStyle); div.style("display", "table-cell"); div.style("white-space", "nowrap"); div.style("line-height", "1.5"); if (width3 !== Number.POSITIVE_INFINITY) { div.style("max-width", width3 + "px"); div.style("text-align", "center"); } div.attr("xmlns", "http://www.w3.org/1999/xhtml"); if (addBackground) { div.attr("class", "labelBkg"); } let bbox = div.node().getBoundingClientRect(); if (bbox.width === width3) { div.style("display", "table"); div.style("white-space", "break-spaces"); div.style("width", width3 + "px"); bbox = div.node().getBoundingClientRect(); } return fo.node(); } function createTspan(textElement, lineIndex, lineHeight, centerText = false) { const tspan = textElement.append("tspan").attr("class", "text-outer-tspan").attr("x", 0).attr("y", lineIndex * lineHeight - 0.1 + "em").attr("dy", lineHeight + "em"); if (centerText) { tspan.attr("text-anchor", "middle"); } return tspan; } function computeWidthOfText(parentNode, lineHeight, line2) { const testElement = parentNode.append("text"); const testSpan = createTspan(testElement, 1, lineHeight); updateTextContentAndStyles(testSpan, line2); const textLength = testSpan.node().getComputedTextLength(); testElement.remove(); return textLength; } function computeDimensionOfText(parentNode, lineHeight, text4) { const testElement = parentNode.append("text"); const testSpan = createTspan(testElement, 1, lineHeight); updateTextContentAndStyles(testSpan, [{ content: text4, type: "normal" }]); const textDimension = testSpan.node()?.getBoundingClientRect(); if (textDimension) { testElement.remove(); } return textDimension; } function createFormattedText(width3, g2, structuredText, addBackground = false, centerText = false) { const lineHeight = 1.1; const labelGroup = g2.append("g"); const bkg = labelGroup.insert("rect").attr("class", "background").attr("style", "stroke: none"); const textElement = labelGroup.append("text").attr("y", "-10.1"); if (centerText) { textElement.attr("text-anchor", "middle"); } let lineIndex = 0; for (const line2 of structuredText) { const checkWidth = /* @__PURE__ */ __name((line3) => computeWidthOfText(labelGroup, lineHeight, line3) <= width3, "checkWidth"); const linesUnderWidth = checkWidth(line2) ? [line2] : splitLineToFitWidth(line2, checkWidth); for (const preparedLine of linesUnderWidth) { const tspan = createTspan(textElement, lineIndex, lineHeight, centerText); updateTextContentAndStyles(tspan, preparedLine); lineIndex++; } } if (addBackground) { const bbox = textElement.node().getBBox(); const padding2 = 2; bkg.attr("x", bbox.x - padding2).attr("y", bbox.y - padding2).attr("width", bbox.width + 2 * padding2).attr("height", bbox.height + 2 * padding2); return labelGroup.node(); } else { return textElement.node(); } } function updateTextContentAndStyles(tspan, wrappedLine) { tspan.text(""); wrappedLine.forEach((word, index) => { const innerTspan = tspan.append("tspan").attr("font-style", word.type === "em" ? "italic" : "normal").attr("class", "text-inner-tspan").attr("font-weight", word.type === "strong" ? "bold" : "normal"); if (index === 0) { innerTspan.text(word.content); } else { innerTspan.text(" " + word.content); } }); } async function replaceIconSubstring(text4, config5 = {}) { const pendingReplacements = []; text4.replace(/(fa[bklrs]?):fa-([\w-]+)/g, (fullMatch, prefix, iconName) => { pendingReplacements.push( (async () => { const registeredIconName = `${prefix}:${iconName}`; if (await isIconAvailable(registeredIconName)) { return await getIconSVG(registeredIconName, void 0, { class: "label-icon" }); } else { return ``; } })() ); return fullMatch; }); const replacements = await Promise.all(pendingReplacements); return text4.replace(/(fa[bklrs]?):fa-([\w-]+)/g, () => replacements.shift() ?? ""); } var maxSafeSizeForWidth, createText; var init_createText = __esm({ "src/rendering-util/createText.ts"() { "use strict"; init_src32(); init_common(); init_logger(); init_handle_markdown_text(); init_utils2(); init_icons(); init_splitText(); init_config(); __name(applyStyle, "applyStyle"); maxSafeSizeForWidth = 16384; __name(addHtmlSpan, "addHtmlSpan"); __name(createTspan, "createTspan"); __name(computeWidthOfText, "computeWidthOfText"); __name(computeDimensionOfText, "computeDimensionOfText"); __name(createFormattedText, "createFormattedText"); __name(updateTextContentAndStyles, "updateTextContentAndStyles"); __name(replaceIconSubstring, "replaceIconSubstring"); createText = /* @__PURE__ */ __name(async (el, text4 = "", { style: style3 = "", isTitle = false, classes: classes3 = "", useHtmlLabels = true, markdown = true, isNode: isNode2 = true, /** * The width to wrap the text within. Set to `Number.POSITIVE_INFINITY` for no wrapping. */ width: width3 = 200, addSvgBackground = false } = {}, config5) => { log.debug( "XYZ createText", text4, style3, isTitle, classes3, useHtmlLabels, isNode2, "addSvgBackground: ", addSvgBackground ); if (useHtmlLabels) { const htmlText = markdown ? markdownToHTML(text4, config5) : nonMarkdownToHTML(text4); const decodedReplacedText = await replaceIconSubstring(decodeEntities(htmlText), config5); const inputForKatex = text4.replace(/\\\\/g, "\\"); const node2 = { isNode: isNode2, label: hasKatex(text4) ? inputForKatex : decodedReplacedText, labelStyle: style3.replace("fill:", "color:") }; const vertexNode = await addHtmlSpan(el, node2, width3, classes3, addSvgBackground, config5); return vertexNode; } else { const sanitizeBR = text4.replace(/\` around edge labels.
*
* TODO: We should probably remove this in a future release.
*/
p {
margin: 0;
padding: 0;
display: inline;
}
rect {
opacity: 0.5;
background-color: ${options2.edgeLabelBackground};
fill: ${options2.edgeLabelBackground};
}
text-align: center;
}
/* For html labels only */
.labelBkg {
background-color: ${options2.edgeLabelBackground};
}
.node .cluster {
// fill: ${fade3(options2.mainBkg, 0.5)};
fill: ${fade3(options2.clusterBkg, 0.5)};
stroke: ${fade3(options2.clusterBorder, 0.2)};
box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px;
stroke-width: 1px;
}
.cluster text {
fill: ${options2.titleColor};
}
.cluster span,p {
color: ${options2.titleColor};
}
/* .cluster div {
color: ${options2.titleColor};
} */
div.mermaidTooltip {
position: absolute;
text-align: center;
max-width: 200px;
padding: 2px;
font-family: ${options2.fontFamily};
font-size: 12px;
background: ${options2.tertiaryColor};
border: 1px solid ${options2.border2};
border-radius: 2px;
pointer-events: none;
z-index: 100;
}
.flowchartTitleText {
text-anchor: middle;
font-size: 18px;
fill: ${options2.textColor};
}
${getIconStyles()}
`, "getStyles");
styles_default16 = getStyles17;
}
});
// src/dagre-wrapper/markers.js
var insertMarkers3, extension4, composition2, aggregation2, dependency2, lollipop2, point7, circle4, cross2, barb2, markers2, markers_default2;
var init_markers2 = __esm({
"src/dagre-wrapper/markers.js"() {
"use strict";
init_logger();
insertMarkers3 = /* @__PURE__ */ __name((elem, markerArray, type3, id32) => {
markerArray.forEach((markerName) => {
markers2[markerName](elem, type3, id32);
});
}, "insertMarkers");
extension4 = /* @__PURE__ */ __name((elem, type3, id32) => {
log.trace("Making markers for ", id32);
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-extensionStart").attr("class", "marker extension " + type3).attr("refX", 18).attr("refY", 7).attr("markerWidth", 190).attr("markerHeight", 240).attr("orient", "auto").append("path").attr("d", "M 1,7 L18,13 V 1 Z");
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-extensionEnd").attr("class", "marker extension " + type3).attr("refX", 1).attr("refY", 7).attr("markerWidth", 20).attr("markerHeight", 28).attr("orient", "auto").append("path").attr("d", "M 1,1 V 13 L18,7 Z");
}, "extension");
composition2 = /* @__PURE__ */ __name((elem, type3, id32) => {
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-compositionStart").attr("class", "marker composition " + type3).attr("refX", 18).attr("refY", 7).attr("markerWidth", 190).attr("markerHeight", 240).attr("orient", "auto").append("path").attr("d", "M 18,7 L9,13 L1,7 L9,1 Z");
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-compositionEnd").attr("class", "marker composition " + type3).attr("refX", 1).attr("refY", 7).attr("markerWidth", 20).attr("markerHeight", 28).attr("orient", "auto").append("path").attr("d", "M 18,7 L9,13 L1,7 L9,1 Z");
}, "composition");
aggregation2 = /* @__PURE__ */ __name((elem, type3, id32) => {
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-aggregationStart").attr("class", "marker aggregation " + type3).attr("refX", 18).attr("refY", 7).attr("markerWidth", 190).attr("markerHeight", 240).attr("orient", "auto").append("path").attr("d", "M 18,7 L9,13 L1,7 L9,1 Z");
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-aggregationEnd").attr("class", "marker aggregation " + type3).attr("refX", 1).attr("refY", 7).attr("markerWidth", 20).attr("markerHeight", 28).attr("orient", "auto").append("path").attr("d", "M 18,7 L9,13 L1,7 L9,1 Z");
}, "aggregation");
dependency2 = /* @__PURE__ */ __name((elem, type3, id32) => {
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-dependencyStart").attr("class", "marker dependency " + type3).attr("refX", 6).attr("refY", 7).attr("markerWidth", 190).attr("markerHeight", 240).attr("orient", "auto").append("path").attr("d", "M 5,7 L9,13 L1,7 L9,1 Z");
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-dependencyEnd").attr("class", "marker dependency " + type3).attr("refX", 13).attr("refY", 7).attr("markerWidth", 20).attr("markerHeight", 28).attr("orient", "auto").append("path").attr("d", "M 18,7 L9,13 L14,7 L9,1 Z");
}, "dependency");
lollipop2 = /* @__PURE__ */ __name((elem, type3, id32) => {
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-lollipopStart").attr("class", "marker lollipop " + type3).attr("refX", 13).attr("refY", 7).attr("markerWidth", 190).attr("markerHeight", 240).attr("orient", "auto").append("circle").attr("stroke", "black").attr("fill", "transparent").attr("cx", 7).attr("cy", 7).attr("r", 6);
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-lollipopEnd").attr("class", "marker lollipop " + type3).attr("refX", 1).attr("refY", 7).attr("markerWidth", 190).attr("markerHeight", 240).attr("orient", "auto").append("circle").attr("stroke", "black").attr("fill", "transparent").attr("cx", 7).attr("cy", 7).attr("r", 6);
}, "lollipop");
point7 = /* @__PURE__ */ __name((elem, type3, id32) => {
elem.append("marker").attr("id", id32 + "_" + type3 + "-pointEnd").attr("class", "marker " + type3).attr("viewBox", "0 0 10 10").attr("refX", 6).attr("refY", 5).attr("markerUnits", "userSpaceOnUse").attr("markerWidth", 12).attr("markerHeight", 12).attr("orient", "auto").append("path").attr("d", "M 0 0 L 10 5 L 0 10 z").attr("class", "arrowMarkerPath").style("stroke-width", 1).style("stroke-dasharray", "1,0");
elem.append("marker").attr("id", id32 + "_" + type3 + "-pointStart").attr("class", "marker " + type3).attr("viewBox", "0 0 10 10").attr("refX", 4.5).attr("refY", 5).attr("markerUnits", "userSpaceOnUse").attr("markerWidth", 12).attr("markerHeight", 12).attr("orient", "auto").append("path").attr("d", "M 0 5 L 10 10 L 10 0 z").attr("class", "arrowMarkerPath").style("stroke-width", 1).style("stroke-dasharray", "1,0");
}, "point");
circle4 = /* @__PURE__ */ __name((elem, type3, id32) => {
elem.append("marker").attr("id", id32 + "_" + type3 + "-circleEnd").attr("class", "marker " + type3).attr("viewBox", "0 0 10 10").attr("refX", 11).attr("refY", 5).attr("markerUnits", "userSpaceOnUse").attr("markerWidth", 11).attr("markerHeight", 11).attr("orient", "auto").append("circle").attr("cx", "5").attr("cy", "5").attr("r", "5").attr("class", "arrowMarkerPath").style("stroke-width", 1).style("stroke-dasharray", "1,0");
elem.append("marker").attr("id", id32 + "_" + type3 + "-circleStart").attr("class", "marker " + type3).attr("viewBox", "0 0 10 10").attr("refX", -1).attr("refY", 5).attr("markerUnits", "userSpaceOnUse").attr("markerWidth", 11).attr("markerHeight", 11).attr("orient", "auto").append("circle").attr("cx", "5").attr("cy", "5").attr("r", "5").attr("class", "arrowMarkerPath").style("stroke-width", 1).style("stroke-dasharray", "1,0");
}, "circle");
cross2 = /* @__PURE__ */ __name((elem, type3, id32) => {
elem.append("marker").attr("id", id32 + "_" + type3 + "-crossEnd").attr("class", "marker cross " + type3).attr("viewBox", "0 0 11 11").attr("refX", 12).attr("refY", 5.2).attr("markerUnits", "userSpaceOnUse").attr("markerWidth", 11).attr("markerHeight", 11).attr("orient", "auto").append("path").attr("d", "M 1,1 l 9,9 M 10,1 l -9,9").attr("class", "arrowMarkerPath").style("stroke-width", 2).style("stroke-dasharray", "1,0");
elem.append("marker").attr("id", id32 + "_" + type3 + "-crossStart").attr("class", "marker cross " + type3).attr("viewBox", "0 0 11 11").attr("refX", -1).attr("refY", 5.2).attr("markerUnits", "userSpaceOnUse").attr("markerWidth", 11).attr("markerHeight", 11).attr("orient", "auto").append("path").attr("d", "M 1,1 l 9,9 M 10,1 l -9,9").attr("class", "arrowMarkerPath").style("stroke-width", 2).style("stroke-dasharray", "1,0");
}, "cross");
barb2 = /* @__PURE__ */ __name((elem, type3, id32) => {
elem.append("defs").append("marker").attr("id", id32 + "_" + type3 + "-barbEnd").attr("refX", 19).attr("refY", 7).attr("markerWidth", 20).attr("markerHeight", 14).attr("markerUnits", "strokeWidth").attr("orient", "auto").append("path").attr("d", "M 19,7 L9,13 L14,7 L9,1 Z");
}, "barb");
markers2 = {
extension: extension4,
composition: composition2,
aggregation: aggregation2,
dependency: dependency2,
lollipop: lollipop2,
point: point7,
circle: circle4,
cross: cross2,
barb: barb2
};
markers_default2 = insertMarkers3;
}
});
// src/diagrams/block/layout.ts
function calculateBlockPosition(columns, position5) {
if (columns === 0 || !Number.isInteger(columns)) {
throw new Error("Columns must be an integer !== 0.");
}
if (position5 < 0 || !Number.isInteger(position5)) {
throw new Error("Position must be a non-negative integer." + position5);
}
if (columns < 0) {
return { px: position5, py: 0 };
}
if (columns === 1) {
return { px: 0, py: position5 };
}
const px = position5 % columns;
const py = Math.floor(position5 / columns);
return { px, py };
}
function setBlockSizes(block2, db8, siblingWidth = 0, siblingHeight = 0) {
log.debug(
"setBlockSizes abc95 (start)",
block2.id,
block2?.size?.x,
"block width =",
block2?.size,
"siblingWidth",
siblingWidth
);
if (!block2?.size?.width) {
block2.size = {
width: siblingWidth,
height: siblingHeight,
x: 0,
y: 0
};
}
let maxWidth2 = 0;
let maxHeight = 0;
if (block2.children?.length > 0) {
for (const child of block2.children) {
setBlockSizes(child, db8);
}
const childSize = getMaxChildSize(block2);
maxWidth2 = childSize.width;
maxHeight = childSize.height;
log.debug("setBlockSizes abc95 maxWidth of", block2.id, ":s children is ", maxWidth2, maxHeight);
for (const child of block2.children) {
if (child.size) {
log.debug(
`abc95 Setting size of children of ${block2.id} id=${child.id} ${maxWidth2} ${maxHeight} ${JSON.stringify(child.size)}`
);
child.size.width = maxWidth2 * (child.widthInColumns ?? 1) + padding * ((child.widthInColumns ?? 1) - 1);
child.size.height = maxHeight;
child.size.x = 0;
child.size.y = 0;
log.debug(
`abc95 updating size of ${block2.id} children child:${child.id} maxWidth:${maxWidth2} maxHeight:${maxHeight}`
);
}
}
for (const child of block2.children) {
setBlockSizes(child, db8, maxWidth2, maxHeight);
}
const columns = block2.columns ?? -1;
let numItems = 0;
for (const child of block2.children) {
numItems += child.widthInColumns ?? 1;
}
let xSize = block2.children.length;
if (columns > 0 && columns < numItems) {
xSize = columns;
}
const ySize = Math.ceil(numItems / xSize);
let width3 = xSize * (maxWidth2 + padding) + padding;
let height2 = ySize * (maxHeight + padding) + padding;
if (width3 < siblingWidth) {
log.debug(
`Detected to small sibling: abc95 ${block2.id} siblingWidth ${siblingWidth} siblingHeight ${siblingHeight} width ${width3}`
);
width3 = siblingWidth;
height2 = siblingHeight;
const childWidth = (siblingWidth - xSize * padding - padding) / xSize;
const childHeight = (siblingHeight - ySize * padding - padding) / ySize;
log.debug("Size indata abc88", block2.id, "childWidth", childWidth, "maxWidth", maxWidth2);
log.debug("Size indata abc88", block2.id, "childHeight", childHeight, "maxHeight", maxHeight);
log.debug("Size indata abc88 xSize", xSize, "padding", padding);
for (const child of block2.children) {
if (child.size) {
child.size.width = childWidth;
child.size.height = childHeight;
child.size.x = 0;
child.size.y = 0;
}
}
}
log.debug(
`abc95 (finale calc) ${block2.id} xSize ${xSize} ySize ${ySize} columns ${columns}${block2.children.length} width=${Math.max(width3, block2.size?.width || 0)}`
);
if (width3 < (block2?.size?.width || 0)) {
width3 = block2?.size?.width || 0;
const num = columns > 0 ? Math.min(block2.children.length, columns) : block2.children.length;
if (num > 0) {
const childWidth = (width3 - num * padding - padding) / num;
log.debug("abc95 (growing to fit) width", block2.id, width3, block2.size?.width, childWidth);
for (const child of block2.children) {
if (child.size) {
child.size.width = childWidth;
}
}
}
}
block2.size = {
width: width3,
height: height2,
x: 0,
y: 0
};
}
log.debug(
"setBlockSizes abc94 (done)",
block2.id,
block2?.size?.x,
block2?.size?.width,
block2?.size?.y,
block2?.size?.height
);
}
function layoutBlocks(block2, db8) {
log.debug(
`abc85 layout blocks (=>layoutBlocks) ${block2.id} x: ${block2?.size?.x} y: ${block2?.size?.y} width: ${block2?.size?.width}`
);
const columns = block2.columns ?? -1;
log.debug("layoutBlocks columns abc95", block2.id, "=>", columns, block2);
if (block2.children && // find max width of children
block2.children.length > 0) {
const width3 = block2?.children[0]?.size?.width ?? 0;
const widthOfChildren = block2.children.length * width3 + (block2.children.length - 1) * padding;
log.debug("widthOfChildren 88", widthOfChildren, "posX");
const rowHeights = /* @__PURE__ */ new Map();
{
let colPos = 0;
for (const child of block2.children) {
if (!child.size) {
continue;
}
const { py } = calculateBlockPosition(columns, colPos);
const currentMax = rowHeights.get(py) ?? 0;
if (child.size.height > currentMax) {
rowHeights.set(py, child.size.height);
}
let filled = child?.widthInColumns ?? 1;
if (columns > 0) {
filled = Math.min(filled, columns - colPos % columns);
}
colPos += filled;
}
}
const rowYOffsets = /* @__PURE__ */ new Map();
{
let offset = 0;
const rows = [...rowHeights.keys()].sort((a2, b3) => a2 - b3);
for (const row of rows) {
rowYOffsets.set(row, offset);
offset += (rowHeights.get(row) ?? 0) + padding;
}
}
let columnPos = 0;
log.debug("abc91 block?.size?.x", block2.id, block2?.size?.x);
let startingPosX = block2?.size?.x ? block2?.size?.x + (-block2?.size?.width / 2 || 0) : -padding;
let rowPos = 0;
for (const child of block2.children) {
const parent4 = block2;
if (!child.size) {
continue;
}
const { width: width4, height: height2 } = child.size;
const { px, py } = calculateBlockPosition(columns, columnPos);
if (py != rowPos) {
rowPos = py;
startingPosX = block2?.size?.x ? block2?.size?.x + (-block2?.size?.width / 2 || 0) : -padding;
log.debug("New row in layout for block", block2.id, " and child ", child.id, rowPos);
}
log.debug(
`abc89 layout blocks (child) id: ${child.id} Pos: ${columnPos} (px, py) ${px},${py} (${parent4?.size?.x},${parent4?.size?.y}) parent: ${parent4.id} width: ${width4}${padding}`
);
if (parent4.size) {
const halfWidth = width4 / 2;
child.size.x = startingPosX + padding + halfWidth;
log.debug(
`abc91 layout blocks (calc) px, pyid:${child.id} startingPos=X${startingPosX} new startingPosX${child.size.x} ${halfWidth} padding=${padding} width=${width4} halfWidth=${halfWidth} => x:${child.size.x} y:${child.size.y} ${child.widthInColumns} (width * (child?.w || 1)) / 2 ${width4 * (child?.widthInColumns ?? 1) / 2}`
);
startingPosX = child.size.x + halfWidth;
const rowYOffset = rowYOffsets.get(py) ?? 0;
const rowHeight = rowHeights.get(py) ?? height2;
child.size.y = parent4.size.y - parent4.size.height / 2 + rowYOffset + rowHeight / 2 + padding;
log.debug(
`abc88 layout blocks (calc) px, pyid:${child.id}startingPosX${startingPosX}${padding}${halfWidth}=>x:${child.size.x}y:${child.size.y}${child.widthInColumns}(width * (child?.w || 1)) / 2${width4 * (child?.widthInColumns ?? 1) / 2}`
);
}
if (child.children) {
layoutBlocks(child, db8);
}
let columnsFilled = child?.widthInColumns ?? 1;
if (columns > 0) {
columnsFilled = Math.min(columnsFilled, columns - columnPos % columns);
}
columnPos += columnsFilled;
log.debug("abc88 columnsPos", child, columnPos);
}
}
log.debug(
`layout blocks (<==layoutBlocks) ${block2.id} x: ${block2?.size?.x} y: ${block2?.size?.y} width: ${block2?.size?.width}`
);
}
function findBounds(block2, { minX, minY, maxX, maxY } = { minX: 0, minY: 0, maxX: 0, maxY: 0 }) {
if (block2.size && block2.id !== "root") {
const { x: x5, y: y6, width: width3, height: height2 } = block2.size;
if (x5 - width3 / 2 < minX) {
minX = x5 - width3 / 2;
}
if (y6 - height2 / 2 < minY) {
minY = y6 - height2 / 2;
}
if (x5 + width3 / 2 > maxX) {
maxX = x5 + width3 / 2;
}
if (y6 + height2 / 2 > maxY) {
maxY = y6 + height2 / 2;
}
}
if (block2.children) {
for (const child of block2.children) {
({ minX, minY, maxX, maxY } = findBounds(child, { minX, minY, maxX, maxY }));
}
}
return { minX, minY, maxX, maxY };
}
function layout5(db8) {
const root3 = db8.getBlock("root");
if (!root3) {
return;
}
setBlockSizes(root3, db8, 0, 0);
layoutBlocks(root3, db8);
log.debug("getBlocks", JSON.stringify(root3, null, 2));
const { minX, minY, maxX, maxY } = findBounds(root3);
const height2 = maxY - minY;
const width3 = maxX - minX;
return { x: minX, y: minY, width: width3, height: height2 };
}
var padding, getMaxChildSize;
var init_layout3 = __esm({
"src/diagrams/block/layout.ts"() {
"use strict";
init_logger();
init_diagramAPI();
padding = getConfig2()?.block?.padding ?? 8;
__name(calculateBlockPosition, "calculateBlockPosition");
getMaxChildSize = /* @__PURE__ */ __name((block2) => {
let maxWidth2 = 0;
let maxHeight = 0;
for (const child of block2.children) {
const { width: width3, height: height2, x: x5, y: y6 } = child.size ?? { width: 0, height: 0, x: 0, y: 0 };
log.debug(
"getMaxChildSize abc95 child:",
child.id,
"width:",
width3,
"height:",
height2,
"x:",
x5,
"y:",
y6,
child.type
);
if (child.type === "space") {
continue;
}
if (width3 > maxWidth2) {
maxWidth2 = width3 / (child.widthInColumns ?? 1);
}
if (height2 > maxHeight) {
maxHeight = height2;
}
}
return { width: maxWidth2, height: maxHeight };
}, "getMaxChildSize");
__name(setBlockSizes, "setBlockSizes");
__name(layoutBlocks, "layoutBlocks");
__name(findBounds, "findBounds");
__name(layout5, "layout");
}
});
// src/dagre-wrapper/createLabel.js
var createLabel2, createLabel_default2;
var init_createLabel2 = __esm({
"src/dagre-wrapper/createLabel.js"() {
"use strict";
init_config();
init_diagramAPI();
init_createText();
createLabel2 = /* @__PURE__ */ __name(async (element3, _vertexText, style3, isTitle = false, isNode2 = false) => {
let vertexText = _vertexText || "";
if (typeof vertexText === "object") {
vertexText = vertexText[0];
}
const config5 = getConfig2();
const useHtmlLabels = getEffectiveHtmlLabels(config5);
return await createText(
element3,
vertexText,
{
style: style3,
isTitle,
useHtmlLabels,
markdown: false,
isNode: isNode2,
width: Number.POSITIVE_INFINITY
},
config5
);
}, "createLabel");
createLabel_default2 = createLabel2;
}
});
// src/dagre-wrapper/edgeMarker.ts
var addEdgeMarkers2, arrowTypesMap2, addEdgeMarker2;
var init_edgeMarker2 = __esm({
"src/dagre-wrapper/edgeMarker.ts"() {
"use strict";
init_logger();
addEdgeMarkers2 = /* @__PURE__ */ __name((svgPath, edge, url, id32, diagramType) => {
if (edge.arrowTypeStart) {
addEdgeMarker2(svgPath, "start", edge.arrowTypeStart, url, id32, diagramType);
}
if (edge.arrowTypeEnd) {
addEdgeMarker2(svgPath, "end", edge.arrowTypeEnd, url, id32, diagramType);
}
}, "addEdgeMarkers");
arrowTypesMap2 = {
arrow_cross: "cross",
arrow_point: "point",
arrow_barb: "barb",
arrow_circle: "circle",
aggregation: "aggregation",
extension: "extension",
composition: "composition",
dependency: "dependency",
lollipop: "lollipop"
};
addEdgeMarker2 = /* @__PURE__ */ __name((svgPath, position5, arrowType, url, id32, diagramType) => {
const endMarkerType = arrowTypesMap2[arrowType];
if (!endMarkerType) {
log.warn(`Unknown arrow type: ${arrowType}`);
return;
}
const suffix = position5 === "start" ? "Start" : "End";
svgPath.attr(`marker-${position5}`, `url(${url}#${id32}_${diagramType}-${endMarkerType}${suffix})`);
}, "addEdgeMarker");
}
});
// src/dagre-wrapper/edges.js
function setTerminalWidth2(fo, value2) {
if (getEffectiveHtmlLabels(getConfig2()) && fo) {
fo.style.width = value2.length * 9 + "px";
fo.style.height = "12px";
}
}
var edgeLabels2, terminalLabels2, insertEdgeLabel2, positionEdgeLabel2, outsideNode2, intersection3, cutPathAtIntersect2, insertEdge2;
var init_edges2 = __esm({
"src/dagre-wrapper/edges.js"() {
"use strict";
init_logger();
init_createLabel2();
init_createText();
init_labelTransform();
init_src32();
init_diagramAPI();
init_config();
init_utils2();
init_common();
init_lineWithOffset();
init_subGraphTitleMargins();
init_edgeMarker2();
edgeLabels2 = {};
terminalLabels2 = {};
insertEdgeLabel2 = /* @__PURE__ */ __name(async (elem, edge) => {
const config5 = getConfig2();
const useHtmlLabels = getEffectiveHtmlLabels(config5);
const edgeLabel = elem.insert("g").attr("class", "edgeLabel");
const label = edgeLabel.insert("g").attr("class", "label");
const isMarkdown = edge.labelType === "markdown";
const labelElement = await createText(
elem,
edge.label,
{
style: edge.labelStyle,
useHtmlLabels,
// TODO: The old code only set addSvgBackground when using markdown, but
// this function is only used by block diagrams which never use markdown.
addSvgBackground: isMarkdown,
isNode: false,
markdown: isMarkdown,
// If using markdown, wrap using default width
width: isMarkdown ? void 0 : Number.POSITIVE_INFINITY
},
config5
);
label.node().appendChild(labelElement);
let bbox = labelElement.getBBox();
let transformBbox = bbox;
if (useHtmlLabels) {
const div = labelElement.children[0];
const dv = select_default2(labelElement);
bbox = div.getBoundingClientRect();
transformBbox = bbox;
dv.attr("width", bbox.width);
dv.attr("height", bbox.height);
} else {
const textEl = select_default2(labelElement).select("text").node();
if (textEl && typeof textEl.getBBox === "function") {
transformBbox = textEl.getBBox();
}
}
label.attr("transform", computeLabelTransform(transformBbox, useHtmlLabels));
edgeLabels2[edge.id] = edgeLabel;
edge.width = bbox.width;
edge.height = bbox.height;
let fo;
if (edge.startLabelLeft) {
const startEdgeLabelLeft = elem.insert("g").attr("class", "edgeTerminals");
const inner2 = startEdgeLabelLeft.insert("g").attr("class", "inner");
const startLabelElement = await createLabel_default2(inner2, edge.startLabelLeft, edge.labelStyle);
fo = startLabelElement;
let slBox = startLabelElement.getBBox();
if (useHtmlLabels) {
const div = startLabelElement.children[0];
const dv = select_default2(startLabelElement);
slBox = div.getBoundingClientRect();
dv.attr("width", slBox.width);
dv.attr("height", slBox.height);
}
inner2.attr("transform", computeLabelTransform(slBox, useHtmlLabels));
if (!terminalLabels2[edge.id]) {
terminalLabels2[edge.id] = {};
}
terminalLabels2[edge.id].startLeft = startEdgeLabelLeft;
setTerminalWidth2(fo, edge.startLabelLeft);
}
if (edge.startLabelRight) {
const startEdgeLabelRight = elem.insert("g").attr("class", "edgeTerminals");
const inner2 = startEdgeLabelRight.insert("g").attr("class", "inner");
const startLabelElement = await createLabel_default2(
startEdgeLabelRight,
edge.startLabelRight,
edge.labelStyle
);
fo = startLabelElement;
inner2.node().appendChild(startLabelElement);
let slBox = startLabelElement.getBBox();
if (useHtmlLabels) {
const div = startLabelElement.children[0];
const dv = select_default2(startLabelElement);
slBox = div.getBoundingClientRect();
dv.attr("width", slBox.width);
dv.attr("height", slBox.height);
}
inner2.attr("transform", computeLabelTransform(slBox, useHtmlLabels));
if (!terminalLabels2[edge.id]) {
terminalLabels2[edge.id] = {};
}
terminalLabels2[edge.id].startRight = startEdgeLabelRight;
setTerminalWidth2(fo, edge.startLabelRight);
}
if (edge.endLabelLeft) {
const endEdgeLabelLeft = elem.insert("g").attr("class", "edgeTerminals");
const inner2 = endEdgeLabelLeft.insert("g").attr("class", "inner");
const endLabelElement = await createLabel_default2(inner2, edge.endLabelLeft, edge.labelStyle);
fo = endLabelElement;
let slBox = endLabelElement.getBBox();
if (useHtmlLabels) {
const div = endLabelElement.children[0];
const dv = select_default2(endLabelElement);
slBox = div.getBoundingClientRect();
dv.attr("width", slBox.width);
dv.attr("height", slBox.height);
}
inner2.attr("transform", computeLabelTransform(slBox, useHtmlLabels));
endEdgeLabelLeft.node().appendChild(endLabelElement);
if (!terminalLabels2[edge.id]) {
terminalLabels2[edge.id] = {};
}
terminalLabels2[edge.id].endLeft = endEdgeLabelLeft;
setTerminalWidth2(fo, edge.endLabelLeft);
}
if (edge.endLabelRight) {
const endEdgeLabelRight = elem.insert("g").attr("class", "edgeTerminals");
const inner2 = endEdgeLabelRight.insert("g").attr("class", "inner");
const endLabelElement = await createLabel_default2(inner2, edge.endLabelRight, edge.labelStyle);
fo = endLabelElement;
let slBox = endLabelElement.getBBox();
if (useHtmlLabels) {
const div = endLabelElement.children[0];
const dv = select_default2(endLabelElement);
slBox = div.getBoundingClientRect();
dv.attr("width", slBox.width);
dv.attr("height", slBox.height);
}
inner2.attr("transform", computeLabelTransform(slBox, useHtmlLabels));
endEdgeLabelRight.node().appendChild(endLabelElement);
if (!terminalLabels2[edge.id]) {
terminalLabels2[edge.id] = {};
}
terminalLabels2[edge.id].endRight = endEdgeLabelRight;
setTerminalWidth2(fo, edge.endLabelRight);
}
return labelElement;
}, "insertEdgeLabel");
__name(setTerminalWidth2, "setTerminalWidth");
positionEdgeLabel2 = /* @__PURE__ */ __name((edge, paths) => {
log.debug("Moving label abc88 ", edge.id, edge.label, edgeLabels2[edge.id], paths);
let path4 = paths.updatedPath ? paths.updatedPath : paths.originalPath;
const siteConfig2 = getConfig2();
const { subGraphTitleTotalMargin } = getSubGraphTitleMargins(siteConfig2);
if (edge.label) {
const el = edgeLabels2[edge.id];
let x5 = edge.x;
let y6 = edge.y;
if (path4) {
const pos = utils_default2.calcLabelPosition(path4);
log.debug(
"Moving label " + edge.label + " from (",
x5,
",",
y6,
") to (",
pos.x,
",",
pos.y,
") abc88"
);
if (paths.updatedPath) {
x5 = pos.x;
y6 = pos.y;
}
}
el.attr("transform", `translate(${x5}, ${y6 + subGraphTitleTotalMargin / 2})`);
}
if (edge.startLabelLeft) {
const el = terminalLabels2[edge.id].startLeft;
let x5 = edge.x;
let y6 = edge.y;
if (path4) {
const pos = utils_default2.calcTerminalLabelPosition(edge.arrowTypeStart ? 10 : 0, "start_left", path4);
x5 = pos.x;
y6 = pos.y;
}
el.attr("transform", `translate(${x5}, ${y6})`);
}
if (edge.startLabelRight) {
const el = terminalLabels2[edge.id].startRight;
let x5 = edge.x;
let y6 = edge.y;
if (path4) {
const pos = utils_default2.calcTerminalLabelPosition(
edge.arrowTypeStart ? 10 : 0,
"start_right",
path4
);
x5 = pos.x;
y6 = pos.y;
}
el.attr("transform", `translate(${x5}, ${y6})`);
}
if (edge.endLabelLeft) {
const el = terminalLabels2[edge.id].endLeft;
let x5 = edge.x;
let y6 = edge.y;
if (path4) {
const pos = utils_default2.calcTerminalLabelPosition(edge.arrowTypeEnd ? 10 : 0, "end_left", path4);
x5 = pos.x;
y6 = pos.y;
}
el.attr("transform", `translate(${x5}, ${y6})`);
}
if (edge.endLabelRight) {
const el = terminalLabels2[edge.id].endRight;
let x5 = edge.x;
let y6 = edge.y;
if (path4) {
const pos = utils_default2.calcTerminalLabelPosition(edge.arrowTypeEnd ? 10 : 0, "end_right", path4);
x5 = pos.x;
y6 = pos.y;
}
el.attr("transform", `translate(${x5}, ${y6})`);
}
}, "positionEdgeLabel");
outsideNode2 = /* @__PURE__ */ __name((node2, point8) => {
const x5 = node2.x;
const y6 = node2.y;
const dx = Math.abs(point8.x - x5);
const dy = Math.abs(point8.y - y6);
const w4 = node2.width / 2;
const h3 = node2.height / 2;
if (dx >= w4 || dy >= h3) {
return true;
}
return false;
}, "outsideNode");
intersection3 = /* @__PURE__ */ __name((node2, outsidePoint, insidePoint) => {
log.debug(`intersection calc abc89:
outsidePoint: ${JSON.stringify(outsidePoint)}
insidePoint : ${JSON.stringify(insidePoint)}
node : x:${node2.x} y:${node2.y} w:${node2.width} h:${node2.height}`);
const x5 = node2.x;
const y6 = node2.y;
const dx = Math.abs(x5 - insidePoint.x);
const w4 = node2.width / 2;
let r2 = insidePoint.x < outsidePoint.x ? w4 - dx : w4 + dx;
const h3 = node2.height / 2;
const Q3 = Math.abs(outsidePoint.y - insidePoint.y);
const R3 = Math.abs(outsidePoint.x - insidePoint.x);
if (Math.abs(y6 - outsidePoint.y) * w4 > Math.abs(x5 - outsidePoint.x) * h3) {
let q3 = insidePoint.y < outsidePoint.y ? outsidePoint.y - h3 - y6 : y6 - h3 - outsidePoint.y;
r2 = R3 * q3 / Q3;
const res = {
x: insidePoint.x < outsidePoint.x ? insidePoint.x + r2 : insidePoint.x - R3 + r2,
y: insidePoint.y < outsidePoint.y ? insidePoint.y + Q3 - q3 : insidePoint.y - Q3 + q3
};
if (r2 === 0) {
res.x = outsidePoint.x;
res.y = outsidePoint.y;
}
if (R3 === 0) {
res.x = outsidePoint.x;
}
if (Q3 === 0) {
res.y = outsidePoint.y;
}
log.debug(`abc89 topp/bott calc, Q ${Q3}, q ${q3}, R ${R3}, r ${r2}`, res);
return res;
} else {
if (insidePoint.x < outsidePoint.x) {
r2 = outsidePoint.x - w4 - x5;
} else {
r2 = x5 - w4 - outsidePoint.x;
}
let q3 = Q3 * r2 / R3;
let _x = insidePoint.x < outsidePoint.x ? insidePoint.x + R3 - r2 : insidePoint.x - R3 + r2;
let _y = insidePoint.y < outsidePoint.y ? insidePoint.y + q3 : insidePoint.y - q3;
log.debug(`sides calc abc89, Q ${Q3}, q ${q3}, R ${R3}, r ${r2}`, { _x, _y });
if (r2 === 0) {
_x = outsidePoint.x;
_y = outsidePoint.y;
}
if (R3 === 0) {
_x = outsidePoint.x;
}
if (Q3 === 0) {
_y = outsidePoint.y;
}
return { x: _x, y: _y };
}
}, "intersection");
cutPathAtIntersect2 = /* @__PURE__ */ __name((_points, boundaryNode) => {
log.debug("abc88 cutPathAtIntersect", _points, boundaryNode);
let points = [];
let lastPointOutside = _points[0];
let isInside = false;
_points.forEach((point8) => {
if (!outsideNode2(boundaryNode, point8) && !isInside) {
const inter = intersection3(boundaryNode, lastPointOutside, point8);
let pointPresent = false;
points.forEach((p3) => {
pointPresent = pointPresent || p3.x === inter.x && p3.y === inter.y;
});
if (!points.some((e3) => e3.x === inter.x && e3.y === inter.y)) {
points.push(inter);
}
isInside = true;
} else {
lastPointOutside = point8;
if (!isInside) {
points.push(point8);
}
}
});
return points;
}, "cutPathAtIntersect");
insertEdge2 = /* @__PURE__ */ __name(function(elem, e3, edge, clusterDb2, diagramType, graph, id32) {
let points = edge.points;
log.debug("abc88 InsertEdge: edge=", edge, "e=", e3);
let pointsHasChanged = false;
const tail = graph.node(e3.v);
var head2 = graph.node(e3.w);
if (head2?.intersect && tail?.intersect) {
points = points.slice(1, edge.points.length - 1);
points.unshift(tail.intersect(points[0]));
points.push(head2.intersect(points[points.length - 1]));
}
if (edge.toCluster) {
log.debug("to cluster abc88", clusterDb2[edge.toCluster]);
points = cutPathAtIntersect2(edge.points, clusterDb2[edge.toCluster].node);
pointsHasChanged = true;
}
if (edge.fromCluster) {
log.debug("from cluster abc88", clusterDb2[edge.fromCluster]);
points = cutPathAtIntersect2(points.reverse(), clusterDb2[edge.fromCluster].node).reverse();
pointsHasChanged = true;
}
const lineData = points.filter((p3) => !Number.isNaN(p3.y));
let curve = basis_default2;
if (edge.curve && (diagramType === "graph" || diagramType === "flowchart")) {
curve = edge.curve;
}
const { x: x5, y: y6 } = getLineFunctionsWithOffset(edge);
const lineFunction = line_default().x(x5).y(y6).curve(curve);
let strokeClasses;
switch (edge.thickness) {
case "normal":
strokeClasses = "edge-thickness-normal";
break;
case "thick":
strokeClasses = "edge-thickness-thick";
break;
case "invisible":
strokeClasses = "edge-thickness-thick";
break;
default:
strokeClasses = "";
}
switch (edge.pattern) {
case "solid":
strokeClasses += " edge-pattern-solid";
break;
case "dotted":
strokeClasses += " edge-pattern-dotted";
break;
case "dashed":
strokeClasses += " edge-pattern-dashed";
break;
}
const svgPath = elem.append("path").attr("d", lineFunction(lineData)).attr("id", edge.id).attr("class", " " + strokeClasses + (edge.classes ? " " + edge.classes : "")).attr("style", edge.style);
let url = "";
if (getConfig2().flowchart.arrowMarkerAbsolute || getConfig2().state.arrowMarkerAbsolute) {
url = getUrl(true);
}
addEdgeMarkers2(svgPath, edge, url, id32, diagramType);
let paths = {};
if (pointsHasChanged) {
paths.updatedPath = points;
}
paths.originalPath = edge.points;
return paths;
}, "insertEdge");
}
});
// src/dagre-wrapper/blockArrowHelper.ts
var expandAndDeduplicateDirections, getArrowPoints;
var init_blockArrowHelper = __esm({
"src/dagre-wrapper/blockArrowHelper.ts"() {
"use strict";
expandAndDeduplicateDirections = /* @__PURE__ */ __name((directions) => {
const uniqueDirections = /* @__PURE__ */ new Set();
for (const direction of directions) {
switch (direction) {
case "x":
uniqueDirections.add("right");
uniqueDirections.add("left");
break;
case "y":
uniqueDirections.add("up");
uniqueDirections.add("down");
break;
default:
uniqueDirections.add(direction);
break;
}
}
return uniqueDirections;
}, "expandAndDeduplicateDirections");
getArrowPoints = /* @__PURE__ */ __name((duplicatedDirections, bbox, node2) => {
const directions = expandAndDeduplicateDirections(duplicatedDirections);
const f2 = 2;
const height2 = bbox.height + 2 * node2.padding;
const midpoint3 = height2 / f2;
const width3 = bbox.width + 2 * midpoint3 + node2.padding;
const padding2 = node2.padding / 2;
if (directions.has("right") && directions.has("left") && directions.has("up") && directions.has("down")) {
return [
// Bottom
{ x: 0, y: 0 },
{ x: midpoint3, y: 0 },
{ x: width3 / 2, y: 2 * padding2 },
{ x: width3 - midpoint3, y: 0 },
{ x: width3, y: 0 },
// Right
{ x: width3, y: -height2 / 3 },
{ x: width3 + 2 * padding2, y: -height2 / 2 },
{ x: width3, y: -2 * height2 / 3 },
{ x: width3, y: -height2 },
// Top
{ x: width3 - midpoint3, y: -height2 },
{ x: width3 / 2, y: -height2 - 2 * padding2 },
{ x: midpoint3, y: -height2 },
// Left
{ x: 0, y: -height2 },
{ x: 0, y: -2 * height2 / 3 },
{ x: -2 * padding2, y: -height2 / 2 },
{ x: 0, y: -height2 / 3 }
];
}
if (directions.has("right") && directions.has("left") && directions.has("up")) {
return [
{ x: midpoint3, y: 0 },
{ x: width3 - midpoint3, y: 0 },
{ x: width3, y: -height2 / 2 },
{ x: width3 - midpoint3, y: -height2 },
{ x: midpoint3, y: -height2 },
{ x: 0, y: -height2 / 2 }
];
}
if (directions.has("right") && directions.has("left") && directions.has("down")) {
return [
{ x: 0, y: 0 },
{ x: midpoint3, y: -height2 },
{ x: width3 - midpoint3, y: -height2 },
{ x: width3, y: 0 }
];
}
if (directions.has("right") && directions.has("up") && directions.has("down")) {
return [
{ x: 0, y: 0 },
{ x: width3, y: -midpoint3 },
{ x: width3, y: -height2 + midpoint3 },
{ x: 0, y: -height2 }
];
}
if (directions.has("left") && directions.has("up") && directions.has("down")) {
return [
{ x: width3, y: 0 },
{ x: 0, y: -midpoint3 },
{ x: 0, y: -height2 + midpoint3 },
{ x: width3, y: -height2 }
];
}
if (directions.has("right") && directions.has("left")) {
return [
{ x: midpoint3, y: 0 },
{ x: midpoint3, y: -padding2 },
{ x: width3 - midpoint3, y: -padding2 },
{ x: width3 - midpoint3, y: 0 },
{ x: width3, y: -height2 / 2 },
{ x: width3 - midpoint3, y: -height2 },
{ x: width3 - midpoint3, y: -height2 + padding2 },
{ x: midpoint3, y: -height2 + padding2 },
{ x: midpoint3, y: -height2 },
{ x: 0, y: -height2 / 2 }
];
}
if (directions.has("up") && directions.has("down")) {
return [
// Bottom center
{ x: width3 / 2, y: 0 },
// Left pont of bottom arrow
{ x: 0, y: -padding2 },
{ x: midpoint3, y: -padding2 },
// Left top over vertical section
{ x: midpoint3, y: -height2 + padding2 },
{ x: 0, y: -height2 + padding2 },
// Top of arrow
{ x: width3 / 2, y: -height2 },
{ x: width3, y: -height2 + padding2 },
// Top of right vertical bar
{ x: width3 - midpoint3, y: -height2 + padding2 },
{ x: width3 - midpoint3, y: -padding2 },
{ x: width3, y: -padding2 }
];
}
if (directions.has("right") && directions.has("up")) {
return [
{ x: 0, y: 0 },
{ x: width3, y: -midpoint3 },
{ x: 0, y: -height2 }
];
}
if (directions.has("right") && directions.has("down")) {
return [
{ x: 0, y: 0 },
{ x: width3, y: 0 },
{ x: 0, y: -height2 }
];
}
if (directions.has("left") && directions.has("up")) {
return [
{ x: width3, y: 0 },
{ x: 0, y: -midpoint3 },
{ x: width3, y: -height2 }
];
}
if (directions.has("left") && directions.has("down")) {
return [
{ x: width3, y: 0 },
{ x: 0, y: 0 },
{ x: width3, y: -height2 }
];
}
if (directions.has("right")) {
return [
{ x: midpoint3, y: -padding2 },
{ x: midpoint3, y: -padding2 },
{ x: width3 - midpoint3, y: -padding2 },
{ x: width3 - midpoint3, y: 0 },
{ x: width3, y: -height2 / 2 },
{ x: width3 - midpoint3, y: -height2 },
{ x: width3 - midpoint3, y: -height2 + padding2 },
// top left corner of arrow
{ x: midpoint3, y: -height2 + padding2 },
{ x: midpoint3, y: -height2 + padding2 }
];
}
if (directions.has("left")) {
return [
{ x: midpoint3, y: 0 },
{ x: midpoint3, y: -padding2 },
// Two points, the right corners
{ x: width3 - midpoint3, y: -padding2 },
{ x: width3 - midpoint3, y: -height2 + padding2 },
{ x: midpoint3, y: -height2 + padding2 },
{ x: midpoint3, y: -height2 },
{ x: 0, y: -height2 / 2 }
];
}
if (directions.has("up")) {
return [
// Bottom center
{ x: midpoint3, y: -padding2 },
// Left top over vertical section
{ x: midpoint3, y: -height2 + padding2 },
{ x: 0, y: -height2 + padding2 },
// Top of arrow
{ x: width3 / 2, y: -height2 },
{ x: width3, y: -height2 + padding2 },
// Top of right vertical bar
{ x: width3 - midpoint3, y: -height2 + padding2 },
{ x: width3 - midpoint3, y: -padding2 }
];
}
if (directions.has("down")) {
return [
// Bottom center
{ x: width3 / 2, y: 0 },
// Left pont of bottom arrow
{ x: 0, y: -padding2 },
{ x: midpoint3, y: -padding2 },
// Left top over vertical section
{ x: midpoint3, y: -height2 + padding2 },
{ x: width3 - midpoint3, y: -height2 + padding2 },
{ x: width3 - midpoint3, y: -padding2 },
{ x: width3, y: -padding2 }
];
}
return [{ x: 0, y: 0 }];
}, "getArrowPoints");
}
});
// src/dagre-wrapper/intersect/intersect-node.js
function intersectNode2(node2, point8) {
return node2.intersect(point8);
}
var intersect_node_default2;
var init_intersect_node2 = __esm({
"src/dagre-wrapper/intersect/intersect-node.js"() {
"use strict";
__name(intersectNode2, "intersectNode");
intersect_node_default2 = intersectNode2;
}
});
// src/dagre-wrapper/intersect/intersect-ellipse.js
function intersectEllipse2(node2, rx, ry, point8) {
var cx = node2.x;
var cy = node2.y;
var px = cx - point8.x;
var py = cy - point8.y;
var det = Math.sqrt(rx * rx * py * py + ry * ry * px * px);
var dx = Math.abs(rx * ry * px / det);
if (point8.x < cx) {
dx = -dx;
}
var dy = Math.abs(rx * ry * py / det);
if (point8.y < cy) {
dy = -dy;
}
return { x: cx + dx, y: cy + dy };
}
var intersect_ellipse_default2;
var init_intersect_ellipse2 = __esm({
"src/dagre-wrapper/intersect/intersect-ellipse.js"() {
"use strict";
__name(intersectEllipse2, "intersectEllipse");
intersect_ellipse_default2 = intersectEllipse2;
}
});
// src/dagre-wrapper/intersect/intersect-circle.js
function intersectCircle2(node2, rx, point8) {
return intersect_ellipse_default2(node2, rx, rx, point8);
}
var intersect_circle_default2;
var init_intersect_circle2 = __esm({
"src/dagre-wrapper/intersect/intersect-circle.js"() {
"use strict";
init_intersect_ellipse2();
__name(intersectCircle2, "intersectCircle");
intersect_circle_default2 = intersectCircle2;
}
});
// src/dagre-wrapper/intersect/intersect-line.js
function intersectLine2(p1, p22, q1, q22) {
var a1, a2, b1, b22, c1, c22;
var r1, r2, r3, r4;
var denom, offset, num;
var x5, y6;
a1 = p22.y - p1.y;
b1 = p1.x - p22.x;
c1 = p22.x * p1.y - p1.x * p22.y;
r3 = a1 * q1.x + b1 * q1.y + c1;
r4 = a1 * q22.x + b1 * q22.y + c1;
if (r3 !== 0 && r4 !== 0 && sameSign2(r3, r4)) {
return;
}
a2 = q22.y - q1.y;
b22 = q1.x - q22.x;
c22 = q22.x * q1.y - q1.x * q22.y;
r1 = a2 * p1.x + b22 * p1.y + c22;
r2 = a2 * p22.x + b22 * p22.y + c22;
if (r1 !== 0 && r2 !== 0 && sameSign2(r1, r2)) {
return;
}
denom = a1 * b22 - a2 * b1;
if (denom === 0) {
return;
}
offset = Math.abs(denom / 2);
num = b1 * c22 - b22 * c1;
x5 = num < 0 ? (num - offset) / denom : (num + offset) / denom;
num = a2 * c1 - a1 * c22;
y6 = num < 0 ? (num - offset) / denom : (num + offset) / denom;
return { x: x5, y: y6 };
}
function sameSign2(r1, r2) {
return r1 * r2 > 0;
}
var intersect_line_default2;
var init_intersect_line2 = __esm({
"src/dagre-wrapper/intersect/intersect-line.js"() {
"use strict";
__name(intersectLine2, "intersectLine");
__name(sameSign2, "sameSign");
intersect_line_default2 = intersectLine2;
}
});
// src/dagre-wrapper/intersect/intersect-polygon.js
function intersectPolygon2(node2, polyPoints, point8) {
var x1 = node2.x;
var y1 = node2.y;
var intersections = [];
var minX = Number.POSITIVE_INFINITY;
var minY = Number.POSITIVE_INFINITY;
if (typeof polyPoints.forEach === "function") {
polyPoints.forEach(function(entry) {
minX = Math.min(minX, entry.x);
minY = Math.min(minY, entry.y);
});
} else {
minX = Math.min(minX, polyPoints.x);
minY = Math.min(minY, polyPoints.y);
}
var left3 = x1 - node2.width / 2 - minX;
var top2 = y1 - node2.height / 2 - minY;
for (var i2 = 0; i2 < polyPoints.length; i2++) {
var p1 = polyPoints[i2];
var p22 = polyPoints[i2 < polyPoints.length - 1 ? i2 + 1 : 0];
var intersect3 = intersect_line_default2(
node2,
point8,
{ x: left3 + p1.x, y: top2 + p1.y },
{ x: left3 + p22.x, y: top2 + p22.y }
);
if (intersect3) {
intersections.push(intersect3);
}
}
if (!intersections.length) {
return node2;
}
if (intersections.length > 1) {
intersections.sort(function(p3, q3) {
var pdx = p3.x - point8.x;
var pdy = p3.y - point8.y;
var distp = Math.sqrt(pdx * pdx + pdy * pdy);
var qdx = q3.x - point8.x;
var qdy = q3.y - point8.y;
var distq = Math.sqrt(qdx * qdx + qdy * qdy);
return distp < distq ? -1 : distp === distq ? 0 : 1;
});
}
return intersections[0];
}
var intersect_polygon_default2;
var init_intersect_polygon2 = __esm({
"src/dagre-wrapper/intersect/intersect-polygon.js"() {
"use strict";
init_intersect_line2();
intersect_polygon_default2 = intersectPolygon2;
__name(intersectPolygon2, "intersectPolygon");
}
});
// src/dagre-wrapper/intersect/intersect-rect.js
var intersectRect3, intersect_rect_default2;
var init_intersect_rect2 = __esm({
"src/dagre-wrapper/intersect/intersect-rect.js"() {
"use strict";
intersectRect3 = /* @__PURE__ */ __name((node2, point8) => {
var x5 = node2.x;
var y6 = node2.y;
var dx = point8.x - x5;
var dy = point8.y - y6;
var w4 = node2.width / 2;
var h3 = node2.height / 2;
var sx, sy;
if (Math.abs(dy) * w4 > Math.abs(dx) * h3) {
if (dy < 0) {
h3 = -h3;
}
sx = dy === 0 ? 0 : h3 * dx / dy;
sy = h3;
} else {
if (dx < 0) {
w4 = -w4;
}
sx = w4;
sy = dx === 0 ? 0 : w4 * dy / dx;
}
return { x: x5 + sx, y: y6 + sy };
}, "intersectRect");
intersect_rect_default2 = intersectRect3;
}
});
// src/dagre-wrapper/intersect/index.js
var intersect_default2;
var init_intersect2 = __esm({
"src/dagre-wrapper/intersect/index.js"() {
"use strict";
init_intersect_node2();
init_intersect_circle2();
init_intersect_ellipse2();
init_intersect_polygon2();
init_intersect_rect2();
intersect_default2 = {
node: intersect_node_default2,
circle: intersect_circle_default2,
ellipse: intersect_ellipse_default2,
polygon: intersect_polygon_default2,
rect: intersect_rect_default2
};
}
});
// src/dagre-wrapper/shapes/util.js
function insertPolygonShape2(parent4, w4, h3, points) {
return parent4.insert("polygon", ":first-child").attr(
"points",
points.map(function(d3) {
return d3.x + "," + d3.y;
}).join(" ")
).attr("class", "label-container").attr("transform", "translate(" + -w4 / 2 + "," + h3 / 2 + ")");
}
var labelHelper2, updateNodeBounds2;
var init_util4 = __esm({
"src/dagre-wrapper/shapes/util.js"() {
"use strict";
init_createLabel2();
init_createText();
init_diagramAPI();
init_config();
init_src32();
init_common();
init_utils2();
init_labelImageUtils();
labelHelper2 = /* @__PURE__ */ __name(async (parent4, node2, _classes, isNode2) => {
const config5 = getConfig2();
let classes3;
const useHtmlLabels = node2.useHtmlLabels || getEffectiveHtmlLabels(config5);
if (!_classes) {
classes3 = "node default";
} else {
classes3 = _classes;
}
const shapeSvg = parent4.insert("g").attr("class", classes3).attr("id", node2.domId || node2.id);
const label = shapeSvg.insert("g").attr("class", "label").attr("style", node2.labelStyle);
let labelText;
if (node2.labelText === void 0) {
labelText = "";
} else {
labelText = typeof node2.labelText === "string" ? node2.labelText : node2.labelText[0];
}
let text4;
if (node2.labelType === "markdown") {
text4 = createText(
label,
sanitizeText(decodeEntities(labelText), config5),
{
useHtmlLabels,
width: node2.width || config5.flowchart.wrappingWidth,
classes: "markdown-node-label"
},
config5
);
} else {
text4 = await createLabel_default2(
label,
sanitizeText(decodeEntities(labelText), config5),
node2.labelStyle,
false,
isNode2
);
}
let bbox = text4.getBBox();
const halfPadding = node2.padding / 2;
if (getEffectiveHtmlLabels(config5)) {
const div = text4.children[0];
const dv = select_default2(text4);
await configureLabelImages(div, labelText);
bbox = div.getBoundingClientRect();
dv.attr("width", bbox.width);
dv.attr("height", bbox.height);
}
if (useHtmlLabels) {
label.attr("transform", "translate(" + -bbox.width / 2 + ", " + -bbox.height / 2 + ")");
} else {
label.attr("transform", "translate(0, " + -bbox.height / 2 + ")");
}
if (node2.centerLabel) {
label.attr("transform", "translate(" + -bbox.width / 2 + ", " + -bbox.height / 2 + ")");
}
label.insert("rect", ":first-child");
return { shapeSvg, bbox, halfPadding, label };
}, "labelHelper");
updateNodeBounds2 = /* @__PURE__ */ __name((node2, element3) => {
const bbox = element3.node().getBBox();
node2.width = bbox.width;
node2.height = bbox.height;
}, "updateNodeBounds");
__name(insertPolygonShape2, "insertPolygonShape");
}
});
// src/dagre-wrapper/shapes/note.js
var note2, note_default;
var init_note2 = __esm({
"src/dagre-wrapper/shapes/note.js"() {
"use strict";
init_util4();
init_logger();
init_diagramAPI();
init_config();
init_intersect2();
note2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const useHtmlLabels = node2.useHtmlLabels || getEffectiveHtmlLabels(getConfig2());
if (!useHtmlLabels) {
node2.centerLabel = true;
}
const { shapeSvg, bbox, halfPadding } = await labelHelper2(
parent4,
node2,
"node " + node2.classes,
true
);
log.info("Classes = ", node2.classes);
const rect3 = shapeSvg.insert("rect", ":first-child");
rect3.attr("rx", node2.rx).attr("ry", node2.ry).attr("x", -bbox.width / 2 - halfPadding).attr("y", -bbox.height / 2 - halfPadding).attr("width", bbox.width + node2.padding).attr("height", bbox.height + node2.padding);
updateNodeBounds2(node2, rect3);
node2.intersect = function(point8) {
return intersect_default2.rect(node2, point8);
};
return shapeSvg;
}, "note");
note_default = note2;
}
});
// src/dagre-wrapper/nodes.js
function applyNodePropertyBorders(rect3, borders, totalWidth, totalHeight) {
const strokeDashArray = [];
const addBorder = /* @__PURE__ */ __name((length2) => {
strokeDashArray.push(length2, 0);
}, "addBorder");
const skipBorder = /* @__PURE__ */ __name((length2) => {
strokeDashArray.push(0, length2);
}, "skipBorder");
if (borders.includes("t")) {
log.debug("add top border");
addBorder(totalWidth);
} else {
skipBorder(totalWidth);
}
if (borders.includes("r")) {
log.debug("add right border");
addBorder(totalHeight);
} else {
skipBorder(totalHeight);
}
if (borders.includes("b")) {
log.debug("add bottom border");
addBorder(totalWidth);
} else {
skipBorder(totalWidth);
}
if (borders.includes("l")) {
log.debug("add left border");
addBorder(totalHeight);
} else {
skipBorder(totalHeight);
}
rect3.attr("stroke-dasharray", strokeDashArray.join(" "));
}
var formatClass, getClassesFromNode, question2, choice2, hexagon2, block_arrow, rect_left_inv_arrow2, lean_right2, lean_left2, trapezoid2, inv_trapezoid2, rect_right_inv_arrow, cylinder2, rect2, composite, labelRect2, rectWithTitle2, stadium2, circle5, doublecircle2, subroutine2, start2, forkJoin2, end, class_box, shapes3, nodeElems2, insertNode2, positionNode2;
var init_nodes3 = __esm({
"src/dagre-wrapper/nodes.js"() {
"use strict";
init_src32();
init_diagramAPI();
init_config();
init_logger();
init_blockArrowHelper();
init_createLabel2();
init_intersect2();
init_note2();
init_util4();
formatClass = /* @__PURE__ */ __name((str2) => {
if (str2) {
return " " + str2;
}
return "";
}, "formatClass");
getClassesFromNode = /* @__PURE__ */ __name((node2, otherClasses) => {
return `${otherClasses ? otherClasses : "node default"}${formatClass(node2.classes)} ${formatClass(
node2.class
)}`;
}, "getClassesFromNode");
question2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const w4 = bbox.width + node2.padding;
const h3 = bbox.height + node2.padding;
const s2 = w4 + h3;
const points = [
{ x: s2 / 2, y: 0 },
{ x: s2, y: -s2 / 2 },
{ x: s2 / 2, y: -s2 },
{ x: 0, y: -s2 / 2 }
];
log.info("Question main (Circle)");
const questionElem = insertPolygonShape2(shapeSvg, s2, s2, points);
questionElem.attr("style", node2.style);
updateNodeBounds2(node2, questionElem);
node2.intersect = function(point8) {
log.warn("Intersect called");
return intersect_default2.polygon(node2, points, point8);
};
return shapeSvg;
}, "question");
choice2 = /* @__PURE__ */ __name((parent4, node2) => {
const shapeSvg = parent4.insert("g").attr("class", "node default").attr("id", node2.domId || node2.id);
const s2 = 28;
const points = [
{ x: 0, y: s2 / 2 },
{ x: s2 / 2, y: 0 },
{ x: 0, y: -s2 / 2 },
{ x: -s2 / 2, y: 0 }
];
const choice3 = shapeSvg.insert("polygon", ":first-child").attr(
"points",
points.map(function(d3) {
return d3.x + "," + d3.y;
}).join(" ")
);
choice3.attr("class", "state-start").attr("r", 7).attr("width", 28).attr("height", 28);
node2.width = 28;
node2.height = 28;
node2.intersect = function(point8) {
return intersect_default2.circle(node2, 14, point8);
};
return shapeSvg;
}, "choice");
hexagon2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const f2 = 4;
const h3 = bbox.height + node2.padding;
const m3 = h3 / f2;
const w4 = bbox.width + 2 * m3 + node2.padding;
const points = [
{ x: m3, y: 0 },
{ x: w4 - m3, y: 0 },
{ x: w4, y: -h3 / 2 },
{ x: w4 - m3, y: -h3 },
{ x: m3, y: -h3 },
{ x: 0, y: -h3 / 2 }
];
const hex2 = insertPolygonShape2(shapeSvg, w4, h3, points);
hex2.attr("style", node2.style);
updateNodeBounds2(node2, hex2);
node2.intersect = function(point8) {
return intersect_default2.polygon(node2, points, point8);
};
return shapeSvg;
}, "hexagon");
block_arrow = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(parent4, node2, void 0, true);
const f2 = 2;
const h3 = bbox.height + 2 * node2.padding;
const m3 = h3 / f2;
const w4 = bbox.width + 2 * m3 + node2.padding;
const points = getArrowPoints(node2.directions, bbox, node2);
const blockArrow = insertPolygonShape2(shapeSvg, w4, h3, points);
blockArrow.attr("style", node2.style);
updateNodeBounds2(node2, blockArrow);
node2.intersect = function(point8) {
return intersect_default2.polygon(node2, points, point8);
};
return shapeSvg;
}, "block_arrow");
rect_left_inv_arrow2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const w4 = bbox.width + node2.padding;
const h3 = bbox.height + node2.padding;
const points = [
{ x: -h3 / 2, y: 0 },
{ x: w4, y: 0 },
{ x: w4, y: -h3 },
{ x: -h3 / 2, y: -h3 },
{ x: 0, y: -h3 / 2 }
];
const el = insertPolygonShape2(shapeSvg, w4, h3, points);
el.attr("style", node2.style);
node2.width = w4 + h3;
node2.height = h3;
node2.intersect = function(point8) {
return intersect_default2.polygon(node2, points, point8);
};
return shapeSvg;
}, "rect_left_inv_arrow");
lean_right2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(parent4, node2, getClassesFromNode(node2), true);
const w4 = bbox.width + node2.padding;
const h3 = bbox.height + node2.padding;
const points = [
{ x: -2 * h3 / 6, y: 0 },
{ x: w4 - h3 / 6, y: 0 },
{ x: w4 + 2 * h3 / 6, y: -h3 },
{ x: h3 / 6, y: -h3 }
];
const el = insertPolygonShape2(shapeSvg, w4, h3, points);
el.attr("style", node2.style);
updateNodeBounds2(node2, el);
node2.intersect = function(point8) {
return intersect_default2.polygon(node2, points, point8);
};
return shapeSvg;
}, "lean_right");
lean_left2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const w4 = bbox.width + node2.padding;
const h3 = bbox.height + node2.padding;
const points = [
{ x: 2 * h3 / 6, y: 0 },
{ x: w4 + h3 / 6, y: 0 },
{ x: w4 - 2 * h3 / 6, y: -h3 },
{ x: -h3 / 6, y: -h3 }
];
const el = insertPolygonShape2(shapeSvg, w4, h3, points);
el.attr("style", node2.style);
updateNodeBounds2(node2, el);
node2.intersect = function(point8) {
return intersect_default2.polygon(node2, points, point8);
};
return shapeSvg;
}, "lean_left");
trapezoid2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const w4 = bbox.width + node2.padding;
const h3 = bbox.height + node2.padding;
const points = [
{ x: -2 * h3 / 6, y: 0 },
{ x: w4 + 2 * h3 / 6, y: 0 },
{ x: w4 - h3 / 6, y: -h3 },
{ x: h3 / 6, y: -h3 }
];
const el = insertPolygonShape2(shapeSvg, w4, h3, points);
el.attr("style", node2.style);
updateNodeBounds2(node2, el);
node2.intersect = function(point8) {
return intersect_default2.polygon(node2, points, point8);
};
return shapeSvg;
}, "trapezoid");
inv_trapezoid2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const w4 = bbox.width + node2.padding;
const h3 = bbox.height + node2.padding;
const points = [
{ x: h3 / 6, y: 0 },
{ x: w4 - h3 / 6, y: 0 },
{ x: w4 + 2 * h3 / 6, y: -h3 },
{ x: -2 * h3 / 6, y: -h3 }
];
const el = insertPolygonShape2(shapeSvg, w4, h3, points);
el.attr("style", node2.style);
updateNodeBounds2(node2, el);
node2.intersect = function(point8) {
return intersect_default2.polygon(node2, points, point8);
};
return shapeSvg;
}, "inv_trapezoid");
rect_right_inv_arrow = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const w4 = bbox.width + node2.padding;
const h3 = bbox.height + node2.padding;
const points = [
{ x: 0, y: 0 },
{ x: w4 + h3 / 2, y: 0 },
{ x: w4, y: -h3 / 2 },
{ x: w4 + h3 / 2, y: -h3 },
{ x: 0, y: -h3 }
];
const el = insertPolygonShape2(shapeSvg, w4, h3, points);
el.attr("style", node2.style);
updateNodeBounds2(node2, el);
node2.intersect = function(point8) {
return intersect_default2.polygon(node2, points, point8);
};
return shapeSvg;
}, "rect_right_inv_arrow");
cylinder2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const w4 = bbox.width + node2.padding;
const rx = w4 / 2;
const ry = rx / (2.5 + w4 / 50);
const h3 = bbox.height + ry + node2.padding;
const shape = "M 0," + ry + " a " + rx + "," + ry + " 0,0,0 " + w4 + " 0 a " + rx + "," + ry + " 0,0,0 " + -w4 + " 0 l 0," + h3 + " a " + rx + "," + ry + " 0,0,0 " + w4 + " 0 l 0," + -h3;
const el = shapeSvg.attr("label-offset-y", ry).insert("path", ":first-child").attr("style", node2.style).attr("d", shape).attr("transform", "translate(" + -w4 / 2 + "," + -(h3 / 2 + ry) + ")");
updateNodeBounds2(node2, el);
node2.intersect = function(point8) {
const pos = intersect_default2.rect(node2, point8);
const x5 = pos.x - node2.x;
if (rx != 0 && (Math.abs(x5) < node2.width / 2 || Math.abs(x5) == node2.width / 2 && Math.abs(pos.y - node2.y) > node2.height / 2 - ry)) {
let y6 = ry * ry * (1 - x5 * x5 / (rx * rx));
if (y6 != 0) {
y6 = Math.sqrt(y6);
}
y6 = ry - y6;
if (point8.y - node2.y > 0) {
y6 = -y6;
}
pos.y += y6;
}
return pos;
};
return shapeSvg;
}, "cylinder");
rect2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox, halfPadding } = await labelHelper2(
parent4,
node2,
"node " + node2.classes + " " + node2.class,
true
);
const rect3 = shapeSvg.insert("rect", ":first-child");
const totalWidth = node2.positioned ? node2.width : bbox.width + node2.padding;
const totalHeight = node2.positioned ? node2.height : bbox.height + node2.padding;
const x5 = node2.positioned ? -totalWidth / 2 : -bbox.width / 2 - halfPadding;
const y6 = node2.positioned ? -totalHeight / 2 : -bbox.height / 2 - halfPadding;
rect3.attr("class", "basic label-container").attr("style", node2.style).attr("rx", node2.rx).attr("ry", node2.ry).attr("x", x5).attr("y", y6).attr("width", totalWidth).attr("height", totalHeight);
if (node2.props) {
const propKeys = new Set(Object.keys(node2.props));
if (node2.props.borders) {
applyNodePropertyBorders(rect3, node2.props.borders, totalWidth, totalHeight);
propKeys.delete("borders");
}
propKeys.forEach((propKey) => {
log.warn(`Unknown node property ${propKey}`);
});
}
updateNodeBounds2(node2, rect3);
node2.intersect = function(point8) {
return intersect_default2.rect(node2, point8);
};
return shapeSvg;
}, "rect");
composite = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox, halfPadding } = await labelHelper2(
parent4,
node2,
"node " + node2.classes,
true
);
const rect3 = shapeSvg.insert("rect", ":first-child");
const totalWidth = node2.positioned ? node2.width : bbox.width + node2.padding;
const totalHeight = node2.positioned ? node2.height : bbox.height + node2.padding;
const x5 = node2.positioned ? -totalWidth / 2 : -bbox.width / 2 - halfPadding;
const y6 = node2.positioned ? -totalHeight / 2 : -bbox.height / 2 - halfPadding;
rect3.attr("class", "basic cluster composite label-container").attr("style", node2.style).attr("rx", node2.rx).attr("ry", node2.ry).attr("x", x5).attr("y", y6).attr("width", totalWidth).attr("height", totalHeight);
if (node2.props) {
const propKeys = new Set(Object.keys(node2.props));
if (node2.props.borders) {
applyNodePropertyBorders(rect3, node2.props.borders, totalWidth, totalHeight);
propKeys.delete("borders");
}
propKeys.forEach((propKey) => {
log.warn(`Unknown node property ${propKey}`);
});
}
updateNodeBounds2(node2, rect3);
node2.intersect = function(point8) {
return intersect_default2.rect(node2, point8);
};
return shapeSvg;
}, "composite");
labelRect2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg } = await labelHelper2(parent4, node2, "label", true);
log.trace("Classes = ", node2.class);
const rect3 = shapeSvg.insert("rect", ":first-child");
const totalWidth = 0;
const totalHeight = 0;
rect3.attr("width", totalWidth).attr("height", totalHeight);
shapeSvg.attr("class", "label edgeLabel");
if (node2.props) {
const propKeys = new Set(Object.keys(node2.props));
if (node2.props.borders) {
applyNodePropertyBorders(rect3, node2.props.borders, totalWidth, totalHeight);
propKeys.delete("borders");
}
propKeys.forEach((propKey) => {
log.warn(`Unknown node property ${propKey}`);
});
}
updateNodeBounds2(node2, rect3);
node2.intersect = function(point8) {
return intersect_default2.rect(node2, point8);
};
return shapeSvg;
}, "labelRect");
__name(applyNodePropertyBorders, "applyNodePropertyBorders");
rectWithTitle2 = /* @__PURE__ */ __name(async (parent4, node2) => {
let classes3;
if (!node2.classes) {
classes3 = "node default";
} else {
classes3 = "node " + node2.classes;
}
const shapeSvg = parent4.insert("g").attr("class", classes3).attr("id", node2.domId || node2.id);
const rect3 = shapeSvg.insert("rect", ":first-child");
const innerLine = shapeSvg.insert("line");
const label = shapeSvg.insert("g").attr("class", "label");
const text22 = node2.labelText.flat ? node2.labelText.flat() : node2.labelText;
let title2 = "";
if (typeof text22 === "object") {
title2 = text22[0];
} else {
title2 = text22;
}
log.info("Label text abc79", title2, text22, typeof text22 === "object");
const text4 = await createLabel_default2(label, title2, node2.labelStyle, true, true);
let bbox = { width: 0, height: 0 };
if (getEffectiveHtmlLabels(getConfig2())) {
const div = text4.children[0];
const dv = select_default2(text4);
bbox = div.getBoundingClientRect();
dv.attr("width", bbox.width);
dv.attr("height", bbox.height);
}
log.info("Text 2", text22);
const textRows = text22.slice(1, text22.length);
let titleBox = text4.getBBox();
const descr = await createLabel_default2(
label,
textRows.join ? textRows.join("
") : textRows,
node2.labelStyle,
true,
true
);
if (getEffectiveHtmlLabels(getConfig2())) {
const div = descr.children[0];
const dv = select_default2(descr);
bbox = div.getBoundingClientRect();
dv.attr("width", bbox.width);
dv.attr("height", bbox.height);
}
const halfPadding = node2.padding / 2;
select_default2(descr).attr(
"transform",
"translate( " + // (titleBox.width - bbox.width) / 2 +
(bbox.width > titleBox.width ? 0 : (titleBox.width - bbox.width) / 2) + ", " + (titleBox.height + halfPadding + 5) + ")"
);
select_default2(text4).attr(
"transform",
"translate( " + // (titleBox.width - bbox.width) / 2 +
(bbox.width < titleBox.width ? 0 : -(titleBox.width - bbox.width) / 2) + ", 0)"
);
bbox = label.node().getBBox();
label.attr(
"transform",
"translate(" + -bbox.width / 2 + ", " + (-bbox.height / 2 - halfPadding + 3) + ")"
);
rect3.attr("class", "outer title-state").attr("x", -bbox.width / 2 - halfPadding).attr("y", -bbox.height / 2 - halfPadding).attr("width", bbox.width + node2.padding).attr("height", bbox.height + node2.padding);
innerLine.attr("class", "divider").attr("x1", -bbox.width / 2 - halfPadding).attr("x2", bbox.width / 2 + halfPadding).attr("y1", -bbox.height / 2 - halfPadding + titleBox.height + halfPadding).attr("y2", -bbox.height / 2 - halfPadding + titleBox.height + halfPadding);
updateNodeBounds2(node2, rect3);
node2.intersect = function(point8) {
return intersect_default2.rect(node2, point8);
};
return shapeSvg;
}, "rectWithTitle");
stadium2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const h3 = bbox.height + node2.padding;
const w4 = bbox.width + h3 / 4 + node2.padding;
const rect3 = shapeSvg.insert("rect", ":first-child").attr("style", node2.style).attr("rx", h3 / 2).attr("ry", h3 / 2).attr("x", -w4 / 2).attr("y", -h3 / 2).attr("width", w4).attr("height", h3);
updateNodeBounds2(node2, rect3);
node2.intersect = function(point8) {
return intersect_default2.rect(node2, point8);
};
return shapeSvg;
}, "stadium");
circle5 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox, halfPadding } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const circle6 = shapeSvg.insert("circle", ":first-child");
circle6.attr("style", node2.style).attr("rx", node2.rx).attr("ry", node2.ry).attr("r", bbox.width / 2 + halfPadding).attr("width", bbox.width + node2.padding).attr("height", bbox.height + node2.padding);
log.info("Circle main");
updateNodeBounds2(node2, circle6);
node2.intersect = function(point8) {
log.info("Circle intersect", node2, bbox.width / 2 + halfPadding, point8);
return intersect_default2.circle(node2, bbox.width / 2 + halfPadding, point8);
};
return shapeSvg;
}, "circle");
doublecircle2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox, halfPadding } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const gap = 5;
const circleGroup = shapeSvg.insert("g", ":first-child");
const outerCircle = circleGroup.insert("circle");
const innerCircle = circleGroup.insert("circle");
circleGroup.attr("class", node2.class);
outerCircle.attr("style", node2.style).attr("rx", node2.rx).attr("ry", node2.ry).attr("r", bbox.width / 2 + halfPadding + gap).attr("width", bbox.width + node2.padding + gap * 2).attr("height", bbox.height + node2.padding + gap * 2);
innerCircle.attr("style", node2.style).attr("rx", node2.rx).attr("ry", node2.ry).attr("r", bbox.width / 2 + halfPadding).attr("width", bbox.width + node2.padding).attr("height", bbox.height + node2.padding);
log.info("DoubleCircle main");
updateNodeBounds2(node2, outerCircle);
node2.intersect = function(point8) {
log.info("DoubleCircle intersect", node2, bbox.width / 2 + halfPadding + gap, point8);
return intersect_default2.circle(node2, bbox.width / 2 + halfPadding + gap, point8);
};
return shapeSvg;
}, "doublecircle");
subroutine2 = /* @__PURE__ */ __name(async (parent4, node2) => {
const { shapeSvg, bbox } = await labelHelper2(
parent4,
node2,
getClassesFromNode(node2, void 0),
true
);
const w4 = bbox.width + node2.padding;
const h3 = bbox.height + node2.padding;
const points = [
{ x: 0, y: 0 },
{ x: w4, y: 0 },
{ x: w4, y: -h3 },
{ x: 0, y: -h3 },
{ x: 0, y: 0 },
{ x: -8, y: 0 },
{ x: w4 + 8, y: 0 },
{ x: w4 + 8, y: -h3 },
{ x: -8, y: -h3 },
{ x: -8, y: 0 }
];
const el = insertPolygonShape2(shapeSvg, w4, h3, points);
el.attr("style", node2.style);
updateNodeBounds2(node2, el);
node2.intersect = function(point8) {
return intersect_default2.polygon(node2, points, point8);
};
return shapeSvg;
}, "subroutine");
start2 = /* @__PURE__ */ __name((parent4, node2) => {
const shapeSvg = parent4.insert("g").attr("class", "node default").attr("id", node2.domId || node2.id);
const circle6 = shapeSvg.insert("circle", ":first-child");
circle6.attr("class", "state-start").attr("r", 7).attr("width", 14).attr("height", 14);
updateNodeBounds2(node2, circle6);
node2.intersect = function(point8) {
return intersect_default2.circle(node2, 7, point8);
};
return shapeSvg;
}, "start");
forkJoin2 = /* @__PURE__ */ __name((parent4, node2, dir2) => {
const shapeSvg = parent4.insert("g").attr("class", "node default").attr("id", node2.domId || node2.id);
let width3 = 70;
let height2 = 10;
if (dir2 === "LR") {
width3 = 10;
height2 = 70;
}
const shape = shapeSvg.append("rect").attr("x", -1 * width3 / 2).attr("y", -1 * height2 / 2).attr("width", width3).attr("height", height2).attr("class", "fork-join");
updateNodeBounds2(node2, shape);
node2.height = node2.height + node2.padding / 2;
node2.width = node2.width + node2.padding / 2;
node2.intersect = function(point8) {
return intersect_default2.rect(node2, point8);
};
return shapeSvg;
}, "forkJoin");
end = /* @__PURE__ */ __name((parent4, node2) => {
const shapeSvg = parent4.insert("g").attr("class", "node default").attr("id", node2.domId || node2.id);
const innerCircle = shapeSvg.insert("circle", ":first-child");
const circle6 = shapeSvg.insert("circle", ":first-child");
circle6.attr("class", "state-start").attr("r", 7).attr("width", 14).attr("height", 14);
innerCircle.attr("class", "state-end").attr("r", 5).attr("width", 10).attr("height", 10);
updateNodeBounds2(node2, circle6);
node2.intersect = function(point8) {
return intersect_default2.circle(node2, 7, point8);
};
return shapeSvg;
}, "end");
class_box = /* @__PURE__ */ __name(async (parent4, node2) => {
const halfPadding = node2.padding / 2;
const rowPadding = 4;
const lineHeight = 8;
let classes3;
if (!node2.classes) {
classes3 = "node default";
} else {
classes3 = "node " + node2.classes;
}
const shapeSvg = parent4.insert("g").attr("class", classes3).attr("id", node2.domId || node2.id);
const rect3 = shapeSvg.insert("rect", ":first-child");
const topLine = shapeSvg.insert("line");
const bottomLine = shapeSvg.insert("line");
let maxWidth2 = 0;
let maxHeight = rowPadding;
const labelContainer = shapeSvg.insert("g").attr("class", "label");
let verticalPos = 0;
const hasInterface = node2.classData.annotations?.[0];
const interfaceLabelText = node2.classData.annotations[0] ? "\xAB" + node2.classData.annotations[0] + "\xBB" : "";
const interfaceLabel = await createLabel_default2(
labelContainer,
interfaceLabelText,
node2.labelStyle,
true,
true
);
let interfaceBBox = interfaceLabel.getBBox();
if (getEffectiveHtmlLabels(getConfig2())) {
const div = interfaceLabel.children[0];
const dv = select_default2(interfaceLabel);
interfaceBBox = div.getBoundingClientRect();
dv.attr("width", interfaceBBox.width);
dv.attr("height", interfaceBBox.height);
}
if (node2.classData.annotations[0]) {
maxHeight += interfaceBBox.height + rowPadding;
maxWidth2 += interfaceBBox.width;
}
let classTitleString = node2.classData.label;
if (node2.classData.type !== void 0 && node2.classData.type !== "") {
if (getEffectiveHtmlLabels(getConfig2())) {
classTitleString += "<" + node2.classData.type + ">";
} else {
classTitleString += "<" + node2.classData.type + ">";
}
}
const classTitleLabel = await createLabel_default2(
labelContainer,
classTitleString,
node2.labelStyle,
true,
true
);
select_default2(classTitleLabel).attr("class", "classTitle");
let classTitleBBox = classTitleLabel.getBBox();
if (getEffectiveHtmlLabels(getConfig2())) {
const div = classTitleLabel.children[0];
const dv = select_default2(classTitleLabel);
classTitleBBox = div.getBoundingClientRect();
dv.attr("width", classTitleBBox.width);
dv.attr("height", classTitleBBox.height);
}
maxHeight += classTitleBBox.height + rowPadding;
if (classTitleBBox.width > maxWidth2) {
maxWidth2 = classTitleBBox.width;
}
const classAttributes = [];
node2.classData.members.forEach(async (member) => {
const parsedInfo = member.getDisplayDetails();
let parsedText = parsedInfo.displayText;
if (getEffectiveHtmlLabels(getConfig2())) {
parsedText = parsedText.replace(//g, ">");
}
const lbl = await createLabel_default2(
labelContainer,
parsedText,
parsedInfo.cssStyle ? parsedInfo.cssStyle : node2.labelStyle,
true,
true
);
let bbox = lbl.getBBox();
if (getEffectiveHtmlLabels(getConfig2())) {
const div = lbl.children[0];
const dv = select_default2(lbl);
bbox = div.getBoundingClientRect();
dv.attr("width", bbox.width);
dv.attr("height", bbox.height);
}
if (bbox.width > maxWidth2) {
maxWidth2 = bbox.width;
}
maxHeight += bbox.height + rowPadding;
classAttributes.push(lbl);
});
maxHeight += lineHeight;
const classMethods = [];
node2.classData.methods.forEach(async (member) => {
const parsedInfo = member.getDisplayDetails();
let displayText = parsedInfo.displayText;
if (getEffectiveHtmlLabels(getConfig2())) {
displayText = displayText.replace(//g, ">");
}
const lbl = await createLabel_default2(
labelContainer,
displayText,
parsedInfo.cssStyle ? parsedInfo.cssStyle : node2.labelStyle,
true,
true
);
let bbox = lbl.getBBox();
if (getEffectiveHtmlLabels(getConfig2())) {
const div = lbl.children[0];
const dv = select_default2(lbl);
bbox = div.getBoundingClientRect();
dv.attr("width", bbox.width);
dv.attr("height", bbox.height);
}
if (bbox.width > maxWidth2) {
maxWidth2 = bbox.width;
}
maxHeight += bbox.height + rowPadding;
classMethods.push(lbl);
});
maxHeight += lineHeight;
if (hasInterface) {
let diffX2 = (maxWidth2 - interfaceBBox.width) / 2;
select_default2(interfaceLabel).attr(
"transform",
"translate( " + (-1 * maxWidth2 / 2 + diffX2) + ", " + -1 * maxHeight / 2 + ")"
);
verticalPos = interfaceBBox.height + rowPadding;
}
let diffX = (maxWidth2 - classTitleBBox.width) / 2;
select_default2(classTitleLabel).attr(
"transform",
"translate( " + (-1 * maxWidth2 / 2 + diffX) + ", " + (-1 * maxHeight / 2 + verticalPos) + ")"
);
verticalPos += classTitleBBox.height + rowPadding;
topLine.attr("class", "divider").attr("x1", -maxWidth2 / 2 - halfPadding).attr("x2", maxWidth2 / 2 + halfPadding).attr("y1", -maxHeight / 2 - halfPadding + lineHeight + verticalPos).attr("y2", -maxHeight / 2 - halfPadding + lineHeight + verticalPos);
verticalPos += lineHeight;
classAttributes.forEach((lbl) => {
select_default2(lbl).attr(
"transform",
"translate( " + -maxWidth2 / 2 + ", " + (-1 * maxHeight / 2 + verticalPos + lineHeight / 2) + ")"
);
const memberBBox = lbl?.getBBox();
verticalPos += (memberBBox?.height ?? 0) + rowPadding;
});
verticalPos += lineHeight;
bottomLine.attr("class", "divider").attr("x1", -maxWidth2 / 2 - halfPadding).attr("x2", maxWidth2 / 2 + halfPadding).attr("y1", -maxHeight / 2 - halfPadding + lineHeight + verticalPos).attr("y2", -maxHeight / 2 - halfPadding + lineHeight + verticalPos);
verticalPos += lineHeight;
classMethods.forEach((lbl) => {
select_default2(lbl).attr(
"transform",
"translate( " + -maxWidth2 / 2 + ", " + (-1 * maxHeight / 2 + verticalPos) + ")"
);
const memberBBox = lbl?.getBBox();
verticalPos += (memberBBox?.height ?? 0) + rowPadding;
});
rect3.attr("style", node2.style).attr("class", "outer title-state").attr("x", -maxWidth2 / 2 - halfPadding).attr("y", -(maxHeight / 2) - halfPadding).attr("width", maxWidth2 + node2.padding).attr("height", maxHeight + node2.padding);
updateNodeBounds2(node2, rect3);
node2.intersect = function(point8) {
return intersect_default2.rect(node2, point8);
};
return shapeSvg;
}, "class_box");
shapes3 = {
rhombus: question2,
composite,
question: question2,
rect: rect2,
labelRect: labelRect2,
rectWithTitle: rectWithTitle2,
choice: choice2,
circle: circle5,
doublecircle: doublecircle2,
stadium: stadium2,
hexagon: hexagon2,
block_arrow,
rect_left_inv_arrow: rect_left_inv_arrow2,
lean_right: lean_right2,
lean_left: lean_left2,
trapezoid: trapezoid2,
inv_trapezoid: inv_trapezoid2,
rect_right_inv_arrow,
cylinder: cylinder2,
start: start2,
end,
note: note_default,
subroutine: subroutine2,
fork: forkJoin2,
join: forkJoin2,
class_box
};
nodeElems2 = {};
insertNode2 = /* @__PURE__ */ __name(async (elem, node2, renderOptions) => {
let newEl;
let el;
if (node2.link) {
let target;
if (getConfig2().securityLevel === "sandbox") {
target = "_top";
} else if (node2.linkTarget) {
target = node2.linkTarget || "_blank";
}
newEl = elem.insert("svg:a").attr("xlink:href", node2.link).attr("target", target);
el = await shapes3[node2.shape](newEl, node2, renderOptions);
} else {
el = await shapes3[node2.shape](elem, node2, renderOptions);
newEl = el;
}
if (node2.tooltip) {
el.attr("title", node2.tooltip);
}
if (node2.class) {
el.attr("class", "node default " + node2.class);
}
nodeElems2[node2.id] = newEl;
if (node2.haveCallback) {
nodeElems2[node2.id].attr("class", nodeElems2[node2.id].attr("class") + " clickable");
}
return newEl;
}, "insertNode");
positionNode2 = /* @__PURE__ */ __name((node2) => {
const el = nodeElems2[node2.id];
log.trace(
"Transforming node",
node2.diff,
node2,
"translate(" + (node2.x - node2.width / 2 - 5) + ", " + node2.width / 2 + ")"
);
const padding2 = 8;
const diff2 = node2.diff || 0;
if (node2.clusterNode) {
el.attr(
"transform",
"translate(" + (node2.x + diff2 - node2.width / 2) + ", " + (node2.y - node2.height / 2 - padding2) + ")"
);
} else {
el.attr("transform", "translate(" + node2.x + ", " + node2.y + ")");
}
return diff2;
}, "positionNode");
}
});
// src/diagrams/block/renderHelpers.ts
function getNodeFromBlock(block2, db8, positioned = false) {
const vertex = block2;
let classStr = "default";
if ((vertex?.classes?.length || 0) > 0) {
classStr = (vertex?.classes ?? []).join(" ");
}
classStr = classStr + " flowchart-label";
let radius2 = 0;
let shape = "";
let padding2;
switch (vertex.type) {
case "round":
radius2 = 5;
shape = "rect";
break;
case "composite":
radius2 = 0;
shape = "composite";
padding2 = 0;
break;
case "square":
shape = "rect";
break;
case "diamond":
shape = "question";
break;
case "hexagon":
shape = "hexagon";
break;
case "block_arrow":
shape = "block_arrow";
break;
case "odd":
shape = "rect_left_inv_arrow";
break;
case "lean_right":
shape = "lean_right";
break;
case "lean_left":
shape = "lean_left";
break;
case "trapezoid":
shape = "trapezoid";
break;
case "inv_trapezoid":
shape = "inv_trapezoid";
break;
case "rect_left_inv_arrow":
shape = "rect_left_inv_arrow";
break;
case "circle":
shape = "circle";
break;
case "ellipse":
shape = "ellipse";
break;
case "stadium":
shape = "stadium";
break;
case "subroutine":
shape = "subroutine";
break;
case "cylinder":
shape = "cylinder";
break;
case "group":
shape = "rect";
break;
case "doublecircle":
shape = "doublecircle";
break;
default:
shape = "rect";
}
const styles4 = getStylesFromArray(vertex?.styles ?? []);
const vertexText = vertex.label;
const bounds4 = vertex.size ?? { width: 0, height: 0, x: 0, y: 0 };
const node2 = {
labelStyle: styles4.labelStyle,
shape,
labelText: vertexText,
rx: radius2,
ry: radius2,
class: classStr,
style: styles4.style,
id: vertex.id,
directions: vertex.directions,
width: bounds4.width,
height: bounds4.height,
x: bounds4.x,
y: bounds4.y,
positioned,
intersect: void 0,
type: vertex.type,
padding: padding2 ?? getConfig()?.block?.padding ?? 0
};
return node2;
}
async function calculateBlockSize(elem, block2, db8) {
const node2 = getNodeFromBlock(block2, db8, false);
if (node2.type === "group") {
return;
}
const config5 = getConfig();
const nodeEl = await insertNode2(elem, node2, { config: config5 });
const boundingBox3 = nodeEl.node().getBBox();
const obj = db8.getBlock(node2.id);
obj.size = { width: boundingBox3.width, height: boundingBox3.height, x: 0, y: 0, node: nodeEl };
db8.setBlock(obj);
nodeEl.remove();
}
async function insertBlockPositioned(elem, block2, db8) {
const node2 = getNodeFromBlock(block2, db8, true);
const obj = db8.getBlock(node2.id);
if (obj.type !== "space") {
const config5 = getConfig();
await insertNode2(elem, node2, { config: config5 });
block2.intersect = node2?.intersect;
positionNode2(node2);
}
}
async function performOperations(elem, blocks2, db8, operation) {
for (const block2 of blocks2) {
await operation(elem, block2, db8);
if (block2.children) {
await performOperations(elem, block2.children, db8, operation);
}
}
}
async function calculateBlockSizes(elem, blocks2, db8) {
await performOperations(elem, blocks2, db8, calculateBlockSize);
}
async function insertBlocks(elem, blocks2, db8) {
await performOperations(elem, blocks2, db8, insertBlockPositioned);
}
async function insertEdges(elem, edges3, blocks2, db8, id32) {
const g2 = new Graph({
multigraph: true,
compound: true
});
g2.setGraph({
rankdir: "TB",
nodesep: 10,
ranksep: 10,
marginx: 8,
marginy: 8
});
for (const block2 of blocks2) {
if (block2.size) {
g2.setNode(block2.id, {
width: block2.size.width,
height: block2.size.height,
intersect: block2.intersect
});
}
}
for (const edge of edges3) {
if (edge.start && edge.end) {
const startBlock = db8.getBlock(edge.start);
const endBlock = db8.getBlock(edge.end);
if (startBlock?.size && endBlock?.size) {
const start3 = startBlock.size;
const end2 = endBlock.size;
const points = [
{ x: start3.x, y: start3.y },
{ x: start3.x + (end2.x - start3.x) / 2, y: start3.y + (end2.y - start3.y) / 2 },
{ x: end2.x, y: end2.y }
];
insertEdge2(
elem,
{ v: edge.start, w: edge.end, name: edge.id },
{
...edge,
arrowTypeEnd: edge.arrowTypeEnd,
arrowTypeStart: edge.arrowTypeStart,
points,
classes: "edge-thickness-normal edge-pattern-solid flowchart-link LS-a1 LE-b1"
},
void 0,
"block",
g2,
id32
);
if (edge.label) {
await insertEdgeLabel2(elem, {
...edge,
label: edge.label,
labelStyle: "stroke: #333; stroke-width: 1.5px;fill:none;",
arrowTypeEnd: edge.arrowTypeEnd,
arrowTypeStart: edge.arrowTypeStart,
points,
classes: "edge-thickness-normal edge-pattern-solid flowchart-link LS-a1 LE-b1"
});
positionEdgeLabel2(
{ ...edge, x: points[1].x, y: points[1].y },
{
originalPath: points
}
);
}
}
}
}
}
var init_renderHelpers = __esm({
"src/diagrams/block/renderHelpers.ts"() {
"use strict";
init_graphlib();
init_config();
init_edges2();
init_nodes3();
init_utils2();
__name(getNodeFromBlock, "getNodeFromBlock");
__name(calculateBlockSize, "calculateBlockSize");
__name(insertBlockPositioned, "insertBlockPositioned");
__name(performOperations, "performOperations");
__name(calculateBlockSizes, "calculateBlockSizes");
__name(insertBlocks, "insertBlocks");
__name(insertEdges, "insertEdges");
}
});
// src/diagrams/block/blockRenderer.ts
var getClasses5, draw23, blockRenderer_default;
var init_blockRenderer = __esm({
"src/diagrams/block/blockRenderer.ts"() {
"use strict";
init_src32();
init_config();
init_markers2();
init_logger();
init_setupGraphViewbox();
init_layout3();
init_renderHelpers();
getClasses5 = /* @__PURE__ */ __name(function(text4, diagObj) {
return diagObj.db.getClasses();
}, "getClasses");
draw23 = /* @__PURE__ */ __name(async function(text4, id32, _version, diagObj) {
const { securityLevel, block: conf5 } = getConfig();
const db8 = diagObj.db;
let sandboxElement;
if (securityLevel === "sandbox") {
sandboxElement = select_default2("#i" + id32);
}
const root3 = securityLevel === "sandbox" ? select_default2(sandboxElement.nodes()[0].contentDocument.body) : select_default2("body");
const svg2 = securityLevel === "sandbox" ? root3.select(`[id="${id32}"]`) : select_default2(`[id="${id32}"]`);
const markers3 = ["point", "circle", "cross"];
markers_default2(svg2, markers3, diagObj.type, id32);
const bl = db8.getBlocks();
const blArr = db8.getBlocksFlat();
const edges3 = db8.getEdges();
const nodes5 = svg2.insert("g").attr("class", "block");
await calculateBlockSizes(nodes5, bl, db8);
const bounds4 = layout5(db8);
await insertBlocks(nodes5, bl, db8);
await insertEdges(nodes5, edges3, blArr, db8, id32);
if (bounds4) {
const bounds22 = bounds4;
const magicFactor = Math.max(1, Math.round(0.125 * (bounds22.width / bounds22.height)));
const height2 = bounds22.height + magicFactor + 10;
const width3 = bounds22.width + 10;
const { useMaxWidth } = conf5;
configureSvgSize(svg2, height2, width3, !!useMaxWidth);
log.debug("Here Bounds", bounds4, bounds22);
svg2.attr(
"viewBox",
`${bounds22.x - 5} ${bounds22.y - 5} ${bounds22.width + 10} ${bounds22.height + 10}`
);
}
}, "draw");
blockRenderer_default = {
draw: draw23,
getClasses: getClasses5
};
}
});
// src/diagrams/block/blockDiagram.ts
var blockDiagram_exports = {};
__export(blockDiagram_exports, {
diagram: () => diagram24
});
var diagram24;
var init_blockDiagram = __esm({
"src/diagrams/block/blockDiagram.ts"() {
"use strict";
init_block();
init_blockDB();
init_styles18();
init_blockRenderer();
diagram24 = {
parser: block_default,
db: blockDB_default,
renderer: blockRenderer_default,
styles: styles_default16
};
}
});
// src/diagrams/architecture/architectureTypes.ts
var ArchitectureDirectionName, ArchitectureDirectionArrow, ArchitectureDirectionArrowShift, getOppositeArchitectureDirection, isArchitectureDirection, isArchitectureDirectionX, isArchitectureDirectionY, isArchitectureDirectionXY, isArchitecturePairXY, isValidArchitectureDirectionPair, getArchitectureDirectionPair, shiftPositionByArchitectureDirectionPair, getArchitectureDirectionXYFactors, getArchitectureDirectionAlignment, isArchitectureService, isArchitectureJunction, edgeData, nodeData;
var init_architectureTypes = __esm({
"src/diagrams/architecture/architectureTypes.ts"() {
"use strict";
ArchitectureDirectionName = {
L: "left",
R: "right",
T: "top",
B: "bottom"
};
ArchitectureDirectionArrow = {
L: /* @__PURE__ */ __name((scale3) => `${scale3},${scale3 / 2} 0,${scale3} 0,0`, "L"),
R: /* @__PURE__ */ __name((scale3) => `0,${scale3 / 2} ${scale3},0 ${scale3},${scale3}`, "R"),
T: /* @__PURE__ */ __name((scale3) => `0,0 ${scale3},0 ${scale3 / 2},${scale3}`, "T"),
B: /* @__PURE__ */ __name((scale3) => `${scale3 / 2},0 ${scale3},${scale3} 0,${scale3}`, "B")
};
ArchitectureDirectionArrowShift = {
L: /* @__PURE__ */ __name((orig, arrowSize) => orig - arrowSize + 2, "L"),
R: /* @__PURE__ */ __name((orig, _arrowSize) => orig - 2, "R"),
T: /* @__PURE__ */ __name((orig, arrowSize) => orig - arrowSize + 2, "T"),
B: /* @__PURE__ */ __name((orig, _arrowSize) => orig - 2, "B")
};
getOppositeArchitectureDirection = /* @__PURE__ */ __name(function(x5) {
if (isArchitectureDirectionX(x5)) {
return x5 === "L" ? "R" : "L";
} else {
return x5 === "T" ? "B" : "T";
}
}, "getOppositeArchitectureDirection");
isArchitectureDirection = /* @__PURE__ */ __name(function(x5) {
const temp = x5;
return temp === "L" || temp === "R" || temp === "T" || temp === "B";
}, "isArchitectureDirection");
isArchitectureDirectionX = /* @__PURE__ */ __name(function(x5) {
const temp = x5;
return temp === "L" || temp === "R";
}, "isArchitectureDirectionX");
isArchitectureDirectionY = /* @__PURE__ */ __name(function(x5) {
const temp = x5;
return temp === "T" || temp === "B";
}, "isArchitectureDirectionY");
isArchitectureDirectionXY = /* @__PURE__ */ __name(function(a2, b3) {
const aX_bY = isArchitectureDirectionX(a2) && isArchitectureDirectionY(b3);
const aY_bX = isArchitectureDirectionY(a2) && isArchitectureDirectionX(b3);
return aX_bY || aY_bX;
}, "isArchitectureDirectionXY");
isArchitecturePairXY = /* @__PURE__ */ __name(function(pair) {
const lhs = pair[0];
const rhs = pair[1];
const aX_bY = isArchitectureDirectionX(lhs) && isArchitectureDirectionY(rhs);
const aY_bX = isArchitectureDirectionY(lhs) && isArchitectureDirectionX(rhs);
return aX_bY || aY_bX;
}, "isArchitecturePairXY");
isValidArchitectureDirectionPair = /* @__PURE__ */ __name(function(x5) {
return x5 !== "LL" && x5 !== "RR" && x5 !== "TT" && x5 !== "BB";
}, "isValidArchitectureDirectionPair");
getArchitectureDirectionPair = /* @__PURE__ */ __name(function(sourceDir, targetDir) {
const pair = `${sourceDir}${targetDir}`;
return isValidArchitectureDirectionPair(pair) ? pair : void 0;
}, "getArchitectureDirectionPair");
shiftPositionByArchitectureDirectionPair = /* @__PURE__ */ __name(function([x5, y6], pair) {
const lhs = pair[0];
const rhs = pair[1];
if (isArchitectureDirectionX(lhs)) {
if (isArchitectureDirectionY(rhs)) {
return [x5 + (lhs === "L" ? -1 : 1), y6 + (rhs === "T" ? 1 : -1)];
} else {
return [x5 + (lhs === "L" ? -1 : 1), y6];
}
} else {
if (isArchitectureDirectionX(rhs)) {
return [x5 + (rhs === "L" ? 1 : -1), y6 + (lhs === "T" ? 1 : -1)];
} else {
return [x5, y6 + (lhs === "T" ? 1 : -1)];
}
}
}, "shiftPositionByArchitectureDirectionPair");
getArchitectureDirectionXYFactors = /* @__PURE__ */ __name(function(pair) {
if (pair === "LT" || pair === "TL") {
return [1, 1];
} else if (pair === "BL" || pair === "LB") {
return [1, -1];
} else if (pair === "BR" || pair === "RB") {
return [-1, -1];
} else {
return [-1, 1];
}
}, "getArchitectureDirectionXYFactors");
getArchitectureDirectionAlignment = /* @__PURE__ */ __name(function(a2, b3) {
if (isArchitectureDirectionXY(a2, b3)) {
return "bend";
} else if (isArchitectureDirectionX(a2)) {
return "horizontal";
}
return "vertical";
}, "getArchitectureDirectionAlignment");
isArchitectureService = /* @__PURE__ */ __name(function(x5) {
const temp = x5;
return temp.type === "service";
}, "isArchitectureService");
isArchitectureJunction = /* @__PURE__ */ __name(function(x5) {
const temp = x5;
return temp.type === "junction";
}, "isArchitectureJunction");
edgeData = /* @__PURE__ */ __name((edge) => {
return edge.data();
}, "edgeData");
nodeData = /* @__PURE__ */ __name((node2) => {
return node2.data();
}, "nodeData");
}
});
// src/diagrams/architecture/architectureDb.ts
var DEFAULT_ARCHITECTURE_CONFIG, ArchitectureDB;
var init_architectureDb = __esm({
"src/diagrams/architecture/architectureDb.ts"() {
"use strict";
init_config();
init_defaultConfig();
init_utils2();
init_commonDb();
init_architectureTypes();
DEFAULT_ARCHITECTURE_CONFIG = defaultConfig_default.architecture;
ArchitectureDB = class {
constructor() {
this.nodes = {};
this.groups = {};
this.edges = [];
this.registeredIds = {};
this.elements = {};
this.setAccTitle = setAccTitle;
this.getAccTitle = getAccTitle;
this.setDiagramTitle = setDiagramTitle;
this.getDiagramTitle = getDiagramTitle;
this.getAccDescription = getAccDescription;
this.setAccDescription = setAccDescription;
this.clear();
}
static {
__name(this, "ArchitectureDB");
}
clear() {
this.nodes = {};
this.groups = {};
this.edges = [];
this.registeredIds = {};
this.dataStructures = void 0;
this.elements = {};
clear();
}
addService({
id: id32,
icon: icon2,
in: parent4,
title: title2,
iconText
}) {
if (this.registeredIds[id32] !== void 0) {
throw new Error(
`The service id [${id32}] is already in use by another ${this.registeredIds[id32]}`
);
}
if (parent4 !== void 0) {
if (id32 === parent4) {
throw new Error(`The service [${id32}] cannot be placed within itself`);
}
if (this.registeredIds[parent4] === void 0) {
throw new Error(
`The service [${id32}]'s parent does not exist. Please make sure the parent is created before this service`
);
}
if (this.registeredIds[parent4] === "node") {
throw new Error(`The service [${id32}]'s parent is not a group`);
}
}
this.registeredIds[id32] = "node";
this.nodes[id32] = {
id: id32,
type: "service",
icon: icon2,
iconText,
title: title2,
edges: [],
in: parent4
};
}
getServices() {
return Object.values(this.nodes).filter(isArchitectureService);
}
addJunction({ id: id32, in: parent4 }) {
if (this.registeredIds[id32] !== void 0) {
throw new Error(
`The junction id [${id32}] is already in use by another ${this.registeredIds[id32]}`
);
}
if (parent4 !== void 0) {
if (id32 === parent4) {
throw new Error(`The junction [${id32}] cannot be placed within itself`);
}
if (this.registeredIds[parent4] === void 0) {
throw new Error(
`The junction [${id32}]'s parent does not exist. Please make sure the parent is created before this junction`
);
}
if (this.registeredIds[parent4] === "node") {
throw new Error(`The junction [${id32}]'s parent is not a group`);
}
}
this.registeredIds[id32] = "node";
this.nodes[id32] = {
id: id32,
type: "junction",
edges: [],
in: parent4
};
}
getJunctions() {
return Object.values(this.nodes).filter(isArchitectureJunction);
}
getNodes() {
return Object.values(this.nodes);
}
getNode(id32) {
return this.nodes[id32] ?? null;
}
addGroup({ id: id32, icon: icon2, in: parent4, title: title2 }) {
if (this.registeredIds?.[id32] !== void 0) {
throw new Error(
`The group id [${id32}] is already in use by another ${this.registeredIds[id32]}`
);
}
if (parent4 !== void 0) {
if (id32 === parent4) {
throw new Error(`The group [${id32}] cannot be placed within itself`);
}
if (this.registeredIds?.[parent4] === void 0) {
throw new Error(
`The group [${id32}]'s parent does not exist. Please make sure the parent is created before this group`
);
}
if (this.registeredIds?.[parent4] === "node") {
throw new Error(`The group [${id32}]'s parent is not a group`);
}
}
this.registeredIds[id32] = "group";
this.groups[id32] = {
id: id32,
icon: icon2,
title: title2,
in: parent4
};
}
getGroups() {
return Object.values(this.groups);
}
addEdge({
lhsId,
rhsId,
lhsDir,
rhsDir,
lhsInto,
rhsInto,
lhsGroup,
rhsGroup,
title: title2
}) {
if (!isArchitectureDirection(lhsDir)) {
throw new Error(
`Invalid direction given for left hand side of edge ${lhsId}--${rhsId}. Expected (L,R,T,B) got ${String(lhsDir)}`
);
}
if (!isArchitectureDirection(rhsDir)) {
throw new Error(
`Invalid direction given for right hand side of edge ${lhsId}--${rhsId}. Expected (L,R,T,B) got ${String(rhsDir)}`
);
}
if (this.nodes[lhsId] === void 0 && this.groups[lhsId] === void 0) {
throw new Error(
`The left-hand id [${lhsId}] does not yet exist. Please create the service/group before declaring an edge to it.`
);
}
if (this.nodes[rhsId] === void 0 && this.groups[rhsId] === void 0) {
throw new Error(
`The right-hand id [${rhsId}] does not yet exist. Please create the service/group before declaring an edge to it.`
);
}
const lhsGroupId = this.nodes[lhsId].in;
const rhsGroupId = this.nodes[rhsId].in;
if (lhsGroup && lhsGroupId && rhsGroupId && lhsGroupId == rhsGroupId) {
throw new Error(
`The left-hand id [${lhsId}] is modified to traverse the group boundary, but the edge does not pass through two groups.`
);
}
if (rhsGroup && lhsGroupId && rhsGroupId && lhsGroupId == rhsGroupId) {
throw new Error(
`The right-hand id [${rhsId}] is modified to traverse the group boundary, but the edge does not pass through two groups.`
);
}
const edge = {
lhsId,
lhsDir,
lhsInto,
lhsGroup,
rhsId,
rhsDir,
rhsInto,
rhsGroup,
title: title2
};
this.edges.push(edge);
if (this.nodes[lhsId] && this.nodes[rhsId]) {
this.nodes[lhsId].edges.push(this.edges[this.edges.length - 1]);
this.nodes[rhsId].edges.push(this.edges[this.edges.length - 1]);
}
}
getEdges() {
return this.edges;
}
/**
* Returns the current diagram's adjacency list, spatial map, & group alignments.
* If they have not been created, run the algorithms to generate them.
* @returns
*/
getDataStructures() {
if (this.dataStructures === void 0) {
const groupAlignments = {};
const adjList = Object.entries(this.nodes).reduce((prevOuter, [id32, service]) => {
prevOuter[id32] = service.edges.reduce((prevInner, edge) => {
const lhsGroupId = this.getNode(edge.lhsId)?.in;
const rhsGroupId = this.getNode(edge.rhsId)?.in;
if (lhsGroupId && rhsGroupId && lhsGroupId !== rhsGroupId) {
const alignment = getArchitectureDirectionAlignment(edge.lhsDir, edge.rhsDir);
if (alignment !== "bend") {
groupAlignments[lhsGroupId] ??= {};
groupAlignments[lhsGroupId][rhsGroupId] = alignment;
groupAlignments[rhsGroupId] ??= {};
groupAlignments[rhsGroupId][lhsGroupId] = alignment;
}
}
if (edge.lhsId === id32) {
const pair = getArchitectureDirectionPair(edge.lhsDir, edge.rhsDir);
if (pair) {
prevInner[pair] = edge.rhsId;
}
} else {
const pair = getArchitectureDirectionPair(edge.rhsDir, edge.lhsDir);
if (pair) {
prevInner[pair] = edge.lhsId;
}
}
return prevInner;
}, {});
return prevOuter;
}, {});
const firstId = Object.keys(adjList)[0];
const visited = { [firstId]: 1 };
const notVisited = Object.keys(adjList).reduce(
(prev2, id32) => id32 === firstId ? prev2 : { ...prev2, [id32]: 1 },
{}
);
const BFS = /* @__PURE__ */ __name((startingId) => {
const spatialMap = { [startingId]: [0, 0] };
const queue = [startingId];
while (queue.length > 0) {
const id32 = queue.shift();
if (id32) {
visited[id32] = 1;
delete notVisited[id32];
const adj = adjList[id32];
const [posX, posY] = spatialMap[id32];
Object.entries(adj).forEach(([dir2, rhsId]) => {
if (!visited[rhsId]) {
spatialMap[rhsId] = shiftPositionByArchitectureDirectionPair(
[posX, posY],
dir2
);
queue.push(rhsId);
}
});
}
}
return spatialMap;
}, "BFS");
const spatialMaps = [BFS(firstId)];
while (Object.keys(notVisited).length > 0) {
spatialMaps.push(BFS(Object.keys(notVisited)[0]));
}
this.dataStructures = {
adjList,
spatialMaps,
groupAlignments
};
}
return this.dataStructures;
}
setElementForId(id32, element3) {
this.elements[id32] = element3;
}
getElementById(id32) {
return this.elements[id32];
}
getConfig() {
return cleanAndMerge({
...DEFAULT_ARCHITECTURE_CONFIG,
...getConfig().architecture
});
}
getConfigField(field) {
return this.getConfig()[field];
}
};
}
});
// src/diagrams/architecture/architectureParser.ts
var populateDb2, parser22;
var init_architectureParser = __esm({
"src/diagrams/architecture/architectureParser.ts"() {
"use strict";
init_mermaid_parser_core();
init_logger();
init_populateCommonDb();
init_architectureDb();
populateDb2 = /* @__PURE__ */ __name((ast, db8) => {
populateCommonDb(ast, db8);
ast.groups.map((group2) => db8.addGroup(group2));
ast.services.map((service) => db8.addService({ ...service, type: "service" }));
ast.junctions.map((service) => db8.addJunction({ ...service, type: "junction" }));
ast.edges.map((edge) => db8.addEdge(edge));
}, "populateDb");
parser22 = {
parser: {
// @ts-expect-error - ArchitectureDB is not assignable to DiagramDB
yy: void 0
},
parse: /* @__PURE__ */ __name(async (input) => {
const ast = await parse3("architecture", input);
log.debug(ast);
const db8 = parser22.parser?.yy;
if (!(db8 instanceof ArchitectureDB)) {
throw new Error(
"parser.parser?.yy was not a ArchitectureDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues."
);
}
populateDb2(ast, db8);
}, "parse")
};
}
});
// src/diagrams/architecture/architectureStyles.ts
var getStyles18, architectureStyles_default;
var init_architectureStyles = __esm({
"src/diagrams/architecture/architectureStyles.ts"() {
"use strict";
getStyles18 = /* @__PURE__ */ __name((options2) => `
.edge {
stroke-width: ${options2.archEdgeWidth};
stroke: ${options2.archEdgeColor};
fill: none;
}
.arrow {
fill: ${options2.archEdgeArrowColor};
}
.node-bkg {
fill: none;
stroke: ${options2.archGroupBorderColor};
stroke-width: ${options2.archGroupBorderWidth};
stroke-dasharray: 8;
}
.node-icon-text {
display: flex;
align-items: center;
}
.node-icon-text > div {
color: #fff;
margin: 1px;
height: fit-content;
text-align: center;
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
}
`, "getStyles");
architectureStyles_default = getStyles18;
}
});
// ../../node_modules/.pnpm/layout-base@2.0.1/node_modules/layout-base/layout-base.js
var require_layout_base2 = __commonJS({
"../../node_modules/.pnpm/layout-base@2.0.1/node_modules/layout-base/layout-base.js"(exports2, module2) {
"use strict";
(/* @__PURE__ */ __name((function webpackUniversalModuleDefinition(root3, factory) {
if (typeof exports2 === "object" && typeof module2 === "object")
module2.exports = factory();
else if (typeof define === "function" && define.amd)
define([], factory);
else if (typeof exports2 === "object")
exports2["layoutBase"] = factory();
else
root3["layoutBase"] = factory();
}), "webpackUniversalModuleDefinition"))(exports2, function() {
return (
/******/
(function(modules2) {
var installedModules = {};
function __webpack_require__(moduleId) {
if (installedModules[moduleId]) {
return installedModules[moduleId].exports;
}
var module3 = installedModules[moduleId] = {
/******/
i: moduleId,
/******/
l: false,
/******/
exports: {}
/******/
};
modules2[moduleId].call(module3.exports, module3, module3.exports, __webpack_require__);
module3.l = true;
return module3.exports;
}
__name(__webpack_require__, "__webpack_require__");
__webpack_require__.m = modules2;
__webpack_require__.c = installedModules;
__webpack_require__.i = function(value2) {
return value2;
};
__webpack_require__.d = function(exports3, name, getter) {
if (!__webpack_require__.o(exports3, name)) {
Object.defineProperty(exports3, name, {
/******/
configurable: false,
/******/
enumerable: true,
/******/
get: getter
/******/
});
}
};
__webpack_require__.n = function(module3) {
var getter = module3 && module3.__esModule ? (
/******/
/* @__PURE__ */ __name(function getDefault() {
return module3["default"];
}, "getDefault")
) : (
/******/
/* @__PURE__ */ __name(function getModuleExports() {
return module3;
}, "getModuleExports")
);
__webpack_require__.d(getter, "a", getter);
return getter;
};
__webpack_require__.o = function(object3, property2) {
return Object.prototype.hasOwnProperty.call(object3, property2);
};
__webpack_require__.p = "";
return __webpack_require__(__webpack_require__.s = 28);
})([
/* 0 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function LayoutConstants() {
}
__name(LayoutConstants, "LayoutConstants");
LayoutConstants.QUALITY = 1;
LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED = false;
LayoutConstants.DEFAULT_INCREMENTAL = false;
LayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT = true;
LayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT = false;
LayoutConstants.DEFAULT_ANIMATION_PERIOD = 50;
LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES = false;
LayoutConstants.DEFAULT_GRAPH_MARGIN = 15;
LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = false;
LayoutConstants.SIMPLE_NODE_SIZE = 40;
LayoutConstants.SIMPLE_NODE_HALF_SIZE = LayoutConstants.SIMPLE_NODE_SIZE / 2;
LayoutConstants.EMPTY_COMPOUND_NODE_SIZE = 40;
LayoutConstants.MIN_EDGE_LENGTH = 1;
LayoutConstants.WORLD_BOUNDARY = 1e6;
LayoutConstants.INITIAL_WORLD_BOUNDARY = LayoutConstants.WORLD_BOUNDARY / 1e3;
LayoutConstants.WORLD_CENTER_X = 1200;
LayoutConstants.WORLD_CENTER_Y = 900;
module3.exports = LayoutConstants;
}),
/* 1 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var LGraphObject = __webpack_require__(2);
var IGeometry = __webpack_require__(8);
var IMath = __webpack_require__(9);
function LEdge(source, target, vEdge) {
LGraphObject.call(this, vEdge);
this.isOverlapingSourceAndTarget = false;
this.vGraphObject = vEdge;
this.bendpoints = [];
this.source = source;
this.target = target;
}
__name(LEdge, "LEdge");
LEdge.prototype = Object.create(LGraphObject.prototype);
for (var prop in LGraphObject) {
LEdge[prop] = LGraphObject[prop];
}
LEdge.prototype.getSource = function() {
return this.source;
};
LEdge.prototype.getTarget = function() {
return this.target;
};
LEdge.prototype.isInterGraph = function() {
return this.isInterGraph;
};
LEdge.prototype.getLength = function() {
return this.length;
};
LEdge.prototype.isOverlapingSourceAndTarget = function() {
return this.isOverlapingSourceAndTarget;
};
LEdge.prototype.getBendpoints = function() {
return this.bendpoints;
};
LEdge.prototype.getLca = function() {
return this.lca;
};
LEdge.prototype.getSourceInLca = function() {
return this.sourceInLca;
};
LEdge.prototype.getTargetInLca = function() {
return this.targetInLca;
};
LEdge.prototype.getOtherEnd = function(node2) {
if (this.source === node2) {
return this.target;
} else if (this.target === node2) {
return this.source;
} else {
throw "Node is not incident with this edge";
}
};
LEdge.prototype.getOtherEndInGraph = function(node2, graph) {
var otherEnd = this.getOtherEnd(node2);
var root3 = graph.getGraphManager().getRoot();
while (true) {
if (otherEnd.getOwner() == graph) {
return otherEnd;
}
if (otherEnd.getOwner() == root3) {
break;
}
otherEnd = otherEnd.getOwner().getParent();
}
return null;
};
LEdge.prototype.updateLength = function() {
var clipPointCoordinates = new Array(4);
this.isOverlapingSourceAndTarget = IGeometry.getIntersection(this.target.getRect(), this.source.getRect(), clipPointCoordinates);
if (!this.isOverlapingSourceAndTarget) {
this.lengthX = clipPointCoordinates[0] - clipPointCoordinates[2];
this.lengthY = clipPointCoordinates[1] - clipPointCoordinates[3];
if (Math.abs(this.lengthX) < 1) {
this.lengthX = IMath.sign(this.lengthX);
}
if (Math.abs(this.lengthY) < 1) {
this.lengthY = IMath.sign(this.lengthY);
}
this.length = Math.sqrt(this.lengthX * this.lengthX + this.lengthY * this.lengthY);
}
};
LEdge.prototype.updateLengthSimple = function() {
this.lengthX = this.target.getCenterX() - this.source.getCenterX();
this.lengthY = this.target.getCenterY() - this.source.getCenterY();
if (Math.abs(this.lengthX) < 1) {
this.lengthX = IMath.sign(this.lengthX);
}
if (Math.abs(this.lengthY) < 1) {
this.lengthY = IMath.sign(this.lengthY);
}
this.length = Math.sqrt(this.lengthX * this.lengthX + this.lengthY * this.lengthY);
};
module3.exports = LEdge;
}),
/* 2 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function LGraphObject(vGraphObject) {
this.vGraphObject = vGraphObject;
}
__name(LGraphObject, "LGraphObject");
module3.exports = LGraphObject;
}),
/* 3 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var LGraphObject = __webpack_require__(2);
var Integer = __webpack_require__(10);
var RectangleD = __webpack_require__(13);
var LayoutConstants = __webpack_require__(0);
var RandomSeed = __webpack_require__(16);
var PointD = __webpack_require__(5);
function LNode(gm, loc, size4, vNode) {
if (size4 == null && vNode == null) {
vNode = loc;
}
LGraphObject.call(this, vNode);
if (gm.graphManager != null) gm = gm.graphManager;
this.estimatedSize = Integer.MIN_VALUE;
this.inclusionTreeDepth = Integer.MAX_VALUE;
this.vGraphObject = vNode;
this.edges = [];
this.graphManager = gm;
if (size4 != null && loc != null) this.rect = new RectangleD(loc.x, loc.y, size4.width, size4.height);
else this.rect = new RectangleD();
}
__name(LNode, "LNode");
LNode.prototype = Object.create(LGraphObject.prototype);
for (var prop in LGraphObject) {
LNode[prop] = LGraphObject[prop];
}
LNode.prototype.getEdges = function() {
return this.edges;
};
LNode.prototype.getChild = function() {
return this.child;
};
LNode.prototype.getOwner = function() {
return this.owner;
};
LNode.prototype.getWidth = function() {
return this.rect.width;
};
LNode.prototype.setWidth = function(width3) {
this.rect.width = width3;
};
LNode.prototype.getHeight = function() {
return this.rect.height;
};
LNode.prototype.setHeight = function(height2) {
this.rect.height = height2;
};
LNode.prototype.getCenterX = function() {
return this.rect.x + this.rect.width / 2;
};
LNode.prototype.getCenterY = function() {
return this.rect.y + this.rect.height / 2;
};
LNode.prototype.getCenter = function() {
return new PointD(this.rect.x + this.rect.width / 2, this.rect.y + this.rect.height / 2);
};
LNode.prototype.getLocation = function() {
return new PointD(this.rect.x, this.rect.y);
};
LNode.prototype.getRect = function() {
return this.rect;
};
LNode.prototype.getDiagonal = function() {
return Math.sqrt(this.rect.width * this.rect.width + this.rect.height * this.rect.height);
};
LNode.prototype.getHalfTheDiagonal = function() {
return Math.sqrt(this.rect.height * this.rect.height + this.rect.width * this.rect.width) / 2;
};
LNode.prototype.setRect = function(upperLeft, dimension) {
this.rect.x = upperLeft.x;
this.rect.y = upperLeft.y;
this.rect.width = dimension.width;
this.rect.height = dimension.height;
};
LNode.prototype.setCenter = function(cx, cy) {
this.rect.x = cx - this.rect.width / 2;
this.rect.y = cy - this.rect.height / 2;
};
LNode.prototype.setLocation = function(x5, y6) {
this.rect.x = x5;
this.rect.y = y6;
};
LNode.prototype.moveBy = function(dx, dy) {
this.rect.x += dx;
this.rect.y += dy;
};
LNode.prototype.getEdgeListToNode = function(to) {
var edgeList2 = [];
var edge;
var self2 = this;
self2.edges.forEach(function(edge2) {
if (edge2.target == to) {
if (edge2.source != self2) throw "Incorrect edge source!";
edgeList2.push(edge2);
}
});
return edgeList2;
};
LNode.prototype.getEdgesBetween = function(other) {
var edgeList2 = [];
var edge;
var self2 = this;
self2.edges.forEach(function(edge2) {
if (!(edge2.source == self2 || edge2.target == self2)) throw "Incorrect edge source and/or target";
if (edge2.target == other || edge2.source == other) {
edgeList2.push(edge2);
}
});
return edgeList2;
};
LNode.prototype.getNeighborsList = function() {
var neighbors = /* @__PURE__ */ new Set();
var self2 = this;
self2.edges.forEach(function(edge) {
if (edge.source == self2) {
neighbors.add(edge.target);
} else {
if (edge.target != self2) {
throw "Incorrect incidency!";
}
neighbors.add(edge.source);
}
});
return neighbors;
};
LNode.prototype.withChildren = function() {
var withNeighborsList = /* @__PURE__ */ new Set();
var childNode;
var children2;
withNeighborsList.add(this);
if (this.child != null) {
var nodes5 = this.child.getNodes();
for (var i2 = 0; i2 < nodes5.length; i2++) {
childNode = nodes5[i2];
children2 = childNode.withChildren();
children2.forEach(function(node2) {
withNeighborsList.add(node2);
});
}
}
return withNeighborsList;
};
LNode.prototype.getNoOfChildren = function() {
var noOfChildren = 0;
var childNode;
if (this.child == null) {
noOfChildren = 1;
} else {
var nodes5 = this.child.getNodes();
for (var i2 = 0; i2 < nodes5.length; i2++) {
childNode = nodes5[i2];
noOfChildren += childNode.getNoOfChildren();
}
}
if (noOfChildren == 0) {
noOfChildren = 1;
}
return noOfChildren;
};
LNode.prototype.getEstimatedSize = function() {
if (this.estimatedSize == Integer.MIN_VALUE) {
throw "assert failed";
}
return this.estimatedSize;
};
LNode.prototype.calcEstimatedSize = function() {
if (this.child == null) {
return this.estimatedSize = (this.rect.width + this.rect.height) / 2;
} else {
this.estimatedSize = this.child.calcEstimatedSize();
this.rect.width = this.estimatedSize;
this.rect.height = this.estimatedSize;
return this.estimatedSize;
}
};
LNode.prototype.scatter = function() {
var randomCenterX;
var randomCenterY;
var minX = -LayoutConstants.INITIAL_WORLD_BOUNDARY;
var maxX = LayoutConstants.INITIAL_WORLD_BOUNDARY;
randomCenterX = LayoutConstants.WORLD_CENTER_X + RandomSeed.nextDouble() * (maxX - minX) + minX;
var minY = -LayoutConstants.INITIAL_WORLD_BOUNDARY;
var maxY = LayoutConstants.INITIAL_WORLD_BOUNDARY;
randomCenterY = LayoutConstants.WORLD_CENTER_Y + RandomSeed.nextDouble() * (maxY - minY) + minY;
this.rect.x = randomCenterX;
this.rect.y = randomCenterY;
};
LNode.prototype.updateBounds = function() {
if (this.getChild() == null) {
throw "assert failed";
}
if (this.getChild().getNodes().length != 0) {
var childGraph = this.getChild();
childGraph.updateBounds(true);
this.rect.x = childGraph.getLeft();
this.rect.y = childGraph.getTop();
this.setWidth(childGraph.getRight() - childGraph.getLeft());
this.setHeight(childGraph.getBottom() - childGraph.getTop());
if (LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS) {
var width3 = childGraph.getRight() - childGraph.getLeft();
var height2 = childGraph.getBottom() - childGraph.getTop();
if (this.labelWidth) {
if (this.labelPosHorizontal == "left") {
this.rect.x -= this.labelWidth;
this.setWidth(width3 + this.labelWidth);
} else if (this.labelPosHorizontal == "center" && this.labelWidth > width3) {
this.rect.x -= (this.labelWidth - width3) / 2;
this.setWidth(this.labelWidth);
} else if (this.labelPosHorizontal == "right") {
this.setWidth(width3 + this.labelWidth);
}
}
if (this.labelHeight) {
if (this.labelPosVertical == "top") {
this.rect.y -= this.labelHeight;
this.setHeight(height2 + this.labelHeight);
} else if (this.labelPosVertical == "center" && this.labelHeight > height2) {
this.rect.y -= (this.labelHeight - height2) / 2;
this.setHeight(this.labelHeight);
} else if (this.labelPosVertical == "bottom") {
this.setHeight(height2 + this.labelHeight);
}
}
}
}
};
LNode.prototype.getInclusionTreeDepth = function() {
if (this.inclusionTreeDepth == Integer.MAX_VALUE) {
throw "assert failed";
}
return this.inclusionTreeDepth;
};
LNode.prototype.transform = function(trans) {
var left3 = this.rect.x;
if (left3 > LayoutConstants.WORLD_BOUNDARY) {
left3 = LayoutConstants.WORLD_BOUNDARY;
} else if (left3 < -LayoutConstants.WORLD_BOUNDARY) {
left3 = -LayoutConstants.WORLD_BOUNDARY;
}
var top2 = this.rect.y;
if (top2 > LayoutConstants.WORLD_BOUNDARY) {
top2 = LayoutConstants.WORLD_BOUNDARY;
} else if (top2 < -LayoutConstants.WORLD_BOUNDARY) {
top2 = -LayoutConstants.WORLD_BOUNDARY;
}
var leftTop = new PointD(left3, top2);
var vLeftTop = trans.inverseTransformPoint(leftTop);
this.setLocation(vLeftTop.x, vLeftTop.y);
};
LNode.prototype.getLeft = function() {
return this.rect.x;
};
LNode.prototype.getRight = function() {
return this.rect.x + this.rect.width;
};
LNode.prototype.getTop = function() {
return this.rect.y;
};
LNode.prototype.getBottom = function() {
return this.rect.y + this.rect.height;
};
LNode.prototype.getParent = function() {
if (this.owner == null) {
return null;
}
return this.owner.getParent();
};
module3.exports = LNode;
}),
/* 4 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var LayoutConstants = __webpack_require__(0);
function FDLayoutConstants() {
}
__name(FDLayoutConstants, "FDLayoutConstants");
for (var prop in LayoutConstants) {
FDLayoutConstants[prop] = LayoutConstants[prop];
}
FDLayoutConstants.MAX_ITERATIONS = 2500;
FDLayoutConstants.DEFAULT_EDGE_LENGTH = 50;
FDLayoutConstants.DEFAULT_SPRING_STRENGTH = 0.45;
FDLayoutConstants.DEFAULT_REPULSION_STRENGTH = 4500;
FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH = 0.4;
FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = 1;
FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR = 3.8;
FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = 1.5;
FDLayoutConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION = true;
FDLayoutConstants.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION = true;
FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = 0.3;
FDLayoutConstants.COOLING_ADAPTATION_FACTOR = 0.33;
FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT = 1e3;
FDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT = 5e3;
FDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL = 100;
FDLayoutConstants.MAX_NODE_DISPLACEMENT = FDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL * 3;
FDLayoutConstants.MIN_REPULSION_DIST = FDLayoutConstants.DEFAULT_EDGE_LENGTH / 10;
FDLayoutConstants.CONVERGENCE_CHECK_PERIOD = 100;
FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = 0.1;
FDLayoutConstants.MIN_EDGE_LENGTH = 1;
FDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD = 10;
module3.exports = FDLayoutConstants;
}),
/* 5 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function PointD(x5, y6) {
if (x5 == null && y6 == null) {
this.x = 0;
this.y = 0;
} else {
this.x = x5;
this.y = y6;
}
}
__name(PointD, "PointD");
PointD.prototype.getX = function() {
return this.x;
};
PointD.prototype.getY = function() {
return this.y;
};
PointD.prototype.setX = function(x5) {
this.x = x5;
};
PointD.prototype.setY = function(y6) {
this.y = y6;
};
PointD.prototype.getDifference = function(pt) {
return new DimensionD(this.x - pt.x, this.y - pt.y);
};
PointD.prototype.getCopy = function() {
return new PointD(this.x, this.y);
};
PointD.prototype.translate = function(dim) {
this.x += dim.width;
this.y += dim.height;
return this;
};
module3.exports = PointD;
}),
/* 6 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var LGraphObject = __webpack_require__(2);
var Integer = __webpack_require__(10);
var LayoutConstants = __webpack_require__(0);
var LGraphManager = __webpack_require__(7);
var LNode = __webpack_require__(3);
var LEdge = __webpack_require__(1);
var RectangleD = __webpack_require__(13);
var Point3 = __webpack_require__(12);
var LinkedList = __webpack_require__(11);
function LGraph(parent4, obj2, vGraph) {
LGraphObject.call(this, vGraph);
this.estimatedSize = Integer.MIN_VALUE;
this.margin = LayoutConstants.DEFAULT_GRAPH_MARGIN;
this.edges = [];
this.nodes = [];
this.isConnected = false;
this.parent = parent4;
if (obj2 != null && obj2 instanceof LGraphManager) {
this.graphManager = obj2;
} else if (obj2 != null && obj2 instanceof Layout) {
this.graphManager = obj2.graphManager;
}
}
__name(LGraph, "LGraph");
LGraph.prototype = Object.create(LGraphObject.prototype);
for (var prop in LGraphObject) {
LGraph[prop] = LGraphObject[prop];
}
LGraph.prototype.getNodes = function() {
return this.nodes;
};
LGraph.prototype.getEdges = function() {
return this.edges;
};
LGraph.prototype.getGraphManager = function() {
return this.graphManager;
};
LGraph.prototype.getParent = function() {
return this.parent;
};
LGraph.prototype.getLeft = function() {
return this.left;
};
LGraph.prototype.getRight = function() {
return this.right;
};
LGraph.prototype.getTop = function() {
return this.top;
};
LGraph.prototype.getBottom = function() {
return this.bottom;
};
LGraph.prototype.isConnected = function() {
return this.isConnected;
};
LGraph.prototype.add = function(obj1, sourceNode, targetNode) {
if (sourceNode == null && targetNode == null) {
var newNode = obj1;
if (this.graphManager == null) {
throw "Graph has no graph mgr!";
}
if (this.getNodes().indexOf(newNode) > -1) {
throw "Node already in graph!";
}
newNode.owner = this;
this.getNodes().push(newNode);
return newNode;
} else {
var newEdge = obj1;
if (!(this.getNodes().indexOf(sourceNode) > -1 && this.getNodes().indexOf(targetNode) > -1)) {
throw "Source or target not in graph!";
}
if (!(sourceNode.owner == targetNode.owner && sourceNode.owner == this)) {
throw "Both owners must be this graph!";
}
if (sourceNode.owner != targetNode.owner) {
return null;
}
newEdge.source = sourceNode;
newEdge.target = targetNode;
newEdge.isInterGraph = false;
this.getEdges().push(newEdge);
sourceNode.edges.push(newEdge);
if (targetNode != sourceNode) {
targetNode.edges.push(newEdge);
}
return newEdge;
}
};
LGraph.prototype.remove = function(obj) {
var node2 = obj;
if (obj instanceof LNode) {
if (node2 == null) {
throw "Node is null!";
}
if (!(node2.owner != null && node2.owner == this)) {
throw "Owner graph is invalid!";
}
if (this.graphManager == null) {
throw "Owner graph manager is invalid!";
}
var edgesToBeRemoved = node2.edges.slice();
var edge;
var s2 = edgesToBeRemoved.length;
for (var i2 = 0; i2 < s2; i2++) {
edge = edgesToBeRemoved[i2];
if (edge.isInterGraph) {
this.graphManager.remove(edge);
} else {
edge.source.owner.remove(edge);
}
}
var index = this.nodes.indexOf(node2);
if (index == -1) {
throw "Node not in owner node list!";
}
this.nodes.splice(index, 1);
} else if (obj instanceof LEdge) {
var edge = obj;
if (edge == null) {
throw "Edge is null!";
}
if (!(edge.source != null && edge.target != null)) {
throw "Source and/or target is null!";
}
if (!(edge.source.owner != null && edge.target.owner != null && edge.source.owner == this && edge.target.owner == this)) {
throw "Source and/or target owner is invalid!";
}
var sourceIndex = edge.source.edges.indexOf(edge);
var targetIndex = edge.target.edges.indexOf(edge);
if (!(sourceIndex > -1 && targetIndex > -1)) {
throw "Source and/or target doesn't know this edge!";
}
edge.source.edges.splice(sourceIndex, 1);
if (edge.target != edge.source) {
edge.target.edges.splice(targetIndex, 1);
}
var index = edge.source.owner.getEdges().indexOf(edge);
if (index == -1) {
throw "Not in owner's edge list!";
}
edge.source.owner.getEdges().splice(index, 1);
}
};
LGraph.prototype.updateLeftTop = function() {
var top2 = Integer.MAX_VALUE;
var left3 = Integer.MAX_VALUE;
var nodeTop;
var nodeLeft;
var margin;
var nodes5 = this.getNodes();
var s2 = nodes5.length;
for (var i2 = 0; i2 < s2; i2++) {
var lNode = nodes5[i2];
nodeTop = lNode.getTop();
nodeLeft = lNode.getLeft();
if (top2 > nodeTop) {
top2 = nodeTop;
}
if (left3 > nodeLeft) {
left3 = nodeLeft;
}
}
if (top2 == Integer.MAX_VALUE) {
return null;
}
if (nodes5[0].getParent().paddingLeft != void 0) {
margin = nodes5[0].getParent().paddingLeft;
} else {
margin = this.margin;
}
this.left = left3 - margin;
this.top = top2 - margin;
return new Point3(this.left, this.top);
};
LGraph.prototype.updateBounds = function(recursive) {
var left3 = Integer.MAX_VALUE;
var right3 = -Integer.MAX_VALUE;
var top2 = Integer.MAX_VALUE;
var bottom2 = -Integer.MAX_VALUE;
var nodeLeft;
var nodeRight;
var nodeTop;
var nodeBottom;
var margin;
var nodes5 = this.nodes;
var s2 = nodes5.length;
for (var i2 = 0; i2 < s2; i2++) {
var lNode = nodes5[i2];
if (recursive && lNode.child != null) {
lNode.updateBounds();
}
nodeLeft = lNode.getLeft();
nodeRight = lNode.getRight();
nodeTop = lNode.getTop();
nodeBottom = lNode.getBottom();
if (left3 > nodeLeft) {
left3 = nodeLeft;
}
if (right3 < nodeRight) {
right3 = nodeRight;
}
if (top2 > nodeTop) {
top2 = nodeTop;
}
if (bottom2 < nodeBottom) {
bottom2 = nodeBottom;
}
}
var boundingRect = new RectangleD(left3, top2, right3 - left3, bottom2 - top2);
if (left3 == Integer.MAX_VALUE) {
this.left = this.parent.getLeft();
this.right = this.parent.getRight();
this.top = this.parent.getTop();
this.bottom = this.parent.getBottom();
}
if (nodes5[0].getParent().paddingLeft != void 0) {
margin = nodes5[0].getParent().paddingLeft;
} else {
margin = this.margin;
}
this.left = boundingRect.x - margin;
this.right = boundingRect.x + boundingRect.width + margin;
this.top = boundingRect.y - margin;
this.bottom = boundingRect.y + boundingRect.height + margin;
};
LGraph.calculateBounds = function(nodes5) {
var left3 = Integer.MAX_VALUE;
var right3 = -Integer.MAX_VALUE;
var top2 = Integer.MAX_VALUE;
var bottom2 = -Integer.MAX_VALUE;
var nodeLeft;
var nodeRight;
var nodeTop;
var nodeBottom;
var s2 = nodes5.length;
for (var i2 = 0; i2 < s2; i2++) {
var lNode = nodes5[i2];
nodeLeft = lNode.getLeft();
nodeRight = lNode.getRight();
nodeTop = lNode.getTop();
nodeBottom = lNode.getBottom();
if (left3 > nodeLeft) {
left3 = nodeLeft;
}
if (right3 < nodeRight) {
right3 = nodeRight;
}
if (top2 > nodeTop) {
top2 = nodeTop;
}
if (bottom2 < nodeBottom) {
bottom2 = nodeBottom;
}
}
var boundingRect = new RectangleD(left3, top2, right3 - left3, bottom2 - top2);
return boundingRect;
};
LGraph.prototype.getInclusionTreeDepth = function() {
if (this == this.graphManager.getRoot()) {
return 1;
} else {
return this.parent.getInclusionTreeDepth();
}
};
LGraph.prototype.getEstimatedSize = function() {
if (this.estimatedSize == Integer.MIN_VALUE) {
throw "assert failed";
}
return this.estimatedSize;
};
LGraph.prototype.calcEstimatedSize = function() {
var size4 = 0;
var nodes5 = this.nodes;
var s2 = nodes5.length;
for (var i2 = 0; i2 < s2; i2++) {
var lNode = nodes5[i2];
size4 += lNode.calcEstimatedSize();
}
if (size4 == 0) {
this.estimatedSize = LayoutConstants.EMPTY_COMPOUND_NODE_SIZE;
} else {
this.estimatedSize = size4 / Math.sqrt(this.nodes.length);
}
return this.estimatedSize;
};
LGraph.prototype.updateConnected = function() {
var self2 = this;
if (this.nodes.length == 0) {
this.isConnected = true;
return;
}
var queue = new LinkedList();
var visited = /* @__PURE__ */ new Set();
var currentNode = this.nodes[0];
var neighborEdges;
var currentNeighbor;
var childrenOfNode = currentNode.withChildren();
childrenOfNode.forEach(function(node2) {
queue.push(node2);
visited.add(node2);
});
while (queue.length !== 0) {
currentNode = queue.shift();
neighborEdges = currentNode.getEdges();
var size4 = neighborEdges.length;
for (var i2 = 0; i2 < size4; i2++) {
var neighborEdge = neighborEdges[i2];
currentNeighbor = neighborEdge.getOtherEndInGraph(currentNode, this);
if (currentNeighbor != null && !visited.has(currentNeighbor)) {
var childrenOfNeighbor = currentNeighbor.withChildren();
childrenOfNeighbor.forEach(function(node2) {
queue.push(node2);
visited.add(node2);
});
}
}
}
this.isConnected = false;
if (visited.size >= this.nodes.length) {
var noOfVisitedInThisGraph = 0;
visited.forEach(function(visitedNode) {
if (visitedNode.owner == self2) {
noOfVisitedInThisGraph++;
}
});
if (noOfVisitedInThisGraph == this.nodes.length) {
this.isConnected = true;
}
}
};
module3.exports = LGraph;
}),
/* 7 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var LGraph;
var LEdge = __webpack_require__(1);
function LGraphManager(layout7) {
LGraph = __webpack_require__(6);
this.layout = layout7;
this.graphs = [];
this.edges = [];
}
__name(LGraphManager, "LGraphManager");
LGraphManager.prototype.addRoot = function() {
var ngraph = this.layout.newGraph();
var nnode = this.layout.newNode(null);
var root3 = this.add(ngraph, nnode);
this.setRootGraph(root3);
return this.rootGraph;
};
LGraphManager.prototype.add = function(newGraph, parentNode, newEdge, sourceNode, targetNode) {
if (newEdge == null && sourceNode == null && targetNode == null) {
if (newGraph == null) {
throw "Graph is null!";
}
if (parentNode == null) {
throw "Parent node is null!";
}
if (this.graphs.indexOf(newGraph) > -1) {
throw "Graph already in this graph mgr!";
}
this.graphs.push(newGraph);
if (newGraph.parent != null) {
throw "Already has a parent!";
}
if (parentNode.child != null) {
throw "Already has a child!";
}
newGraph.parent = parentNode;
parentNode.child = newGraph;
return newGraph;
} else {
targetNode = newEdge;
sourceNode = parentNode;
newEdge = newGraph;
var sourceGraph = sourceNode.getOwner();
var targetGraph = targetNode.getOwner();
if (!(sourceGraph != null && sourceGraph.getGraphManager() == this)) {
throw "Source not in this graph mgr!";
}
if (!(targetGraph != null && targetGraph.getGraphManager() == this)) {
throw "Target not in this graph mgr!";
}
if (sourceGraph == targetGraph) {
newEdge.isInterGraph = false;
return sourceGraph.add(newEdge, sourceNode, targetNode);
} else {
newEdge.isInterGraph = true;
newEdge.source = sourceNode;
newEdge.target = targetNode;
if (this.edges.indexOf(newEdge) > -1) {
throw "Edge already in inter-graph edge list!";
}
this.edges.push(newEdge);
if (!(newEdge.source != null && newEdge.target != null)) {
throw "Edge source and/or target is null!";
}
if (!(newEdge.source.edges.indexOf(newEdge) == -1 && newEdge.target.edges.indexOf(newEdge) == -1)) {
throw "Edge already in source and/or target incidency list!";
}
newEdge.source.edges.push(newEdge);
newEdge.target.edges.push(newEdge);
return newEdge;
}
}
};
LGraphManager.prototype.remove = function(lObj) {
if (lObj instanceof LGraph) {
var graph = lObj;
if (graph.getGraphManager() != this) {
throw "Graph not in this graph mgr";
}
if (!(graph == this.rootGraph || graph.parent != null && graph.parent.graphManager == this)) {
throw "Invalid parent node!";
}
var edgesToBeRemoved = [];
edgesToBeRemoved = edgesToBeRemoved.concat(graph.getEdges());
var edge;
var s2 = edgesToBeRemoved.length;
for (var i2 = 0; i2 < s2; i2++) {
edge = edgesToBeRemoved[i2];
graph.remove(edge);
}
var nodesToBeRemoved = [];
nodesToBeRemoved = nodesToBeRemoved.concat(graph.getNodes());
var node2;
s2 = nodesToBeRemoved.length;
for (var i2 = 0; i2 < s2; i2++) {
node2 = nodesToBeRemoved[i2];
graph.remove(node2);
}
if (graph == this.rootGraph) {
this.setRootGraph(null);
}
var index = this.graphs.indexOf(graph);
this.graphs.splice(index, 1);
graph.parent = null;
} else if (lObj instanceof LEdge) {
edge = lObj;
if (edge == null) {
throw "Edge is null!";
}
if (!edge.isInterGraph) {
throw "Not an inter-graph edge!";
}
if (!(edge.source != null && edge.target != null)) {
throw "Source and/or target is null!";
}
if (!(edge.source.edges.indexOf(edge) != -1 && edge.target.edges.indexOf(edge) != -1)) {
throw "Source and/or target doesn't know this edge!";
}
var index = edge.source.edges.indexOf(edge);
edge.source.edges.splice(index, 1);
index = edge.target.edges.indexOf(edge);
edge.target.edges.splice(index, 1);
if (!(edge.source.owner != null && edge.source.owner.getGraphManager() != null)) {
throw "Edge owner graph or owner graph manager is null!";
}
if (edge.source.owner.getGraphManager().edges.indexOf(edge) == -1) {
throw "Not in owner graph manager's edge list!";
}
var index = edge.source.owner.getGraphManager().edges.indexOf(edge);
edge.source.owner.getGraphManager().edges.splice(index, 1);
}
};
LGraphManager.prototype.updateBounds = function() {
this.rootGraph.updateBounds(true);
};
LGraphManager.prototype.getGraphs = function() {
return this.graphs;
};
LGraphManager.prototype.getAllNodes = function() {
if (this.allNodes == null) {
var nodeList = [];
var graphs = this.getGraphs();
var s2 = graphs.length;
for (var i2 = 0; i2 < s2; i2++) {
nodeList = nodeList.concat(graphs[i2].getNodes());
}
this.allNodes = nodeList;
}
return this.allNodes;
};
LGraphManager.prototype.resetAllNodes = function() {
this.allNodes = null;
};
LGraphManager.prototype.resetAllEdges = function() {
this.allEdges = null;
};
LGraphManager.prototype.resetAllNodesToApplyGravitation = function() {
this.allNodesToApplyGravitation = null;
};
LGraphManager.prototype.getAllEdges = function() {
if (this.allEdges == null) {
var edgeList2 = [];
var graphs = this.getGraphs();
var s2 = graphs.length;
for (var i2 = 0; i2 < graphs.length; i2++) {
edgeList2 = edgeList2.concat(graphs[i2].getEdges());
}
edgeList2 = edgeList2.concat(this.edges);
this.allEdges = edgeList2;
}
return this.allEdges;
};
LGraphManager.prototype.getAllNodesToApplyGravitation = function() {
return this.allNodesToApplyGravitation;
};
LGraphManager.prototype.setAllNodesToApplyGravitation = function(nodeList) {
if (this.allNodesToApplyGravitation != null) {
throw "assert failed";
}
this.allNodesToApplyGravitation = nodeList;
};
LGraphManager.prototype.getRoot = function() {
return this.rootGraph;
};
LGraphManager.prototype.setRootGraph = function(graph) {
if (graph.getGraphManager() != this) {
throw "Root not in this graph mgr!";
}
this.rootGraph = graph;
if (graph.parent == null) {
graph.parent = this.layout.newNode("Root node");
}
};
LGraphManager.prototype.getLayout = function() {
return this.layout;
};
LGraphManager.prototype.isOneAncestorOfOther = function(firstNode, secondNode) {
if (!(firstNode != null && secondNode != null)) {
throw "assert failed";
}
if (firstNode == secondNode) {
return true;
}
var ownerGraph = firstNode.getOwner();
var parentNode;
do {
parentNode = ownerGraph.getParent();
if (parentNode == null) {
break;
}
if (parentNode == secondNode) {
return true;
}
ownerGraph = parentNode.getOwner();
if (ownerGraph == null) {
break;
}
} while (true);
ownerGraph = secondNode.getOwner();
do {
parentNode = ownerGraph.getParent();
if (parentNode == null) {
break;
}
if (parentNode == firstNode) {
return true;
}
ownerGraph = parentNode.getOwner();
if (ownerGraph == null) {
break;
}
} while (true);
return false;
};
LGraphManager.prototype.calcLowestCommonAncestors = function() {
var edge;
var sourceNode;
var targetNode;
var sourceAncestorGraph;
var targetAncestorGraph;
var edges3 = this.getAllEdges();
var s2 = edges3.length;
for (var i2 = 0; i2 < s2; i2++) {
edge = edges3[i2];
sourceNode = edge.source;
targetNode = edge.target;
edge.lca = null;
edge.sourceInLca = sourceNode;
edge.targetInLca = targetNode;
if (sourceNode == targetNode) {
edge.lca = sourceNode.getOwner();
continue;
}
sourceAncestorGraph = sourceNode.getOwner();
while (edge.lca == null) {
edge.targetInLca = targetNode;
targetAncestorGraph = targetNode.getOwner();
while (edge.lca == null) {
if (targetAncestorGraph == sourceAncestorGraph) {
edge.lca = targetAncestorGraph;
break;
}
if (targetAncestorGraph == this.rootGraph) {
break;
}
if (edge.lca != null) {
throw "assert failed";
}
edge.targetInLca = targetAncestorGraph.getParent();
targetAncestorGraph = edge.targetInLca.getOwner();
}
if (sourceAncestorGraph == this.rootGraph) {
break;
}
if (edge.lca == null) {
edge.sourceInLca = sourceAncestorGraph.getParent();
sourceAncestorGraph = edge.sourceInLca.getOwner();
}
}
if (edge.lca == null) {
throw "assert failed";
}
}
};
LGraphManager.prototype.calcLowestCommonAncestor = function(firstNode, secondNode) {
if (firstNode == secondNode) {
return firstNode.getOwner();
}
var firstOwnerGraph = firstNode.getOwner();
do {
if (firstOwnerGraph == null) {
break;
}
var secondOwnerGraph = secondNode.getOwner();
do {
if (secondOwnerGraph == null) {
break;
}
if (secondOwnerGraph == firstOwnerGraph) {
return secondOwnerGraph;
}
secondOwnerGraph = secondOwnerGraph.getParent().getOwner();
} while (true);
firstOwnerGraph = firstOwnerGraph.getParent().getOwner();
} while (true);
return firstOwnerGraph;
};
LGraphManager.prototype.calcInclusionTreeDepths = function(graph, depth) {
if (graph == null && depth == null) {
graph = this.rootGraph;
depth = 1;
}
var node2;
var nodes5 = graph.getNodes();
var s2 = nodes5.length;
for (var i2 = 0; i2 < s2; i2++) {
node2 = nodes5[i2];
node2.inclusionTreeDepth = depth;
if (node2.child != null) {
this.calcInclusionTreeDepths(node2.child, depth + 1);
}
}
};
LGraphManager.prototype.includesInvalidEdge = function() {
var edge;
var edgesToRemove = [];
var s2 = this.edges.length;
for (var i2 = 0; i2 < s2; i2++) {
edge = this.edges[i2];
if (this.isOneAncestorOfOther(edge.source, edge.target)) {
edgesToRemove.push(edge);
}
}
for (var i2 = 0; i2 < edgesToRemove.length; i2++) {
this.remove(edgesToRemove[i2]);
}
return false;
};
module3.exports = LGraphManager;
}),
/* 8 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var Point3 = __webpack_require__(12);
function IGeometry() {
}
__name(IGeometry, "IGeometry");
IGeometry.calcSeparationAmount = function(rectA, rectB, overlapAmount, separationBuffer) {
if (!rectA.intersects(rectB)) {
throw "assert failed";
}
var directions = new Array(2);
this.decideDirectionsForOverlappingNodes(rectA, rectB, directions);
overlapAmount[0] = Math.min(rectA.getRight(), rectB.getRight()) - Math.max(rectA.x, rectB.x);
overlapAmount[1] = Math.min(rectA.getBottom(), rectB.getBottom()) - Math.max(rectA.y, rectB.y);
if (rectA.getX() <= rectB.getX() && rectA.getRight() >= rectB.getRight()) {
overlapAmount[0] += Math.min(rectB.getX() - rectA.getX(), rectA.getRight() - rectB.getRight());
} else if (rectB.getX() <= rectA.getX() && rectB.getRight() >= rectA.getRight()) {
overlapAmount[0] += Math.min(rectA.getX() - rectB.getX(), rectB.getRight() - rectA.getRight());
}
if (rectA.getY() <= rectB.getY() && rectA.getBottom() >= rectB.getBottom()) {
overlapAmount[1] += Math.min(rectB.getY() - rectA.getY(), rectA.getBottom() - rectB.getBottom());
} else if (rectB.getY() <= rectA.getY() && rectB.getBottom() >= rectA.getBottom()) {
overlapAmount[1] += Math.min(rectA.getY() - rectB.getY(), rectB.getBottom() - rectA.getBottom());
}
var slope = Math.abs((rectB.getCenterY() - rectA.getCenterY()) / (rectB.getCenterX() - rectA.getCenterX()));
if (rectB.getCenterY() === rectA.getCenterY() && rectB.getCenterX() === rectA.getCenterX()) {
slope = 1;
}
var moveByY = slope * overlapAmount[0];
var moveByX = overlapAmount[1] / slope;
if (overlapAmount[0] < moveByX) {
moveByX = overlapAmount[0];
} else {
moveByY = overlapAmount[1];
}
overlapAmount[0] = -1 * directions[0] * (moveByX / 2 + separationBuffer);
overlapAmount[1] = -1 * directions[1] * (moveByY / 2 + separationBuffer);
};
IGeometry.decideDirectionsForOverlappingNodes = function(rectA, rectB, directions) {
if (rectA.getCenterX() < rectB.getCenterX()) {
directions[0] = -1;
} else {
directions[0] = 1;
}
if (rectA.getCenterY() < rectB.getCenterY()) {
directions[1] = -1;
} else {
directions[1] = 1;
}
};
IGeometry.getIntersection2 = function(rectA, rectB, result) {
var p1x = rectA.getCenterX();
var p1y = rectA.getCenterY();
var p2x = rectB.getCenterX();
var p2y = rectB.getCenterY();
if (rectA.intersects(rectB)) {
result[0] = p1x;
result[1] = p1y;
result[2] = p2x;
result[3] = p2y;
return true;
}
var topLeftAx = rectA.getX();
var topLeftAy = rectA.getY();
var topRightAx = rectA.getRight();
var bottomLeftAx = rectA.getX();
var bottomLeftAy = rectA.getBottom();
var bottomRightAx = rectA.getRight();
var halfWidthA = rectA.getWidthHalf();
var halfHeightA = rectA.getHeightHalf();
var topLeftBx = rectB.getX();
var topLeftBy = rectB.getY();
var topRightBx = rectB.getRight();
var bottomLeftBx = rectB.getX();
var bottomLeftBy = rectB.getBottom();
var bottomRightBx = rectB.getRight();
var halfWidthB = rectB.getWidthHalf();
var halfHeightB = rectB.getHeightHalf();
var clipPointAFound = false;
var clipPointBFound = false;
if (p1x === p2x) {
if (p1y > p2y) {
result[0] = p1x;
result[1] = topLeftAy;
result[2] = p2x;
result[3] = bottomLeftBy;
return false;
} else if (p1y < p2y) {
result[0] = p1x;
result[1] = bottomLeftAy;
result[2] = p2x;
result[3] = topLeftBy;
return false;
} else {
}
} else if (p1y === p2y) {
if (p1x > p2x) {
result[0] = topLeftAx;
result[1] = p1y;
result[2] = topRightBx;
result[3] = p2y;
return false;
} else if (p1x < p2x) {
result[0] = topRightAx;
result[1] = p1y;
result[2] = topLeftBx;
result[3] = p2y;
return false;
} else {
}
} else {
var slopeA = rectA.height / rectA.width;
var slopeB = rectB.height / rectB.width;
var slopePrime = (p2y - p1y) / (p2x - p1x);
var cardinalDirectionA = void 0;
var cardinalDirectionB = void 0;
var tempPointAx = void 0;
var tempPointAy = void 0;
var tempPointBx = void 0;
var tempPointBy = void 0;
if (-slopeA === slopePrime) {
if (p1x > p2x) {
result[0] = bottomLeftAx;
result[1] = bottomLeftAy;
clipPointAFound = true;
} else {
result[0] = topRightAx;
result[1] = topLeftAy;
clipPointAFound = true;
}
} else if (slopeA === slopePrime) {
if (p1x > p2x) {
result[0] = topLeftAx;
result[1] = topLeftAy;
clipPointAFound = true;
} else {
result[0] = bottomRightAx;
result[1] = bottomLeftAy;
clipPointAFound = true;
}
}
if (-slopeB === slopePrime) {
if (p2x > p1x) {
result[2] = bottomLeftBx;
result[3] = bottomLeftBy;
clipPointBFound = true;
} else {
result[2] = topRightBx;
result[3] = topLeftBy;
clipPointBFound = true;
}
} else if (slopeB === slopePrime) {
if (p2x > p1x) {
result[2] = topLeftBx;
result[3] = topLeftBy;
clipPointBFound = true;
} else {
result[2] = bottomRightBx;
result[3] = bottomLeftBy;
clipPointBFound = true;
}
}
if (clipPointAFound && clipPointBFound) {
return false;
}
if (p1x > p2x) {
if (p1y > p2y) {
cardinalDirectionA = this.getCardinalDirection(slopeA, slopePrime, 4);
cardinalDirectionB = this.getCardinalDirection(slopeB, slopePrime, 2);
} else {
cardinalDirectionA = this.getCardinalDirection(-slopeA, slopePrime, 3);
cardinalDirectionB = this.getCardinalDirection(-slopeB, slopePrime, 1);
}
} else {
if (p1y > p2y) {
cardinalDirectionA = this.getCardinalDirection(-slopeA, slopePrime, 1);
cardinalDirectionB = this.getCardinalDirection(-slopeB, slopePrime, 3);
} else {
cardinalDirectionA = this.getCardinalDirection(slopeA, slopePrime, 2);
cardinalDirectionB = this.getCardinalDirection(slopeB, slopePrime, 4);
}
}
if (!clipPointAFound) {
switch (cardinalDirectionA) {
case 1:
tempPointAy = topLeftAy;
tempPointAx = p1x + -halfHeightA / slopePrime;
result[0] = tempPointAx;
result[1] = tempPointAy;
break;
case 2:
tempPointAx = bottomRightAx;
tempPointAy = p1y + halfWidthA * slopePrime;
result[0] = tempPointAx;
result[1] = tempPointAy;
break;
case 3:
tempPointAy = bottomLeftAy;
tempPointAx = p1x + halfHeightA / slopePrime;
result[0] = tempPointAx;
result[1] = tempPointAy;
break;
case 4:
tempPointAx = bottomLeftAx;
tempPointAy = p1y + -halfWidthA * slopePrime;
result[0] = tempPointAx;
result[1] = tempPointAy;
break;
}
}
if (!clipPointBFound) {
switch (cardinalDirectionB) {
case 1:
tempPointBy = topLeftBy;
tempPointBx = p2x + -halfHeightB / slopePrime;
result[2] = tempPointBx;
result[3] = tempPointBy;
break;
case 2:
tempPointBx = bottomRightBx;
tempPointBy = p2y + halfWidthB * slopePrime;
result[2] = tempPointBx;
result[3] = tempPointBy;
break;
case 3:
tempPointBy = bottomLeftBy;
tempPointBx = p2x + halfHeightB / slopePrime;
result[2] = tempPointBx;
result[3] = tempPointBy;
break;
case 4:
tempPointBx = bottomLeftBx;
tempPointBy = p2y + -halfWidthB * slopePrime;
result[2] = tempPointBx;
result[3] = tempPointBy;
break;
}
}
}
return false;
};
IGeometry.getCardinalDirection = function(slope, slopePrime, line2) {
if (slope > slopePrime) {
return line2;
} else {
return 1 + line2 % 4;
}
};
IGeometry.getIntersection = function(s1, s2, f1, f2) {
if (f2 == null) {
return this.getIntersection2(s1, s2, f1);
}
var x1 = s1.x;
var y1 = s1.y;
var x22 = s2.x;
var y22 = s2.y;
var x32 = f1.x;
var y32 = f1.y;
var x42 = f2.x;
var y42 = f2.y;
var x5 = void 0, y6 = void 0;
var a1 = void 0, a2 = void 0, b1 = void 0, b22 = void 0, c1 = void 0, c22 = void 0;
var denom = void 0;
a1 = y22 - y1;
b1 = x1 - x22;
c1 = x22 * y1 - x1 * y22;
a2 = y42 - y32;
b22 = x32 - x42;
c22 = x42 * y32 - x32 * y42;
denom = a1 * b22 - a2 * b1;
if (denom === 0) {
return null;
}
x5 = (b1 * c22 - b22 * c1) / denom;
y6 = (a2 * c1 - a1 * c22) / denom;
return new Point3(x5, y6);
};
IGeometry.angleOfVector = function(Cx, Cy, Nx, Ny) {
var C_angle = void 0;
if (Cx !== Nx) {
C_angle = Math.atan((Ny - Cy) / (Nx - Cx));
if (Nx < Cx) {
C_angle += Math.PI;
} else if (Ny < Cy) {
C_angle += this.TWO_PI;
}
} else if (Ny < Cy) {
C_angle = this.ONE_AND_HALF_PI;
} else {
C_angle = this.HALF_PI;
}
return C_angle;
};
IGeometry.doIntersect = function(p1, p22, p3, p4) {
var a2 = p1.x;
var b3 = p1.y;
var c3 = p22.x;
var d3 = p22.y;
var p5 = p3.x;
var q3 = p3.y;
var r2 = p4.x;
var s2 = p4.y;
var det = (c3 - a2) * (s2 - q3) - (r2 - p5) * (d3 - b3);
if (det === 0) {
return false;
} else {
var lambda = ((s2 - q3) * (r2 - a2) + (p5 - r2) * (s2 - b3)) / det;
var gamma2 = ((b3 - d3) * (r2 - a2) + (c3 - a2) * (s2 - b3)) / det;
return 0 < lambda && lambda < 1 && 0 < gamma2 && gamma2 < 1;
}
};
IGeometry.findCircleLineIntersections = function(Ex, Ey, Lx, Ly, Cx, Cy, r2) {
var a2 = (Lx - Ex) * (Lx - Ex) + (Ly - Ey) * (Ly - Ey);
var b3 = 2 * ((Ex - Cx) * (Lx - Ex) + (Ey - Cy) * (Ly - Ey));
var c3 = (Ex - Cx) * (Ex - Cx) + (Ey - Cy) * (Ey - Cy) - r2 * r2;
var disc = b3 * b3 - 4 * a2 * c3;
if (disc >= 0) {
var t13 = (-b3 + Math.sqrt(b3 * b3 - 4 * a2 * c3)) / (2 * a2);
var t22 = (-b3 - Math.sqrt(b3 * b3 - 4 * a2 * c3)) / (2 * a2);
var intersections = null;
if (t13 >= 0 && t13 <= 1) {
return [t13];
}
if (t22 >= 0 && t22 <= 1) {
return [t22];
}
return intersections;
} else return null;
};
IGeometry.HALF_PI = 0.5 * Math.PI;
IGeometry.ONE_AND_HALF_PI = 1.5 * Math.PI;
IGeometry.TWO_PI = 2 * Math.PI;
IGeometry.THREE_PI = 3 * Math.PI;
module3.exports = IGeometry;
}),
/* 9 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function IMath() {
}
__name(IMath, "IMath");
IMath.sign = function(value2) {
if (value2 > 0) {
return 1;
} else if (value2 < 0) {
return -1;
} else {
return 0;
}
};
IMath.floor = function(value2) {
return value2 < 0 ? Math.ceil(value2) : Math.floor(value2);
};
IMath.ceil = function(value2) {
return value2 < 0 ? Math.floor(value2) : Math.ceil(value2);
};
module3.exports = IMath;
}),
/* 10 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function Integer() {
}
__name(Integer, "Integer");
Integer.MAX_VALUE = 2147483647;
Integer.MIN_VALUE = -2147483648;
module3.exports = Integer;
}),
/* 11 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var _createClass2 = /* @__PURE__ */ (function() {
function defineProperties(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
__name(defineProperties, "defineProperties");
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
function _classCallCheck2(instance2, Constructor) {
if (!(instance2 instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
__name(_classCallCheck2, "_classCallCheck");
var nodeFrom = /* @__PURE__ */ __name(function nodeFrom2(value2) {
return { value: value2, next: null, prev: null };
}, "nodeFrom");
var add3 = /* @__PURE__ */ __name(function add4(prev2, node2, next3, list) {
if (prev2 !== null) {
prev2.next = node2;
} else {
list.head = node2;
}
if (next3 !== null) {
next3.prev = node2;
} else {
list.tail = node2;
}
node2.prev = prev2;
node2.next = next3;
list.length++;
return node2;
}, "add");
var _remove = /* @__PURE__ */ __name(function _remove2(node2, list) {
var prev2 = node2.prev, next3 = node2.next;
if (prev2 !== null) {
prev2.next = next3;
} else {
list.head = next3;
}
if (next3 !== null) {
next3.prev = prev2;
} else {
list.tail = prev2;
}
node2.prev = node2.next = null;
list.length--;
return node2;
}, "_remove");
var LinkedList = (function() {
function LinkedList2(vals) {
var _this = this;
_classCallCheck2(this, LinkedList2);
this.length = 0;
this.head = null;
this.tail = null;
if (vals != null) {
vals.forEach(function(v3) {
return _this.push(v3);
});
}
}
__name(LinkedList2, "LinkedList");
_createClass2(LinkedList2, [{
key: "size",
value: /* @__PURE__ */ __name(function size4() {
return this.length;
}, "size")
}, {
key: "insertBefore",
value: /* @__PURE__ */ __name(function insertBefore(val, otherNode) {
return add3(otherNode.prev, nodeFrom(val), otherNode, this);
}, "insertBefore")
}, {
key: "insertAfter",
value: /* @__PURE__ */ __name(function insertAfter(val, otherNode) {
return add3(otherNode, nodeFrom(val), otherNode.next, this);
}, "insertAfter")
}, {
key: "insertNodeBefore",
value: /* @__PURE__ */ __name(function insertNodeBefore(newNode, otherNode) {
return add3(otherNode.prev, newNode, otherNode, this);
}, "insertNodeBefore")
}, {
key: "insertNodeAfter",
value: /* @__PURE__ */ __name(function insertNodeAfter(newNode, otherNode) {
return add3(otherNode, newNode, otherNode.next, this);
}, "insertNodeAfter")
}, {
key: "push",
value: /* @__PURE__ */ __name(function push3(val) {
return add3(this.tail, nodeFrom(val), null, this);
}, "push")
}, {
key: "unshift",
value: /* @__PURE__ */ __name(function unshift(val) {
return add3(null, nodeFrom(val), this.head, this);
}, "unshift")
}, {
key: "remove",
value: /* @__PURE__ */ __name(function remove3(node2) {
return _remove(node2, this);
}, "remove")
}, {
key: "pop",
value: /* @__PURE__ */ __name(function pop() {
return _remove(this.tail, this).value;
}, "pop")
}, {
key: "popNode",
value: /* @__PURE__ */ __name(function popNode() {
return _remove(this.tail, this);
}, "popNode")
}, {
key: "shift",
value: /* @__PURE__ */ __name(function shift2() {
return _remove(this.head, this).value;
}, "shift")
}, {
key: "shiftNode",
value: /* @__PURE__ */ __name(function shiftNode() {
return _remove(this.head, this);
}, "shiftNode")
}, {
key: "get_object_at",
value: /* @__PURE__ */ __name(function get_object_at(index) {
if (index <= this.length()) {
var i2 = 1;
var current = this.head;
while (i2 < index) {
current = current.next;
i2++;
}
return current.value;
}
}, "get_object_at")
}, {
key: "set_object_at",
value: /* @__PURE__ */ __name(function set_object_at(index, value2) {
if (index <= this.length()) {
var i2 = 1;
var current = this.head;
while (i2 < index) {
current = current.next;
i2++;
}
current.value = value2;
}
}, "set_object_at")
}]);
return LinkedList2;
})();
module3.exports = LinkedList;
}),
/* 12 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function Point3(x5, y6, p3) {
this.x = null;
this.y = null;
if (x5 == null && y6 == null && p3 == null) {
this.x = 0;
this.y = 0;
} else if (typeof x5 == "number" && typeof y6 == "number" && p3 == null) {
this.x = x5;
this.y = y6;
} else if (x5.constructor.name == "Point" && y6 == null && p3 == null) {
p3 = x5;
this.x = p3.x;
this.y = p3.y;
}
}
__name(Point3, "Point");
Point3.prototype.getX = function() {
return this.x;
};
Point3.prototype.getY = function() {
return this.y;
};
Point3.prototype.getLocation = function() {
return new Point3(this.x, this.y);
};
Point3.prototype.setLocation = function(x5, y6, p3) {
if (x5.constructor.name == "Point" && y6 == null && p3 == null) {
p3 = x5;
this.setLocation(p3.x, p3.y);
} else if (typeof x5 == "number" && typeof y6 == "number" && p3 == null) {
if (parseInt(x5) == x5 && parseInt(y6) == y6) {
this.move(x5, y6);
} else {
this.x = Math.floor(x5 + 0.5);
this.y = Math.floor(y6 + 0.5);
}
}
};
Point3.prototype.move = function(x5, y6) {
this.x = x5;
this.y = y6;
};
Point3.prototype.translate = function(dx, dy) {
this.x += dx;
this.y += dy;
};
Point3.prototype.equals = function(obj) {
if (obj.constructor.name == "Point") {
var pt = obj;
return this.x == pt.x && this.y == pt.y;
}
return this == obj;
};
Point3.prototype.toString = function() {
return new Point3().constructor.name + "[x=" + this.x + ",y=" + this.y + "]";
};
module3.exports = Point3;
}),
/* 13 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function RectangleD(x5, y6, width3, height2) {
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
if (x5 != null && y6 != null && width3 != null && height2 != null) {
this.x = x5;
this.y = y6;
this.width = width3;
this.height = height2;
}
}
__name(RectangleD, "RectangleD");
RectangleD.prototype.getX = function() {
return this.x;
};
RectangleD.prototype.setX = function(x5) {
this.x = x5;
};
RectangleD.prototype.getY = function() {
return this.y;
};
RectangleD.prototype.setY = function(y6) {
this.y = y6;
};
RectangleD.prototype.getWidth = function() {
return this.width;
};
RectangleD.prototype.setWidth = function(width3) {
this.width = width3;
};
RectangleD.prototype.getHeight = function() {
return this.height;
};
RectangleD.prototype.setHeight = function(height2) {
this.height = height2;
};
RectangleD.prototype.getRight = function() {
return this.x + this.width;
};
RectangleD.prototype.getBottom = function() {
return this.y + this.height;
};
RectangleD.prototype.intersects = function(a2) {
if (this.getRight() < a2.x) {
return false;
}
if (this.getBottom() < a2.y) {
return false;
}
if (a2.getRight() < this.x) {
return false;
}
if (a2.getBottom() < this.y) {
return false;
}
return true;
};
RectangleD.prototype.getCenterX = function() {
return this.x + this.width / 2;
};
RectangleD.prototype.getMinX = function() {
return this.getX();
};
RectangleD.prototype.getMaxX = function() {
return this.getX() + this.width;
};
RectangleD.prototype.getCenterY = function() {
return this.y + this.height / 2;
};
RectangleD.prototype.getMinY = function() {
return this.getY();
};
RectangleD.prototype.getMaxY = function() {
return this.getY() + this.height;
};
RectangleD.prototype.getWidthHalf = function() {
return this.width / 2;
};
RectangleD.prototype.getHeightHalf = function() {
return this.height / 2;
};
module3.exports = RectangleD;
}),
/* 14 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
function UniqueIDGeneretor() {
}
__name(UniqueIDGeneretor, "UniqueIDGeneretor");
UniqueIDGeneretor.lastID = 0;
UniqueIDGeneretor.createID = function(obj) {
if (UniqueIDGeneretor.isPrimitive(obj)) {
return obj;
}
if (obj.uniqueID != null) {
return obj.uniqueID;
}
obj.uniqueID = UniqueIDGeneretor.getString();
UniqueIDGeneretor.lastID++;
return obj.uniqueID;
};
UniqueIDGeneretor.getString = function(id32) {
if (id32 == null) id32 = UniqueIDGeneretor.lastID;
return "Object#" + id32;
};
UniqueIDGeneretor.isPrimitive = function(arg) {
var type3 = typeof arg === "undefined" ? "undefined" : _typeof2(arg);
return arg == null || type3 != "object" && type3 != "function";
};
module3.exports = UniqueIDGeneretor;
}),
/* 15 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function _toConsumableArray2(arr) {
if (Array.isArray(arr)) {
for (var i2 = 0, arr2 = Array(arr.length); i2 < arr.length; i2++) {
arr2[i2] = arr[i2];
}
return arr2;
} else {
return Array.from(arr);
}
}
__name(_toConsumableArray2, "_toConsumableArray");
var LayoutConstants = __webpack_require__(0);
var LGraphManager = __webpack_require__(7);
var LNode = __webpack_require__(3);
var LEdge = __webpack_require__(1);
var LGraph = __webpack_require__(6);
var PointD = __webpack_require__(5);
var Transform2 = __webpack_require__(17);
var Emitter4 = __webpack_require__(29);
function Layout2(isRemoteUse) {
Emitter4.call(this);
this.layoutQuality = LayoutConstants.QUALITY;
this.createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;
this.incremental = LayoutConstants.DEFAULT_INCREMENTAL;
this.animationOnLayout = LayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT;
this.animationDuringLayout = LayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT;
this.animationPeriod = LayoutConstants.DEFAULT_ANIMATION_PERIOD;
this.uniformLeafNodeSizes = LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES;
this.edgeToDummyNodes = /* @__PURE__ */ new Map();
this.graphManager = new LGraphManager(this);
this.isLayoutFinished = false;
this.isSubLayout = false;
this.isRemoteUse = false;
if (isRemoteUse != null) {
this.isRemoteUse = isRemoteUse;
}
}
__name(Layout2, "Layout");
Layout2.RANDOM_SEED = 1;
Layout2.prototype = Object.create(Emitter4.prototype);
Layout2.prototype.getGraphManager = function() {
return this.graphManager;
};
Layout2.prototype.getAllNodes = function() {
return this.graphManager.getAllNodes();
};
Layout2.prototype.getAllEdges = function() {
return this.graphManager.getAllEdges();
};
Layout2.prototype.getAllNodesToApplyGravitation = function() {
return this.graphManager.getAllNodesToApplyGravitation();
};
Layout2.prototype.newGraphManager = function() {
var gm = new LGraphManager(this);
this.graphManager = gm;
return gm;
};
Layout2.prototype.newGraph = function(vGraph) {
return new LGraph(null, this.graphManager, vGraph);
};
Layout2.prototype.newNode = function(vNode) {
return new LNode(this.graphManager, vNode);
};
Layout2.prototype.newEdge = function(vEdge) {
return new LEdge(null, null, vEdge);
};
Layout2.prototype.checkLayoutSuccess = function() {
return this.graphManager.getRoot() == null || this.graphManager.getRoot().getNodes().length == 0 || this.graphManager.includesInvalidEdge();
};
Layout2.prototype.runLayout = function() {
this.isLayoutFinished = false;
if (this.tilingPreLayout) {
this.tilingPreLayout();
}
this.initParameters();
var isLayoutSuccessfull;
if (this.checkLayoutSuccess()) {
isLayoutSuccessfull = false;
} else {
isLayoutSuccessfull = this.layout();
}
if (LayoutConstants.ANIMATE === "during") {
return false;
}
if (isLayoutSuccessfull) {
if (!this.isSubLayout) {
this.doPostLayout();
}
}
if (this.tilingPostLayout) {
this.tilingPostLayout();
}
this.isLayoutFinished = true;
return isLayoutSuccessfull;
};
Layout2.prototype.doPostLayout = function() {
if (!this.incremental) {
this.transform();
}
this.update();
};
Layout2.prototype.update2 = function() {
if (this.createBendsAsNeeded) {
this.createBendpointsFromDummyNodes();
this.graphManager.resetAllEdges();
}
if (!this.isRemoteUse) {
var edge;
var allEdges = this.graphManager.getAllEdges();
for (var i2 = 0; i2 < allEdges.length; i2++) {
edge = allEdges[i2];
}
var node2;
var nodes5 = this.graphManager.getRoot().getNodes();
for (var i2 = 0; i2 < nodes5.length; i2++) {
node2 = nodes5[i2];
}
this.update(this.graphManager.getRoot());
}
};
Layout2.prototype.update = function(obj) {
if (obj == null) {
this.update2();
} else if (obj instanceof LNode) {
var node2 = obj;
if (node2.getChild() != null) {
var nodes5 = node2.getChild().getNodes();
for (var i2 = 0; i2 < nodes5.length; i2++) {
update(nodes5[i2]);
}
}
if (node2.vGraphObject != null) {
var vNode = node2.vGraphObject;
vNode.update(node2);
}
} else if (obj instanceof LEdge) {
var edge = obj;
if (edge.vGraphObject != null) {
var vEdge = edge.vGraphObject;
vEdge.update(edge);
}
} else if (obj instanceof LGraph) {
var graph = obj;
if (graph.vGraphObject != null) {
var vGraph = graph.vGraphObject;
vGraph.update(graph);
}
}
};
Layout2.prototype.initParameters = function() {
if (!this.isSubLayout) {
this.layoutQuality = LayoutConstants.QUALITY;
this.animationDuringLayout = LayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT;
this.animationPeriod = LayoutConstants.DEFAULT_ANIMATION_PERIOD;
this.animationOnLayout = LayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT;
this.incremental = LayoutConstants.DEFAULT_INCREMENTAL;
this.createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;
this.uniformLeafNodeSizes = LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES;
}
if (this.animationDuringLayout) {
this.animationOnLayout = false;
}
};
Layout2.prototype.transform = function(newLeftTop) {
if (newLeftTop == void 0) {
this.transform(new PointD(0, 0));
} else {
var trans = new Transform2();
var leftTop = this.graphManager.getRoot().updateLeftTop();
if (leftTop != null) {
trans.setWorldOrgX(newLeftTop.x);
trans.setWorldOrgY(newLeftTop.y);
trans.setDeviceOrgX(leftTop.x);
trans.setDeviceOrgY(leftTop.y);
var nodes5 = this.getAllNodes();
var node2;
for (var i2 = 0; i2 < nodes5.length; i2++) {
node2 = nodes5[i2];
node2.transform(trans);
}
}
}
};
Layout2.prototype.positionNodesRandomly = function(graph) {
if (graph == void 0) {
this.positionNodesRandomly(this.getGraphManager().getRoot());
this.getGraphManager().getRoot().updateBounds(true);
} else {
var lNode;
var childGraph;
var nodes5 = graph.getNodes();
for (var i2 = 0; i2 < nodes5.length; i2++) {
lNode = nodes5[i2];
childGraph = lNode.getChild();
if (childGraph == null) {
lNode.scatter();
} else if (childGraph.getNodes().length == 0) {
lNode.scatter();
} else {
this.positionNodesRandomly(childGraph);
lNode.updateBounds();
}
}
}
};
Layout2.prototype.getFlatForest = function() {
var flatForest = [];
var isForest = true;
var allNodes = this.graphManager.getRoot().getNodes();
var isFlat = true;
for (var i2 = 0; i2 < allNodes.length; i2++) {
if (allNodes[i2].getChild() != null) {
isFlat = false;
}
}
if (!isFlat) {
return flatForest;
}
var visited = /* @__PURE__ */ new Set();
var toBeVisited = [];
var parents3 = /* @__PURE__ */ new Map();
var unProcessedNodes = [];
unProcessedNodes = unProcessedNodes.concat(allNodes);
while (unProcessedNodes.length > 0 && isForest) {
toBeVisited.push(unProcessedNodes[0]);
while (toBeVisited.length > 0 && isForest) {
var currentNode = toBeVisited[0];
toBeVisited.splice(0, 1);
visited.add(currentNode);
var neighborEdges = currentNode.getEdges();
for (var i2 = 0; i2 < neighborEdges.length; i2++) {
var currentNeighbor = neighborEdges[i2].getOtherEnd(currentNode);
if (parents3.get(currentNode) != currentNeighbor) {
if (!visited.has(currentNeighbor)) {
toBeVisited.push(currentNeighbor);
parents3.set(currentNeighbor, currentNode);
} else {
isForest = false;
break;
}
}
}
}
if (!isForest) {
flatForest = [];
} else {
var temp = [].concat(_toConsumableArray2(visited));
flatForest.push(temp);
for (var i2 = 0; i2 < temp.length; i2++) {
var value2 = temp[i2];
var index = unProcessedNodes.indexOf(value2);
if (index > -1) {
unProcessedNodes.splice(index, 1);
}
}
visited = /* @__PURE__ */ new Set();
parents3 = /* @__PURE__ */ new Map();
}
}
return flatForest;
};
Layout2.prototype.createDummyNodesForBendpoints = function(edge) {
var dummyNodes = [];
var prev2 = edge.source;
var graph = this.graphManager.calcLowestCommonAncestor(edge.source, edge.target);
for (var i2 = 0; i2 < edge.bendpoints.length; i2++) {
var dummyNode = this.newNode(null);
dummyNode.setRect(new Point(0, 0), new Dimension(1, 1));
graph.add(dummyNode);
var dummyEdge = this.newEdge(null);
this.graphManager.add(dummyEdge, prev2, dummyNode);
dummyNodes.add(dummyNode);
prev2 = dummyNode;
}
var dummyEdge = this.newEdge(null);
this.graphManager.add(dummyEdge, prev2, edge.target);
this.edgeToDummyNodes.set(edge, dummyNodes);
if (edge.isInterGraph()) {
this.graphManager.remove(edge);
} else {
graph.remove(edge);
}
return dummyNodes;
};
Layout2.prototype.createBendpointsFromDummyNodes = function() {
var edges3 = [];
edges3 = edges3.concat(this.graphManager.getAllEdges());
edges3 = [].concat(_toConsumableArray2(this.edgeToDummyNodes.keys())).concat(edges3);
for (var k2 = 0; k2 < edges3.length; k2++) {
var lEdge = edges3[k2];
if (lEdge.bendpoints.length > 0) {
var path4 = this.edgeToDummyNodes.get(lEdge);
for (var i2 = 0; i2 < path4.length; i2++) {
var dummyNode = path4[i2];
var p3 = new PointD(dummyNode.getCenterX(), dummyNode.getCenterY());
var ebp = lEdge.bendpoints.get(i2);
ebp.x = p3.x;
ebp.y = p3.y;
dummyNode.getOwner().remove(dummyNode);
}
this.graphManager.add(lEdge, lEdge.source, lEdge.target);
}
}
};
Layout2.transform = function(sliderValue, defaultValue, minDiv, maxMul) {
if (minDiv != void 0 && maxMul != void 0) {
var value2 = defaultValue;
if (sliderValue <= 50) {
var minValue = defaultValue / minDiv;
value2 -= (defaultValue - minValue) / 50 * (50 - sliderValue);
} else {
var maxValue = defaultValue * maxMul;
value2 += (maxValue - defaultValue) / 50 * (sliderValue - 50);
}
return value2;
} else {
var a2, b3;
if (sliderValue <= 50) {
a2 = 9 * defaultValue / 500;
b3 = defaultValue / 10;
} else {
a2 = 9 * defaultValue / 50;
b3 = -8 * defaultValue;
}
return a2 * sliderValue + b3;
}
};
Layout2.findCenterOfTree = function(nodes5) {
var list = [];
list = list.concat(nodes5);
var removedNodes = [];
var remainingDegrees = /* @__PURE__ */ new Map();
var foundCenter = false;
var centerNode = null;
if (list.length == 1 || list.length == 2) {
foundCenter = true;
centerNode = list[0];
}
for (var i2 = 0; i2 < list.length; i2++) {
var node2 = list[i2];
var degree = node2.getNeighborsList().size;
remainingDegrees.set(node2, node2.getNeighborsList().size);
if (degree == 1) {
removedNodes.push(node2);
}
}
var tempList = [];
tempList = tempList.concat(removedNodes);
while (!foundCenter) {
var tempList2 = [];
tempList2 = tempList2.concat(tempList);
tempList = [];
for (var i2 = 0; i2 < list.length; i2++) {
var node2 = list[i2];
var index = list.indexOf(node2);
if (index >= 0) {
list.splice(index, 1);
}
var neighbours = node2.getNeighborsList();
neighbours.forEach(function(neighbour) {
if (removedNodes.indexOf(neighbour) < 0) {
var otherDegree = remainingDegrees.get(neighbour);
var newDegree = otherDegree - 1;
if (newDegree == 1) {
tempList.push(neighbour);
}
remainingDegrees.set(neighbour, newDegree);
}
});
}
removedNodes = removedNodes.concat(tempList);
if (list.length == 1 || list.length == 2) {
foundCenter = true;
centerNode = list[0];
}
}
return centerNode;
};
Layout2.prototype.setGraphManager = function(gm) {
this.graphManager = gm;
};
module3.exports = Layout2;
}),
/* 16 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function RandomSeed() {
}
__name(RandomSeed, "RandomSeed");
RandomSeed.seed = 1;
RandomSeed.x = 0;
RandomSeed.nextDouble = function() {
RandomSeed.x = Math.sin(RandomSeed.seed++) * 1e4;
return RandomSeed.x - Math.floor(RandomSeed.x);
};
module3.exports = RandomSeed;
}),
/* 17 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var PointD = __webpack_require__(5);
function Transform2(x5, y6) {
this.lworldOrgX = 0;
this.lworldOrgY = 0;
this.ldeviceOrgX = 0;
this.ldeviceOrgY = 0;
this.lworldExtX = 1;
this.lworldExtY = 1;
this.ldeviceExtX = 1;
this.ldeviceExtY = 1;
}
__name(Transform2, "Transform");
Transform2.prototype.getWorldOrgX = function() {
return this.lworldOrgX;
};
Transform2.prototype.setWorldOrgX = function(wox) {
this.lworldOrgX = wox;
};
Transform2.prototype.getWorldOrgY = function() {
return this.lworldOrgY;
};
Transform2.prototype.setWorldOrgY = function(woy) {
this.lworldOrgY = woy;
};
Transform2.prototype.getWorldExtX = function() {
return this.lworldExtX;
};
Transform2.prototype.setWorldExtX = function(wex) {
this.lworldExtX = wex;
};
Transform2.prototype.getWorldExtY = function() {
return this.lworldExtY;
};
Transform2.prototype.setWorldExtY = function(wey) {
this.lworldExtY = wey;
};
Transform2.prototype.getDeviceOrgX = function() {
return this.ldeviceOrgX;
};
Transform2.prototype.setDeviceOrgX = function(dox) {
this.ldeviceOrgX = dox;
};
Transform2.prototype.getDeviceOrgY = function() {
return this.ldeviceOrgY;
};
Transform2.prototype.setDeviceOrgY = function(doy) {
this.ldeviceOrgY = doy;
};
Transform2.prototype.getDeviceExtX = function() {
return this.ldeviceExtX;
};
Transform2.prototype.setDeviceExtX = function(dex) {
this.ldeviceExtX = dex;
};
Transform2.prototype.getDeviceExtY = function() {
return this.ldeviceExtY;
};
Transform2.prototype.setDeviceExtY = function(dey) {
this.ldeviceExtY = dey;
};
Transform2.prototype.transformX = function(x5) {
var xDevice = 0;
var worldExtX = this.lworldExtX;
if (worldExtX != 0) {
xDevice = this.ldeviceOrgX + (x5 - this.lworldOrgX) * this.ldeviceExtX / worldExtX;
}
return xDevice;
};
Transform2.prototype.transformY = function(y6) {
var yDevice = 0;
var worldExtY = this.lworldExtY;
if (worldExtY != 0) {
yDevice = this.ldeviceOrgY + (y6 - this.lworldOrgY) * this.ldeviceExtY / worldExtY;
}
return yDevice;
};
Transform2.prototype.inverseTransformX = function(x5) {
var xWorld = 0;
var deviceExtX = this.ldeviceExtX;
if (deviceExtX != 0) {
xWorld = this.lworldOrgX + (x5 - this.ldeviceOrgX) * this.lworldExtX / deviceExtX;
}
return xWorld;
};
Transform2.prototype.inverseTransformY = function(y6) {
var yWorld = 0;
var deviceExtY = this.ldeviceExtY;
if (deviceExtY != 0) {
yWorld = this.lworldOrgY + (y6 - this.ldeviceOrgY) * this.lworldExtY / deviceExtY;
}
return yWorld;
};
Transform2.prototype.inverseTransformPoint = function(inPoint) {
var outPoint = new PointD(this.inverseTransformX(inPoint.x), this.inverseTransformY(inPoint.y));
return outPoint;
};
module3.exports = Transform2;
}),
/* 18 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function _toConsumableArray2(arr) {
if (Array.isArray(arr)) {
for (var i2 = 0, arr2 = Array(arr.length); i2 < arr.length; i2++) {
arr2[i2] = arr[i2];
}
return arr2;
} else {
return Array.from(arr);
}
}
__name(_toConsumableArray2, "_toConsumableArray");
var Layout2 = __webpack_require__(15);
var FDLayoutConstants = __webpack_require__(4);
var LayoutConstants = __webpack_require__(0);
var IGeometry = __webpack_require__(8);
var IMath = __webpack_require__(9);
function FDLayout() {
Layout2.call(this);
this.useSmartIdealEdgeLengthCalculation = FDLayoutConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION;
this.gravityConstant = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH;
this.compoundGravityConstant = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH;
this.gravityRangeFactor = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR;
this.compoundGravityRangeFactor = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR;
this.displacementThresholdPerNode = 3 * FDLayoutConstants.DEFAULT_EDGE_LENGTH / 100;
this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;
this.initialCoolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;
this.totalDisplacement = 0;
this.oldTotalDisplacement = 0;
this.maxIterations = FDLayoutConstants.MAX_ITERATIONS;
}
__name(FDLayout, "FDLayout");
FDLayout.prototype = Object.create(Layout2.prototype);
for (var prop in Layout2) {
FDLayout[prop] = Layout2[prop];
}
FDLayout.prototype.initParameters = function() {
Layout2.prototype.initParameters.call(this, arguments);
this.totalIterations = 0;
this.notAnimatedIterations = 0;
this.useFRGridVariant = FDLayoutConstants.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION;
this.grid = [];
};
FDLayout.prototype.calcIdealEdgeLengths = function() {
var edge;
var originalIdealLength;
var lcaDepth;
var source;
var target;
var sizeOfSourceInLca;
var sizeOfTargetInLca;
var allEdges = this.getGraphManager().getAllEdges();
for (var i2 = 0; i2 < allEdges.length; i2++) {
edge = allEdges[i2];
originalIdealLength = edge.idealLength;
if (edge.isInterGraph) {
source = edge.getSource();
target = edge.getTarget();
sizeOfSourceInLca = edge.getSourceInLca().getEstimatedSize();
sizeOfTargetInLca = edge.getTargetInLca().getEstimatedSize();
if (this.useSmartIdealEdgeLengthCalculation) {
edge.idealLength += sizeOfSourceInLca + sizeOfTargetInLca - 2 * LayoutConstants.SIMPLE_NODE_SIZE;
}
lcaDepth = edge.getLca().getInclusionTreeDepth();
edge.idealLength += originalIdealLength * FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR * (source.getInclusionTreeDepth() + target.getInclusionTreeDepth() - 2 * lcaDepth);
}
}
};
FDLayout.prototype.initSpringEmbedder = function() {
var s2 = this.getAllNodes().length;
if (this.incremental) {
if (s2 > FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) {
this.coolingFactor = Math.max(this.coolingFactor * FDLayoutConstants.COOLING_ADAPTATION_FACTOR, this.coolingFactor - (s2 - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) / (FDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) * this.coolingFactor * (1 - FDLayoutConstants.COOLING_ADAPTATION_FACTOR));
}
this.maxNodeDisplacement = FDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL;
} else {
if (s2 > FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) {
this.coolingFactor = Math.max(FDLayoutConstants.COOLING_ADAPTATION_FACTOR, 1 - (s2 - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) / (FDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) * (1 - FDLayoutConstants.COOLING_ADAPTATION_FACTOR));
} else {
this.coolingFactor = 1;
}
this.initialCoolingFactor = this.coolingFactor;
this.maxNodeDisplacement = FDLayoutConstants.MAX_NODE_DISPLACEMENT;
}
this.maxIterations = Math.max(this.getAllNodes().length * 5, this.maxIterations);
this.displacementThresholdPerNode = 3 * FDLayoutConstants.DEFAULT_EDGE_LENGTH / 100;
this.totalDisplacementThreshold = this.displacementThresholdPerNode * this.getAllNodes().length;
this.repulsionRange = this.calcRepulsionRange();
};
FDLayout.prototype.calcSpringForces = function() {
var lEdges = this.getAllEdges();
var edge;
for (var i2 = 0; i2 < lEdges.length; i2++) {
edge = lEdges[i2];
this.calcSpringForce(edge, edge.idealLength);
}
};
FDLayout.prototype.calcRepulsionForces = function() {
var gridUpdateAllowed = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
var forceToNodeSurroundingUpdate = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
var i2, j3;
var nodeA, nodeB;
var lNodes = this.getAllNodes();
var processedNodeSet;
if (this.useFRGridVariant) {
if (this.totalIterations % FDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD == 1 && gridUpdateAllowed) {
this.updateGrid();
}
processedNodeSet = /* @__PURE__ */ new Set();
for (i2 = 0; i2 < lNodes.length; i2++) {
nodeA = lNodes[i2];
this.calculateRepulsionForceOfANode(nodeA, processedNodeSet, gridUpdateAllowed, forceToNodeSurroundingUpdate);
processedNodeSet.add(nodeA);
}
} else {
for (i2 = 0; i2 < lNodes.length; i2++) {
nodeA = lNodes[i2];
for (j3 = i2 + 1; j3 < lNodes.length; j3++) {
nodeB = lNodes[j3];
if (nodeA.getOwner() != nodeB.getOwner()) {
continue;
}
this.calcRepulsionForce(nodeA, nodeB);
}
}
}
};
FDLayout.prototype.calcGravitationalForces = function() {
var node2;
var lNodes = this.getAllNodesToApplyGravitation();
for (var i2 = 0; i2 < lNodes.length; i2++) {
node2 = lNodes[i2];
this.calcGravitationalForce(node2);
}
};
FDLayout.prototype.moveNodes = function() {
var lNodes = this.getAllNodes();
var node2;
for (var i2 = 0; i2 < lNodes.length; i2++) {
node2 = lNodes[i2];
node2.move();
}
};
FDLayout.prototype.calcSpringForce = function(edge, idealLength) {
var sourceNode = edge.getSource();
var targetNode = edge.getTarget();
var length2;
var springForce;
var springForceX;
var springForceY;
if (this.uniformLeafNodeSizes && sourceNode.getChild() == null && targetNode.getChild() == null) {
edge.updateLengthSimple();
} else {
edge.updateLength();
if (edge.isOverlapingSourceAndTarget) {
return;
}
}
length2 = edge.getLength();
if (length2 == 0) return;
springForce = edge.edgeElasticity * (length2 - idealLength);
springForceX = springForce * (edge.lengthX / length2);
springForceY = springForce * (edge.lengthY / length2);
sourceNode.springForceX += springForceX;
sourceNode.springForceY += springForceY;
targetNode.springForceX -= springForceX;
targetNode.springForceY -= springForceY;
};
FDLayout.prototype.calcRepulsionForce = function(nodeA, nodeB) {
var rectA = nodeA.getRect();
var rectB = nodeB.getRect();
var overlapAmount = new Array(2);
var clipPoints = new Array(4);
var distanceX;
var distanceY;
var distanceSquared;
var distance3;
var repulsionForce;
var repulsionForceX;
var repulsionForceY;
if (rectA.intersects(rectB)) {
IGeometry.calcSeparationAmount(rectA, rectB, overlapAmount, FDLayoutConstants.DEFAULT_EDGE_LENGTH / 2);
repulsionForceX = 2 * overlapAmount[0];
repulsionForceY = 2 * overlapAmount[1];
var childrenConstant = nodeA.noOfChildren * nodeB.noOfChildren / (nodeA.noOfChildren + nodeB.noOfChildren);
nodeA.repulsionForceX -= childrenConstant * repulsionForceX;
nodeA.repulsionForceY -= childrenConstant * repulsionForceY;
nodeB.repulsionForceX += childrenConstant * repulsionForceX;
nodeB.repulsionForceY += childrenConstant * repulsionForceY;
} else {
if (this.uniformLeafNodeSizes && nodeA.getChild() == null && nodeB.getChild() == null) {
distanceX = rectB.getCenterX() - rectA.getCenterX();
distanceY = rectB.getCenterY() - rectA.getCenterY();
} else {
IGeometry.getIntersection(rectA, rectB, clipPoints);
distanceX = clipPoints[2] - clipPoints[0];
distanceY = clipPoints[3] - clipPoints[1];
}
if (Math.abs(distanceX) < FDLayoutConstants.MIN_REPULSION_DIST) {
distanceX = IMath.sign(distanceX) * FDLayoutConstants.MIN_REPULSION_DIST;
}
if (Math.abs(distanceY) < FDLayoutConstants.MIN_REPULSION_DIST) {
distanceY = IMath.sign(distanceY) * FDLayoutConstants.MIN_REPULSION_DIST;
}
distanceSquared = distanceX * distanceX + distanceY * distanceY;
distance3 = Math.sqrt(distanceSquared);
repulsionForce = (nodeA.nodeRepulsion / 2 + nodeB.nodeRepulsion / 2) * nodeA.noOfChildren * nodeB.noOfChildren / distanceSquared;
repulsionForceX = repulsionForce * distanceX / distance3;
repulsionForceY = repulsionForce * distanceY / distance3;
nodeA.repulsionForceX -= repulsionForceX;
nodeA.repulsionForceY -= repulsionForceY;
nodeB.repulsionForceX += repulsionForceX;
nodeB.repulsionForceY += repulsionForceY;
}
};
FDLayout.prototype.calcGravitationalForce = function(node2) {
var ownerGraph;
var ownerCenterX;
var ownerCenterY;
var distanceX;
var distanceY;
var absDistanceX;
var absDistanceY;
var estimatedSize;
ownerGraph = node2.getOwner();
ownerCenterX = (ownerGraph.getRight() + ownerGraph.getLeft()) / 2;
ownerCenterY = (ownerGraph.getTop() + ownerGraph.getBottom()) / 2;
distanceX = node2.getCenterX() - ownerCenterX;
distanceY = node2.getCenterY() - ownerCenterY;
absDistanceX = Math.abs(distanceX) + node2.getWidth() / 2;
absDistanceY = Math.abs(distanceY) + node2.getHeight() / 2;
if (node2.getOwner() == this.graphManager.getRoot()) {
estimatedSize = ownerGraph.getEstimatedSize() * this.gravityRangeFactor;
if (absDistanceX > estimatedSize || absDistanceY > estimatedSize) {
node2.gravitationForceX = -this.gravityConstant * distanceX;
node2.gravitationForceY = -this.gravityConstant * distanceY;
}
} else {
estimatedSize = ownerGraph.getEstimatedSize() * this.compoundGravityRangeFactor;
if (absDistanceX > estimatedSize || absDistanceY > estimatedSize) {
node2.gravitationForceX = -this.gravityConstant * distanceX * this.compoundGravityConstant;
node2.gravitationForceY = -this.gravityConstant * distanceY * this.compoundGravityConstant;
}
}
};
FDLayout.prototype.isConverged = function() {
var converged;
var oscilating = false;
if (this.totalIterations > this.maxIterations / 3) {
oscilating = Math.abs(this.totalDisplacement - this.oldTotalDisplacement) < 2;
}
converged = this.totalDisplacement < this.totalDisplacementThreshold;
this.oldTotalDisplacement = this.totalDisplacement;
return converged || oscilating;
};
FDLayout.prototype.animate = function() {
if (this.animationDuringLayout && !this.isSubLayout) {
if (this.notAnimatedIterations == this.animationPeriod) {
this.update();
this.notAnimatedIterations = 0;
} else {
this.notAnimatedIterations++;
}
}
};
FDLayout.prototype.calcNoOfChildrenForAllNodes = function() {
var node2;
var allNodes = this.graphManager.getAllNodes();
for (var i2 = 0; i2 < allNodes.length; i2++) {
node2 = allNodes[i2];
node2.noOfChildren = node2.getNoOfChildren();
}
};
FDLayout.prototype.calcGrid = function(graph) {
var sizeX = 0;
var sizeY = 0;
sizeX = parseInt(Math.ceil((graph.getRight() - graph.getLeft()) / this.repulsionRange));
sizeY = parseInt(Math.ceil((graph.getBottom() - graph.getTop()) / this.repulsionRange));
var grid = new Array(sizeX);
for (var i2 = 0; i2 < sizeX; i2++) {
grid[i2] = new Array(sizeY);
}
for (var i2 = 0; i2 < sizeX; i2++) {
for (var j3 = 0; j3 < sizeY; j3++) {
grid[i2][j3] = new Array();
}
}
return grid;
};
FDLayout.prototype.addNodeToGrid = function(v3, left3, top2) {
var startX2 = 0;
var finishX = 0;
var startY2 = 0;
var finishY = 0;
startX2 = parseInt(Math.floor((v3.getRect().x - left3) / this.repulsionRange));
finishX = parseInt(Math.floor((v3.getRect().width + v3.getRect().x - left3) / this.repulsionRange));
startY2 = parseInt(Math.floor((v3.getRect().y - top2) / this.repulsionRange));
finishY = parseInt(Math.floor((v3.getRect().height + v3.getRect().y - top2) / this.repulsionRange));
for (var i2 = startX2; i2 <= finishX; i2++) {
for (var j3 = startY2; j3 <= finishY; j3++) {
this.grid[i2][j3].push(v3);
v3.setGridCoordinates(startX2, finishX, startY2, finishY);
}
}
};
FDLayout.prototype.updateGrid = function() {
var i2;
var nodeA;
var lNodes = this.getAllNodes();
this.grid = this.calcGrid(this.graphManager.getRoot());
for (i2 = 0; i2 < lNodes.length; i2++) {
nodeA = lNodes[i2];
this.addNodeToGrid(nodeA, this.graphManager.getRoot().getLeft(), this.graphManager.getRoot().getTop());
}
};
FDLayout.prototype.calculateRepulsionForceOfANode = function(nodeA, processedNodeSet, gridUpdateAllowed, forceToNodeSurroundingUpdate) {
if (this.totalIterations % FDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD == 1 && gridUpdateAllowed || forceToNodeSurroundingUpdate) {
var surrounding = /* @__PURE__ */ new Set();
nodeA.surrounding = new Array();
var nodeB;
var grid = this.grid;
for (var i2 = nodeA.startX - 1; i2 < nodeA.finishX + 2; i2++) {
for (var j3 = nodeA.startY - 1; j3 < nodeA.finishY + 2; j3++) {
if (!(i2 < 0 || j3 < 0 || i2 >= grid.length || j3 >= grid[0].length)) {
for (var k2 = 0; k2 < grid[i2][j3].length; k2++) {
nodeB = grid[i2][j3][k2];
if (nodeA.getOwner() != nodeB.getOwner() || nodeA == nodeB) {
continue;
}
if (!processedNodeSet.has(nodeB) && !surrounding.has(nodeB)) {
var distanceX = Math.abs(nodeA.getCenterX() - nodeB.getCenterX()) - (nodeA.getWidth() / 2 + nodeB.getWidth() / 2);
var distanceY = Math.abs(nodeA.getCenterY() - nodeB.getCenterY()) - (nodeA.getHeight() / 2 + nodeB.getHeight() / 2);
if (distanceX <= this.repulsionRange && distanceY <= this.repulsionRange) {
surrounding.add(nodeB);
}
}
}
}
}
}
nodeA.surrounding = [].concat(_toConsumableArray2(surrounding));
}
for (i2 = 0; i2 < nodeA.surrounding.length; i2++) {
this.calcRepulsionForce(nodeA, nodeA.surrounding[i2]);
}
};
FDLayout.prototype.calcRepulsionRange = function() {
return 0;
};
module3.exports = FDLayout;
}),
/* 19 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var LEdge = __webpack_require__(1);
var FDLayoutConstants = __webpack_require__(4);
function FDLayoutEdge(source, target, vEdge) {
LEdge.call(this, source, target, vEdge);
this.idealLength = FDLayoutConstants.DEFAULT_EDGE_LENGTH;
this.edgeElasticity = FDLayoutConstants.DEFAULT_SPRING_STRENGTH;
}
__name(FDLayoutEdge, "FDLayoutEdge");
FDLayoutEdge.prototype = Object.create(LEdge.prototype);
for (var prop in LEdge) {
FDLayoutEdge[prop] = LEdge[prop];
}
module3.exports = FDLayoutEdge;
}),
/* 20 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var LNode = __webpack_require__(3);
var FDLayoutConstants = __webpack_require__(4);
function FDLayoutNode(gm, loc, size4, vNode) {
LNode.call(this, gm, loc, size4, vNode);
this.nodeRepulsion = FDLayoutConstants.DEFAULT_REPULSION_STRENGTH;
this.springForceX = 0;
this.springForceY = 0;
this.repulsionForceX = 0;
this.repulsionForceY = 0;
this.gravitationForceX = 0;
this.gravitationForceY = 0;
this.displacementX = 0;
this.displacementY = 0;
this.startX = 0;
this.finishX = 0;
this.startY = 0;
this.finishY = 0;
this.surrounding = [];
}
__name(FDLayoutNode, "FDLayoutNode");
FDLayoutNode.prototype = Object.create(LNode.prototype);
for (var prop in LNode) {
FDLayoutNode[prop] = LNode[prop];
}
FDLayoutNode.prototype.setGridCoordinates = function(_startX, _finishX, _startY, _finishY) {
this.startX = _startX;
this.finishX = _finishX;
this.startY = _startY;
this.finishY = _finishY;
};
module3.exports = FDLayoutNode;
}),
/* 21 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function DimensionD2(width3, height2) {
this.width = 0;
this.height = 0;
if (width3 !== null && height2 !== null) {
this.height = height2;
this.width = width3;
}
}
__name(DimensionD2, "DimensionD");
DimensionD2.prototype.getWidth = function() {
return this.width;
};
DimensionD2.prototype.setWidth = function(width3) {
this.width = width3;
};
DimensionD2.prototype.getHeight = function() {
return this.height;
};
DimensionD2.prototype.setHeight = function(height2) {
this.height = height2;
};
module3.exports = DimensionD2;
}),
/* 22 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var UniqueIDGeneretor = __webpack_require__(14);
function HashMap() {
this.map = {};
this.keys = [];
}
__name(HashMap, "HashMap");
HashMap.prototype.put = function(key, value2) {
var theId = UniqueIDGeneretor.createID(key);
if (!this.contains(theId)) {
this.map[theId] = value2;
this.keys.push(key);
}
};
HashMap.prototype.contains = function(key) {
var theId = UniqueIDGeneretor.createID(key);
return this.map[key] != null;
};
HashMap.prototype.get = function(key) {
var theId = UniqueIDGeneretor.createID(key);
return this.map[theId];
};
HashMap.prototype.keySet = function() {
return this.keys;
};
module3.exports = HashMap;
}),
/* 23 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var UniqueIDGeneretor = __webpack_require__(14);
function HashSet() {
this.set = {};
}
__name(HashSet, "HashSet");
;
HashSet.prototype.add = function(obj) {
var theId = UniqueIDGeneretor.createID(obj);
if (!this.contains(theId)) this.set[theId] = obj;
};
HashSet.prototype.remove = function(obj) {
delete this.set[UniqueIDGeneretor.createID(obj)];
};
HashSet.prototype.clear = function() {
this.set = {};
};
HashSet.prototype.contains = function(obj) {
return this.set[UniqueIDGeneretor.createID(obj)] == obj;
};
HashSet.prototype.isEmpty = function() {
return this.size() === 0;
};
HashSet.prototype.size = function() {
return Object.keys(this.set).length;
};
HashSet.prototype.addAllTo = function(list) {
var keys2 = Object.keys(this.set);
var length2 = keys2.length;
for (var i2 = 0; i2 < length2; i2++) {
list.push(this.set[keys2[i2]]);
}
};
HashSet.prototype.size = function() {
return Object.keys(this.set).length;
};
HashSet.prototype.addAll = function(list) {
var s2 = list.length;
for (var i2 = 0; i2 < s2; i2++) {
var v3 = list[i2];
this.add(v3);
}
};
module3.exports = HashSet;
}),
/* 24 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function Matrix() {
}
__name(Matrix, "Matrix");
Matrix.multMat = function(array1, array22) {
var result = [];
for (var i2 = 0; i2 < array1.length; i2++) {
result[i2] = [];
for (var j3 = 0; j3 < array22[0].length; j3++) {
result[i2][j3] = 0;
for (var k2 = 0; k2 < array1[0].length; k2++) {
result[i2][j3] += array1[i2][k2] * array22[k2][j3];
}
}
}
return result;
};
Matrix.transpose = function(array4) {
var result = [];
for (var i2 = 0; i2 < array4[0].length; i2++) {
result[i2] = [];
for (var j3 = 0; j3 < array4.length; j3++) {
result[i2][j3] = array4[j3][i2];
}
}
return result;
};
Matrix.multCons = function(array4, constant3) {
var result = [];
for (var i2 = 0; i2 < array4.length; i2++) {
result[i2] = array4[i2] * constant3;
}
return result;
};
Matrix.minusOp = function(array1, array22) {
var result = [];
for (var i2 = 0; i2 < array1.length; i2++) {
result[i2] = array1[i2] - array22[i2];
}
return result;
};
Matrix.dotProduct = function(array1, array22) {
var product = 0;
for (var i2 = 0; i2 < array1.length; i2++) {
product += array1[i2] * array22[i2];
}
return product;
};
Matrix.mag = function(array4) {
return Math.sqrt(this.dotProduct(array4, array4));
};
Matrix.normalize = function(array4) {
var result = [];
var magnitude = this.mag(array4);
for (var i2 = 0; i2 < array4.length; i2++) {
result[i2] = array4[i2] / magnitude;
}
return result;
};
Matrix.multGamma = function(array4) {
var result = [];
var sum2 = 0;
for (var i2 = 0; i2 < array4.length; i2++) {
sum2 += array4[i2];
}
sum2 *= -1 / array4.length;
for (var _i = 0; _i < array4.length; _i++) {
result[_i] = sum2 + array4[_i];
}
return result;
};
Matrix.multL = function(array4, C3, INV) {
var result = [];
var temp1 = [];
var temp2 = [];
for (var i2 = 0; i2 < C3[0].length; i2++) {
var sum2 = 0;
for (var j3 = 0; j3 < C3.length; j3++) {
sum2 += -0.5 * C3[j3][i2] * array4[j3];
}
temp1[i2] = sum2;
}
for (var _i2 = 0; _i2 < INV.length; _i2++) {
var _sum = 0;
for (var _j = 0; _j < INV.length; _j++) {
_sum += INV[_i2][_j] * temp1[_j];
}
temp2[_i2] = _sum;
}
for (var _i3 = 0; _i3 < C3.length; _i3++) {
var _sum2 = 0;
for (var _j2 = 0; _j2 < C3[0].length; _j2++) {
_sum2 += C3[_i3][_j2] * temp2[_j2];
}
result[_i3] = _sum2;
}
return result;
};
module3.exports = Matrix;
}),
/* 25 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var _createClass2 = /* @__PURE__ */ (function() {
function defineProperties(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
__name(defineProperties, "defineProperties");
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
function _classCallCheck2(instance2, Constructor) {
if (!(instance2 instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
__name(_classCallCheck2, "_classCallCheck");
var LinkedList = __webpack_require__(11);
var Quicksort = (function() {
function Quicksort2(A2, compareFunction) {
_classCallCheck2(this, Quicksort2);
if (compareFunction !== null || compareFunction !== void 0) this.compareFunction = this._defaultCompareFunction;
var length2 = void 0;
if (A2 instanceof LinkedList) length2 = A2.size();
else length2 = A2.length;
this._quicksort(A2, 0, length2 - 1);
}
__name(Quicksort2, "Quicksort");
_createClass2(Quicksort2, [{
key: "_quicksort",
value: /* @__PURE__ */ __name(function _quicksort(A2, p3, r2) {
if (p3 < r2) {
var q3 = this._partition(A2, p3, r2);
this._quicksort(A2, p3, q3);
this._quicksort(A2, q3 + 1, r2);
}
}, "_quicksort")
}, {
key: "_partition",
value: /* @__PURE__ */ __name(function _partition(A2, p3, r2) {
var x5 = this._get(A2, p3);
var i2 = p3;
var j3 = r2;
while (true) {
while (this.compareFunction(x5, this._get(A2, j3))) {
j3--;
}
while (this.compareFunction(this._get(A2, i2), x5)) {
i2++;
}
if (i2 < j3) {
this._swap(A2, i2, j3);
i2++;
j3--;
} else return j3;
}
}, "_partition")
}, {
key: "_get",
value: /* @__PURE__ */ __name(function _get(object3, index) {
if (object3 instanceof LinkedList) return object3.get_object_at(index);
else return object3[index];
}, "_get")
}, {
key: "_set",
value: /* @__PURE__ */ __name(function _set(object3, index, value2) {
if (object3 instanceof LinkedList) object3.set_object_at(index, value2);
else object3[index] = value2;
}, "_set")
}, {
key: "_swap",
value: /* @__PURE__ */ __name(function _swap(A2, i2, j3) {
var temp = this._get(A2, i2);
this._set(A2, i2, this._get(A2, j3));
this._set(A2, j3, temp);
}, "_swap")
}, {
key: "_defaultCompareFunction",
value: /* @__PURE__ */ __name(function _defaultCompareFunction(a2, b3) {
return b3 > a2;
}, "_defaultCompareFunction")
}]);
return Quicksort2;
})();
module3.exports = Quicksort;
}),
/* 26 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function SVD() {
}
__name(SVD, "SVD");
;
SVD.svd = function(A2) {
this.U = null;
this.V = null;
this.s = null;
this.m = 0;
this.n = 0;
this.m = A2.length;
this.n = A2[0].length;
var nu = Math.min(this.m, this.n);
this.s = (function(s2) {
var a2 = [];
while (s2-- > 0) {
a2.push(0);
}
return a2;
})(Math.min(this.m + 1, this.n));
this.U = (function(dims) {
var allocate = /* @__PURE__ */ __name(function allocate2(dims2) {
if (dims2.length == 0) {
return 0;
} else {
var array4 = [];
for (var i3 = 0; i3 < dims2[0]; i3++) {
array4.push(allocate2(dims2.slice(1)));
}
return array4;
}
}, "allocate");
return allocate(dims);
})([this.m, nu]);
this.V = (function(dims) {
var allocate = /* @__PURE__ */ __name(function allocate2(dims2) {
if (dims2.length == 0) {
return 0;
} else {
var array4 = [];
for (var i3 = 0; i3 < dims2[0]; i3++) {
array4.push(allocate2(dims2.slice(1)));
}
return array4;
}
}, "allocate");
return allocate(dims);
})([this.n, this.n]);
var e3 = (function(s2) {
var a2 = [];
while (s2-- > 0) {
a2.push(0);
}
return a2;
})(this.n);
var work = (function(s2) {
var a2 = [];
while (s2-- > 0) {
a2.push(0);
}
return a2;
})(this.m);
var wantu = true;
var wantv = true;
var nct = Math.min(this.m - 1, this.n);
var nrt = Math.max(0, Math.min(this.n - 2, this.m));
for (var k2 = 0; k2 < Math.max(nct, nrt); k2++) {
if (k2 < nct) {
this.s[k2] = 0;
for (var i2 = k2; i2 < this.m; i2++) {
this.s[k2] = SVD.hypot(this.s[k2], A2[i2][k2]);
}
;
if (this.s[k2] !== 0) {
if (A2[k2][k2] < 0) {
this.s[k2] = -this.s[k2];
}
for (var _i = k2; _i < this.m; _i++) {
A2[_i][k2] /= this.s[k2];
}
;
A2[k2][k2] += 1;
}
this.s[k2] = -this.s[k2];
}
for (var j3 = k2 + 1; j3 < this.n; j3++) {
if (/* @__PURE__ */ (function(lhs, rhs) {
return lhs && rhs;
})(k2 < nct, this.s[k2] !== 0)) {
var t4 = 0;
for (var _i2 = k2; _i2 < this.m; _i2++) {
t4 += A2[_i2][k2] * A2[_i2][j3];
}
;
t4 = -t4 / A2[k2][k2];
for (var _i3 = k2; _i3 < this.m; _i3++) {
A2[_i3][j3] += t4 * A2[_i3][k2];
}
;
}
e3[j3] = A2[k2][j3];
}
;
if (/* @__PURE__ */ (function(lhs, rhs) {
return lhs && rhs;
})(wantu, k2 < nct)) {
for (var _i4 = k2; _i4 < this.m; _i4++) {
this.U[_i4][k2] = A2[_i4][k2];
}
;
}
if (k2 < nrt) {
e3[k2] = 0;
for (var _i5 = k2 + 1; _i5 < this.n; _i5++) {
e3[k2] = SVD.hypot(e3[k2], e3[_i5]);
}
;
if (e3[k2] !== 0) {
if (e3[k2 + 1] < 0) {
e3[k2] = -e3[k2];
}
for (var _i6 = k2 + 1; _i6 < this.n; _i6++) {
e3[_i6] /= e3[k2];
}
;
e3[k2 + 1] += 1;
}
e3[k2] = -e3[k2];
if (/* @__PURE__ */ (function(lhs, rhs) {
return lhs && rhs;
})(k2 + 1 < this.m, e3[k2] !== 0)) {
for (var _i7 = k2 + 1; _i7 < this.m; _i7++) {
work[_i7] = 0;
}
;
for (var _j = k2 + 1; _j < this.n; _j++) {
for (var _i8 = k2 + 1; _i8 < this.m; _i8++) {
work[_i8] += e3[_j] * A2[_i8][_j];
}
;
}
;
for (var _j2 = k2 + 1; _j2 < this.n; _j2++) {
var _t = -e3[_j2] / e3[k2 + 1];
for (var _i9 = k2 + 1; _i9 < this.m; _i9++) {
A2[_i9][_j2] += _t * work[_i9];
}
;
}
;
}
if (wantv) {
for (var _i10 = k2 + 1; _i10 < this.n; _i10++) {
this.V[_i10][k2] = e3[_i10];
}
;
}
}
}
;
var p3 = Math.min(this.n, this.m + 1);
if (nct < this.n) {
this.s[nct] = A2[nct][nct];
}
if (this.m < p3) {
this.s[p3 - 1] = 0;
}
if (nrt + 1 < p3) {
e3[nrt] = A2[nrt][p3 - 1];
}
e3[p3 - 1] = 0;
if (wantu) {
for (var _j3 = nct; _j3 < nu; _j3++) {
for (var _i11 = 0; _i11 < this.m; _i11++) {
this.U[_i11][_j3] = 0;
}
;
this.U[_j3][_j3] = 1;
}
;
for (var _k = nct - 1; _k >= 0; _k--) {
if (this.s[_k] !== 0) {
for (var _j4 = _k + 1; _j4 < nu; _j4++) {
var _t2 = 0;
for (var _i12 = _k; _i12 < this.m; _i12++) {
_t2 += this.U[_i12][_k] * this.U[_i12][_j4];
}
;
_t2 = -_t2 / this.U[_k][_k];
for (var _i13 = _k; _i13 < this.m; _i13++) {
this.U[_i13][_j4] += _t2 * this.U[_i13][_k];
}
;
}
;
for (var _i14 = _k; _i14 < this.m; _i14++) {
this.U[_i14][_k] = -this.U[_i14][_k];
}
;
this.U[_k][_k] = 1 + this.U[_k][_k];
for (var _i15 = 0; _i15 < _k - 1; _i15++) {
this.U[_i15][_k] = 0;
}
;
} else {
for (var _i16 = 0; _i16 < this.m; _i16++) {
this.U[_i16][_k] = 0;
}
;
this.U[_k][_k] = 1;
}
}
;
}
if (wantv) {
for (var _k2 = this.n - 1; _k2 >= 0; _k2--) {
if (/* @__PURE__ */ (function(lhs, rhs) {
return lhs && rhs;
})(_k2 < nrt, e3[_k2] !== 0)) {
for (var _j5 = _k2 + 1; _j5 < nu; _j5++) {
var _t3 = 0;
for (var _i17 = _k2 + 1; _i17 < this.n; _i17++) {
_t3 += this.V[_i17][_k2] * this.V[_i17][_j5];
}
;
_t3 = -_t3 / this.V[_k2 + 1][_k2];
for (var _i18 = _k2 + 1; _i18 < this.n; _i18++) {
this.V[_i18][_j5] += _t3 * this.V[_i18][_k2];
}
;
}
;
}
for (var _i19 = 0; _i19 < this.n; _i19++) {
this.V[_i19][_k2] = 0;
}
;
this.V[_k2][_k2] = 1;
}
;
}
var pp = p3 - 1;
var iter = 0;
var eps = Math.pow(2, -52);
var tiny = Math.pow(2, -966);
while (p3 > 0) {
var _k3 = void 0;
var kase = void 0;
for (_k3 = p3 - 2; _k3 >= -1; _k3--) {
if (_k3 === -1) {
break;
}
if (Math.abs(e3[_k3]) <= tiny + eps * (Math.abs(this.s[_k3]) + Math.abs(this.s[_k3 + 1]))) {
e3[_k3] = 0;
break;
}
}
;
if (_k3 === p3 - 2) {
kase = 4;
} else {
var ks = void 0;
for (ks = p3 - 1; ks >= _k3; ks--) {
if (ks === _k3) {
break;
}
var _t4 = (ks !== p3 ? Math.abs(e3[ks]) : 0) + (ks !== _k3 + 1 ? Math.abs(e3[ks - 1]) : 0);
if (Math.abs(this.s[ks]) <= tiny + eps * _t4) {
this.s[ks] = 0;
break;
}
}
;
if (ks === _k3) {
kase = 3;
} else if (ks === p3 - 1) {
kase = 1;
} else {
kase = 2;
_k3 = ks;
}
}
_k3++;
switch (kase) {
case 1:
{
var f2 = e3[p3 - 2];
e3[p3 - 2] = 0;
for (var _j6 = p3 - 2; _j6 >= _k3; _j6--) {
var _t5 = SVD.hypot(this.s[_j6], f2);
var cs = this.s[_j6] / _t5;
var sn = f2 / _t5;
this.s[_j6] = _t5;
if (_j6 !== _k3) {
f2 = -sn * e3[_j6 - 1];
e3[_j6 - 1] = cs * e3[_j6 - 1];
}
if (wantv) {
for (var _i20 = 0; _i20 < this.n; _i20++) {
_t5 = cs * this.V[_i20][_j6] + sn * this.V[_i20][p3 - 1];
this.V[_i20][p3 - 1] = -sn * this.V[_i20][_j6] + cs * this.V[_i20][p3 - 1];
this.V[_i20][_j6] = _t5;
}
;
}
}
;
}
;
break;
case 2:
{
var _f = e3[_k3 - 1];
e3[_k3 - 1] = 0;
for (var _j7 = _k3; _j7 < p3; _j7++) {
var _t6 = SVD.hypot(this.s[_j7], _f);
var _cs = this.s[_j7] / _t6;
var _sn = _f / _t6;
this.s[_j7] = _t6;
_f = -_sn * e3[_j7];
e3[_j7] = _cs * e3[_j7];
if (wantu) {
for (var _i21 = 0; _i21 < this.m; _i21++) {
_t6 = _cs * this.U[_i21][_j7] + _sn * this.U[_i21][_k3 - 1];
this.U[_i21][_k3 - 1] = -_sn * this.U[_i21][_j7] + _cs * this.U[_i21][_k3 - 1];
this.U[_i21][_j7] = _t6;
}
;
}
}
;
}
;
break;
case 3:
{
var scale3 = Math.max(Math.max(Math.max(Math.max(Math.abs(this.s[p3 - 1]), Math.abs(this.s[p3 - 2])), Math.abs(e3[p3 - 2])), Math.abs(this.s[_k3])), Math.abs(e3[_k3]));
var sp = this.s[p3 - 1] / scale3;
var spm1 = this.s[p3 - 2] / scale3;
var epm1 = e3[p3 - 2] / scale3;
var sk = this.s[_k3] / scale3;
var ek = e3[_k3] / scale3;
var b3 = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;
var c3 = sp * epm1 * (sp * epm1);
var shift2 = 0;
if (/* @__PURE__ */ (function(lhs, rhs) {
return lhs || rhs;
})(b3 !== 0, c3 !== 0)) {
shift2 = Math.sqrt(b3 * b3 + c3);
if (b3 < 0) {
shift2 = -shift2;
}
shift2 = c3 / (b3 + shift2);
}
var _f2 = (sk + sp) * (sk - sp) + shift2;
var g2 = sk * ek;
for (var _j8 = _k3; _j8 < p3 - 1; _j8++) {
var _t7 = SVD.hypot(_f2, g2);
var _cs2 = _f2 / _t7;
var _sn2 = g2 / _t7;
if (_j8 !== _k3) {
e3[_j8 - 1] = _t7;
}
_f2 = _cs2 * this.s[_j8] + _sn2 * e3[_j8];
e3[_j8] = _cs2 * e3[_j8] - _sn2 * this.s[_j8];
g2 = _sn2 * this.s[_j8 + 1];
this.s[_j8 + 1] = _cs2 * this.s[_j8 + 1];
if (wantv) {
for (var _i22 = 0; _i22 < this.n; _i22++) {
_t7 = _cs2 * this.V[_i22][_j8] + _sn2 * this.V[_i22][_j8 + 1];
this.V[_i22][_j8 + 1] = -_sn2 * this.V[_i22][_j8] + _cs2 * this.V[_i22][_j8 + 1];
this.V[_i22][_j8] = _t7;
}
;
}
_t7 = SVD.hypot(_f2, g2);
_cs2 = _f2 / _t7;
_sn2 = g2 / _t7;
this.s[_j8] = _t7;
_f2 = _cs2 * e3[_j8] + _sn2 * this.s[_j8 + 1];
this.s[_j8 + 1] = -_sn2 * e3[_j8] + _cs2 * this.s[_j8 + 1];
g2 = _sn2 * e3[_j8 + 1];
e3[_j8 + 1] = _cs2 * e3[_j8 + 1];
if (wantu && _j8 < this.m - 1) {
for (var _i23 = 0; _i23 < this.m; _i23++) {
_t7 = _cs2 * this.U[_i23][_j8] + _sn2 * this.U[_i23][_j8 + 1];
this.U[_i23][_j8 + 1] = -_sn2 * this.U[_i23][_j8] + _cs2 * this.U[_i23][_j8 + 1];
this.U[_i23][_j8] = _t7;
}
;
}
}
;
e3[p3 - 2] = _f2;
iter = iter + 1;
}
;
break;
case 4:
{
if (this.s[_k3] <= 0) {
this.s[_k3] = this.s[_k3] < 0 ? -this.s[_k3] : 0;
if (wantv) {
for (var _i24 = 0; _i24 <= pp; _i24++) {
this.V[_i24][_k3] = -this.V[_i24][_k3];
}
;
}
}
while (_k3 < pp) {
if (this.s[_k3] >= this.s[_k3 + 1]) {
break;
}
var _t8 = this.s[_k3];
this.s[_k3] = this.s[_k3 + 1];
this.s[_k3 + 1] = _t8;
if (wantv && _k3 < this.n - 1) {
for (var _i25 = 0; _i25 < this.n; _i25++) {
_t8 = this.V[_i25][_k3 + 1];
this.V[_i25][_k3 + 1] = this.V[_i25][_k3];
this.V[_i25][_k3] = _t8;
}
;
}
if (wantu && _k3 < this.m - 1) {
for (var _i26 = 0; _i26 < this.m; _i26++) {
_t8 = this.U[_i26][_k3 + 1];
this.U[_i26][_k3 + 1] = this.U[_i26][_k3];
this.U[_i26][_k3] = _t8;
}
;
}
_k3++;
}
;
iter = 0;
p3--;
}
;
break;
}
}
;
var result = { U: this.U, V: this.V, S: this.s };
return result;
};
SVD.hypot = function(a2, b3) {
var r2 = void 0;
if (Math.abs(a2) > Math.abs(b3)) {
r2 = b3 / a2;
r2 = Math.abs(a2) * Math.sqrt(1 + r2 * r2);
} else if (b3 != 0) {
r2 = a2 / b3;
r2 = Math.abs(b3) * Math.sqrt(1 + r2 * r2);
} else {
r2 = 0;
}
return r2;
};
module3.exports = SVD;
}),
/* 27 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var _createClass2 = /* @__PURE__ */ (function() {
function defineProperties(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
__name(defineProperties, "defineProperties");
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
function _classCallCheck2(instance2, Constructor) {
if (!(instance2 instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
__name(_classCallCheck2, "_classCallCheck");
var NeedlemanWunsch = (function() {
function NeedlemanWunsch2(sequence1, sequence2) {
var match_score = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1;
var mismatch_penalty = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : -1;
var gap_penalty = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : -1;
_classCallCheck2(this, NeedlemanWunsch2);
this.sequence1 = sequence1;
this.sequence2 = sequence2;
this.match_score = match_score;
this.mismatch_penalty = mismatch_penalty;
this.gap_penalty = gap_penalty;
this.iMax = sequence1.length + 1;
this.jMax = sequence2.length + 1;
this.grid = new Array(this.iMax);
for (var i2 = 0; i2 < this.iMax; i2++) {
this.grid[i2] = new Array(this.jMax);
for (var j3 = 0; j3 < this.jMax; j3++) {
this.grid[i2][j3] = 0;
}
}
this.tracebackGrid = new Array(this.iMax);
for (var _i = 0; _i < this.iMax; _i++) {
this.tracebackGrid[_i] = new Array(this.jMax);
for (var _j = 0; _j < this.jMax; _j++) {
this.tracebackGrid[_i][_j] = [null, null, null];
}
}
this.alignments = [];
this.score = -1;
this.computeGrids();
}
__name(NeedlemanWunsch2, "NeedlemanWunsch");
_createClass2(NeedlemanWunsch2, [{
key: "getScore",
value: /* @__PURE__ */ __name(function getScore() {
return this.score;
}, "getScore")
}, {
key: "getAlignments",
value: /* @__PURE__ */ __name(function getAlignments2() {
return this.alignments;
}, "getAlignments")
// Main dynamic programming procedure
}, {
key: "computeGrids",
value: /* @__PURE__ */ __name(function computeGrids() {
for (var j3 = 1; j3 < this.jMax; j3++) {
this.grid[0][j3] = this.grid[0][j3 - 1] + this.gap_penalty;
this.tracebackGrid[0][j3] = [false, false, true];
}
for (var i2 = 1; i2 < this.iMax; i2++) {
this.grid[i2][0] = this.grid[i2 - 1][0] + this.gap_penalty;
this.tracebackGrid[i2][0] = [false, true, false];
}
for (var _i2 = 1; _i2 < this.iMax; _i2++) {
for (var _j2 = 1; _j2 < this.jMax; _j2++) {
var diag = void 0;
if (this.sequence1[_i2 - 1] === this.sequence2[_j2 - 1]) diag = this.grid[_i2 - 1][_j2 - 1] + this.match_score;
else diag = this.grid[_i2 - 1][_j2 - 1] + this.mismatch_penalty;
var up = this.grid[_i2 - 1][_j2] + this.gap_penalty;
var left3 = this.grid[_i2][_j2 - 1] + this.gap_penalty;
var maxOf = [diag, up, left3];
var indices = this.arrayAllMaxIndexes(maxOf);
this.grid[_i2][_j2] = maxOf[indices[0]];
this.tracebackGrid[_i2][_j2] = [indices.includes(0), indices.includes(1), indices.includes(2)];
}
}
this.score = this.grid[this.iMax - 1][this.jMax - 1];
}, "computeGrids")
// Gets all possible valid sequence combinations
}, {
key: "alignmentTraceback",
value: /* @__PURE__ */ __name(function alignmentTraceback() {
var inProcessAlignments = [];
inProcessAlignments.push({
pos: [this.sequence1.length, this.sequence2.length],
seq1: "",
seq2: ""
});
while (inProcessAlignments[0]) {
var current = inProcessAlignments[0];
var directions = this.tracebackGrid[current.pos[0]][current.pos[1]];
if (directions[0]) {
inProcessAlignments.push({
pos: [current.pos[0] - 1, current.pos[1] - 1],
seq1: this.sequence1[current.pos[0] - 1] + current.seq1,
seq2: this.sequence2[current.pos[1] - 1] + current.seq2
});
}
if (directions[1]) {
inProcessAlignments.push({
pos: [current.pos[0] - 1, current.pos[1]],
seq1: this.sequence1[current.pos[0] - 1] + current.seq1,
seq2: "-" + current.seq2
});
}
if (directions[2]) {
inProcessAlignments.push({
pos: [current.pos[0], current.pos[1] - 1],
seq1: "-" + current.seq1,
seq2: this.sequence2[current.pos[1] - 1] + current.seq2
});
}
if (current.pos[0] === 0 && current.pos[1] === 0) this.alignments.push({
sequence1: current.seq1,
sequence2: current.seq2
});
inProcessAlignments.shift();
}
return this.alignments;
}, "alignmentTraceback")
// Helper Functions
}, {
key: "getAllIndexes",
value: /* @__PURE__ */ __name(function getAllIndexes(arr, val) {
var indexes = [], i2 = -1;
while ((i2 = arr.indexOf(val, i2 + 1)) !== -1) {
indexes.push(i2);
}
return indexes;
}, "getAllIndexes")
}, {
key: "arrayAllMaxIndexes",
value: /* @__PURE__ */ __name(function arrayAllMaxIndexes(array4) {
return this.getAllIndexes(array4, Math.max.apply(null, array4));
}, "arrayAllMaxIndexes")
}]);
return NeedlemanWunsch2;
})();
module3.exports = NeedlemanWunsch;
}),
/* 28 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
var layoutBase = /* @__PURE__ */ __name(function layoutBase2() {
return;
}, "layoutBase");
layoutBase.FDLayout = __webpack_require__(18);
layoutBase.FDLayoutConstants = __webpack_require__(4);
layoutBase.FDLayoutEdge = __webpack_require__(19);
layoutBase.FDLayoutNode = __webpack_require__(20);
layoutBase.DimensionD = __webpack_require__(21);
layoutBase.HashMap = __webpack_require__(22);
layoutBase.HashSet = __webpack_require__(23);
layoutBase.IGeometry = __webpack_require__(8);
layoutBase.IMath = __webpack_require__(9);
layoutBase.Integer = __webpack_require__(10);
layoutBase.Point = __webpack_require__(12);
layoutBase.PointD = __webpack_require__(5);
layoutBase.RandomSeed = __webpack_require__(16);
layoutBase.RectangleD = __webpack_require__(13);
layoutBase.Transform = __webpack_require__(17);
layoutBase.UniqueIDGeneretor = __webpack_require__(14);
layoutBase.Quicksort = __webpack_require__(25);
layoutBase.LinkedList = __webpack_require__(11);
layoutBase.LGraphObject = __webpack_require__(2);
layoutBase.LGraph = __webpack_require__(6);
layoutBase.LEdge = __webpack_require__(1);
layoutBase.LGraphManager = __webpack_require__(7);
layoutBase.LNode = __webpack_require__(3);
layoutBase.Layout = __webpack_require__(15);
layoutBase.LayoutConstants = __webpack_require__(0);
layoutBase.NeedlemanWunsch = __webpack_require__(27);
layoutBase.Matrix = __webpack_require__(24);
layoutBase.SVD = __webpack_require__(26);
module3.exports = layoutBase;
}),
/* 29 */
/***/
(function(module3, exports3, __webpack_require__) {
"use strict";
function Emitter4() {
this.listeners = [];
}
__name(Emitter4, "Emitter");
var p3 = Emitter4.prototype;
p3.addListener = function(event3, callback) {
this.listeners.push({
event: event3,
callback
});
};
p3.removeListener = function(event3, callback) {
for (var i2 = this.listeners.length; i2 >= 0; i2--) {
var l4 = this.listeners[i2];
if (l4.event === event3 && l4.callback === callback) {
this.listeners.splice(i2, 1);
}
}
};
p3.emit = function(event3, data5) {
for (var i2 = 0; i2 < this.listeners.length; i2++) {
var l4 = this.listeners[i2];
if (event3 === l4.event) {
l4.callback(data5);
}
}
};
module3.exports = Emitter4;
})
/******/
])
);
});
}
});
// ../../node_modules/.pnpm/cose-base@2.2.0/node_modules/cose-base/cose-base.js
var require_cose_base2 = __commonJS({
"../../node_modules/.pnpm/cose-base@2.2.0/node_modules/cose-base/cose-base.js"(exports2, module2) {
"use strict";
(/* @__PURE__ */ __name((function webpackUniversalModuleDefinition(root3, factory) {
if (typeof exports2 === "object" && typeof module2 === "object")
module2.exports = factory(require_layout_base2());
else if (typeof define === "function" && define.amd)
define(["layout-base"], factory);
else if (typeof exports2 === "object")
exports2["coseBase"] = factory(require_layout_base2());
else
root3["coseBase"] = factory(root3["layoutBase"]);
}), "webpackUniversalModuleDefinition"))(exports2, function(__WEBPACK_EXTERNAL_MODULE__551__) {
return (
/******/
(() => {
"use strict";
var __webpack_modules__ = {
/***/
45: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var coseBase = {};
coseBase.layoutBase = __webpack_require__2(551);
coseBase.CoSEConstants = __webpack_require__2(806);
coseBase.CoSEEdge = __webpack_require__2(767);
coseBase.CoSEGraph = __webpack_require__2(880);
coseBase.CoSEGraphManager = __webpack_require__2(578);
coseBase.CoSELayout = __webpack_require__2(765);
coseBase.CoSENode = __webpack_require__2(991);
coseBase.ConstraintHandler = __webpack_require__2(902);
module3.exports = coseBase;
})
),
/***/
806: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var FDLayoutConstants = __webpack_require__2(551).FDLayoutConstants;
function CoSEConstants() {
}
__name(CoSEConstants, "CoSEConstants");
for (var prop in FDLayoutConstants) {
CoSEConstants[prop] = FDLayoutConstants[prop];
}
CoSEConstants.DEFAULT_USE_MULTI_LEVEL_SCALING = false;
CoSEConstants.DEFAULT_RADIAL_SEPARATION = FDLayoutConstants.DEFAULT_EDGE_LENGTH;
CoSEConstants.DEFAULT_COMPONENT_SEPERATION = 60;
CoSEConstants.TILE = true;
CoSEConstants.TILING_PADDING_VERTICAL = 10;
CoSEConstants.TILING_PADDING_HORIZONTAL = 10;
CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;
CoSEConstants.ENFORCE_CONSTRAINTS = true;
CoSEConstants.APPLY_LAYOUT = true;
CoSEConstants.RELAX_MOVEMENT_ON_CONSTRAINTS = true;
CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = true;
CoSEConstants.PURE_INCREMENTAL = CoSEConstants.DEFAULT_INCREMENTAL;
module3.exports = CoSEConstants;
})
),
/***/
767: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var FDLayoutEdge = __webpack_require__2(551).FDLayoutEdge;
function CoSEEdge(source, target, vEdge) {
FDLayoutEdge.call(this, source, target, vEdge);
}
__name(CoSEEdge, "CoSEEdge");
CoSEEdge.prototype = Object.create(FDLayoutEdge.prototype);
for (var prop in FDLayoutEdge) {
CoSEEdge[prop] = FDLayoutEdge[prop];
}
module3.exports = CoSEEdge;
})
),
/***/
880: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var LGraph = __webpack_require__2(551).LGraph;
function CoSEGraph(parent4, graphMgr, vGraph) {
LGraph.call(this, parent4, graphMgr, vGraph);
}
__name(CoSEGraph, "CoSEGraph");
CoSEGraph.prototype = Object.create(LGraph.prototype);
for (var prop in LGraph) {
CoSEGraph[prop] = LGraph[prop];
}
module3.exports = CoSEGraph;
})
),
/***/
578: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var LGraphManager = __webpack_require__2(551).LGraphManager;
function CoSEGraphManager(layout7) {
LGraphManager.call(this, layout7);
}
__name(CoSEGraphManager, "CoSEGraphManager");
CoSEGraphManager.prototype = Object.create(LGraphManager.prototype);
for (var prop in LGraphManager) {
CoSEGraphManager[prop] = LGraphManager[prop];
}
module3.exports = CoSEGraphManager;
})
),
/***/
765: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var FDLayout = __webpack_require__2(551).FDLayout;
var CoSEGraphManager = __webpack_require__2(578);
var CoSEGraph = __webpack_require__2(880);
var CoSENode = __webpack_require__2(991);
var CoSEEdge = __webpack_require__2(767);
var CoSEConstants = __webpack_require__2(806);
var ConstraintHandler = __webpack_require__2(902);
var FDLayoutConstants = __webpack_require__2(551).FDLayoutConstants;
var LayoutConstants = __webpack_require__2(551).LayoutConstants;
var Point3 = __webpack_require__2(551).Point;
var PointD = __webpack_require__2(551).PointD;
var DimensionD2 = __webpack_require__2(551).DimensionD;
var Layout2 = __webpack_require__2(551).Layout;
var Integer = __webpack_require__2(551).Integer;
var IGeometry = __webpack_require__2(551).IGeometry;
var LGraph = __webpack_require__2(551).LGraph;
var Transform2 = __webpack_require__2(551).Transform;
var LinkedList = __webpack_require__2(551).LinkedList;
function CoSELayout() {
FDLayout.call(this);
this.toBeTiled = {};
this.constraints = {};
}
__name(CoSELayout, "CoSELayout");
CoSELayout.prototype = Object.create(FDLayout.prototype);
for (var prop in FDLayout) {
CoSELayout[prop] = FDLayout[prop];
}
CoSELayout.prototype.newGraphManager = function() {
var gm = new CoSEGraphManager(this);
this.graphManager = gm;
return gm;
};
CoSELayout.prototype.newGraph = function(vGraph) {
return new CoSEGraph(null, this.graphManager, vGraph);
};
CoSELayout.prototype.newNode = function(vNode) {
return new CoSENode(this.graphManager, vNode);
};
CoSELayout.prototype.newEdge = function(vEdge) {
return new CoSEEdge(null, null, vEdge);
};
CoSELayout.prototype.initParameters = function() {
FDLayout.prototype.initParameters.call(this, arguments);
if (!this.isSubLayout) {
if (CoSEConstants.DEFAULT_EDGE_LENGTH < 10) {
this.idealEdgeLength = 10;
} else {
this.idealEdgeLength = CoSEConstants.DEFAULT_EDGE_LENGTH;
}
this.useSmartIdealEdgeLengthCalculation = CoSEConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION;
this.gravityConstant = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH;
this.compoundGravityConstant = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH;
this.gravityRangeFactor = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR;
this.compoundGravityRangeFactor = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR;
this.prunedNodesAll = [];
this.growTreeIterations = 0;
this.afterGrowthIterations = 0;
this.isTreeGrowing = false;
this.isGrowthFinished = false;
}
};
CoSELayout.prototype.initSpringEmbedder = function() {
FDLayout.prototype.initSpringEmbedder.call(this);
this.coolingCycle = 0;
this.maxCoolingCycle = this.maxIterations / FDLayoutConstants.CONVERGENCE_CHECK_PERIOD;
this.finalTemperature = 0.04;
this.coolingAdjuster = 1;
};
CoSELayout.prototype.layout = function() {
var createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;
if (createBendsAsNeeded) {
this.createBendpoints();
this.graphManager.resetAllEdges();
}
this.level = 0;
return this.classicLayout();
};
CoSELayout.prototype.classicLayout = function() {
this.nodesWithGravity = this.calculateNodesToApplyGravitationTo();
this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity);
this.calcNoOfChildrenForAllNodes();
this.graphManager.calcLowestCommonAncestors();
this.graphManager.calcInclusionTreeDepths();
this.graphManager.getRoot().calcEstimatedSize();
this.calcIdealEdgeLengths();
if (!this.incremental) {
var forest = this.getFlatForest();
if (forest.length > 0) {
this.positionNodesRadially(forest);
} else {
this.reduceTrees();
this.graphManager.resetAllNodesToApplyGravitation();
var allNodes = new Set(this.getAllNodes());
var intersection4 = this.nodesWithGravity.filter(function(x5) {
return allNodes.has(x5);
});
this.graphManager.setAllNodesToApplyGravitation(intersection4);
this.positionNodesRandomly();
}
} else {
if (CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL) {
this.reduceTrees();
this.graphManager.resetAllNodesToApplyGravitation();
var allNodes = new Set(this.getAllNodes());
var intersection4 = this.nodesWithGravity.filter(function(x5) {
return allNodes.has(x5);
});
this.graphManager.setAllNodesToApplyGravitation(intersection4);
}
}
if (Object.keys(this.constraints).length > 0) {
ConstraintHandler.handleConstraints(this);
this.initConstraintVariables();
}
this.initSpringEmbedder();
if (CoSEConstants.APPLY_LAYOUT) {
this.runSpringEmbedder();
}
return true;
};
CoSELayout.prototype.tick = function() {
this.totalIterations++;
if (this.totalIterations === this.maxIterations && !this.isTreeGrowing && !this.isGrowthFinished) {
if (this.prunedNodesAll.length > 0) {
this.isTreeGrowing = true;
} else {
return true;
}
}
if (this.totalIterations % FDLayoutConstants.CONVERGENCE_CHECK_PERIOD == 0 && !this.isTreeGrowing && !this.isGrowthFinished) {
if (this.isConverged()) {
if (this.prunedNodesAll.length > 0) {
this.isTreeGrowing = true;
} else {
return true;
}
}
this.coolingCycle++;
if (this.layoutQuality == 0) {
this.coolingAdjuster = this.coolingCycle;
} else if (this.layoutQuality == 1) {
this.coolingAdjuster = this.coolingCycle / 3;
}
this.coolingFactor = Math.max(this.initialCoolingFactor - Math.pow(this.coolingCycle, Math.log(100 * (this.initialCoolingFactor - this.finalTemperature)) / Math.log(this.maxCoolingCycle)) / 100 * this.coolingAdjuster, this.finalTemperature);
this.animationPeriod = Math.ceil(this.initialAnimationPeriod * Math.sqrt(this.coolingFactor));
}
if (this.isTreeGrowing) {
if (this.growTreeIterations % 10 == 0) {
if (this.prunedNodesAll.length > 0) {
this.graphManager.updateBounds();
this.updateGrid();
this.growTree(this.prunedNodesAll);
this.graphManager.resetAllNodesToApplyGravitation();
var allNodes = new Set(this.getAllNodes());
var intersection4 = this.nodesWithGravity.filter(function(x5) {
return allNodes.has(x5);
});
this.graphManager.setAllNodesToApplyGravitation(intersection4);
this.graphManager.updateBounds();
this.updateGrid();
if (CoSEConstants.PURE_INCREMENTAL) this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL / 2;
else this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;
} else {
this.isTreeGrowing = false;
this.isGrowthFinished = true;
}
}
this.growTreeIterations++;
}
if (this.isGrowthFinished) {
if (this.isConverged()) {
return true;
}
if (this.afterGrowthIterations % 10 == 0) {
this.graphManager.updateBounds();
this.updateGrid();
}
if (CoSEConstants.PURE_INCREMENTAL) this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL / 2 * ((100 - this.afterGrowthIterations) / 100);
else this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL * ((100 - this.afterGrowthIterations) / 100);
this.afterGrowthIterations++;
}
var gridUpdateAllowed = !this.isTreeGrowing && !this.isGrowthFinished;
var forceToNodeSurroundingUpdate = this.growTreeIterations % 10 == 1 && this.isTreeGrowing || this.afterGrowthIterations % 10 == 1 && this.isGrowthFinished;
this.totalDisplacement = 0;
this.graphManager.updateBounds();
this.calcSpringForces();
this.calcRepulsionForces(gridUpdateAllowed, forceToNodeSurroundingUpdate);
this.calcGravitationalForces();
this.moveNodes();
this.animate();
return false;
};
CoSELayout.prototype.getPositionsData = function() {
var allNodes = this.graphManager.getAllNodes();
var pData = {};
for (var i2 = 0; i2 < allNodes.length; i2++) {
var rect3 = allNodes[i2].rect;
var id32 = allNodes[i2].id;
pData[id32] = {
id: id32,
x: rect3.getCenterX(),
y: rect3.getCenterY(),
w: rect3.width,
h: rect3.height
};
}
return pData;
};
CoSELayout.prototype.runSpringEmbedder = function() {
this.initialAnimationPeriod = 25;
this.animationPeriod = this.initialAnimationPeriod;
var layoutEnded = false;
if (FDLayoutConstants.ANIMATE === "during") {
this.emit("layoutstarted");
} else {
while (!layoutEnded) {
layoutEnded = this.tick();
}
this.graphManager.updateBounds();
}
};
CoSELayout.prototype.moveNodes = function() {
var lNodes = this.getAllNodes();
var node2;
for (var i2 = 0; i2 < lNodes.length; i2++) {
node2 = lNodes[i2];
node2.calculateDisplacement();
}
if (Object.keys(this.constraints).length > 0) {
this.updateDisplacements();
}
for (var i2 = 0; i2 < lNodes.length; i2++) {
node2 = lNodes[i2];
node2.move();
}
};
CoSELayout.prototype.initConstraintVariables = function() {
var self2 = this;
this.idToNodeMap = /* @__PURE__ */ new Map();
this.fixedNodeSet = /* @__PURE__ */ new Set();
var allNodes = this.graphManager.getAllNodes();
for (var i2 = 0; i2 < allNodes.length; i2++) {
var node2 = allNodes[i2];
this.idToNodeMap.set(node2.id, node2);
}
var calculateCompoundWeight = /* @__PURE__ */ __name(function calculateCompoundWeight2(compoundNode) {
var nodes5 = compoundNode.getChild().getNodes();
var node3;
var fixedNodeWeight2 = 0;
for (var i3 = 0; i3 < nodes5.length; i3++) {
node3 = nodes5[i3];
if (node3.getChild() == null) {
if (self2.fixedNodeSet.has(node3.id)) {
fixedNodeWeight2 += 100;
}
} else {
fixedNodeWeight2 += calculateCompoundWeight2(node3);
}
}
return fixedNodeWeight2;
}, "calculateCompoundWeight");
if (this.constraints.fixedNodeConstraint) {
this.constraints.fixedNodeConstraint.forEach(function(nodeData2) {
self2.fixedNodeSet.add(nodeData2.nodeId);
});
var allNodes = this.graphManager.getAllNodes();
var node2;
for (var i2 = 0; i2 < allNodes.length; i2++) {
node2 = allNodes[i2];
if (node2.getChild() != null) {
var fixedNodeWeight = calculateCompoundWeight(node2);
if (fixedNodeWeight > 0) {
node2.fixedNodeWeight = fixedNodeWeight;
}
}
}
}
if (this.constraints.relativePlacementConstraint) {
var nodeToDummyForVerticalAlignment = /* @__PURE__ */ new Map();
var nodeToDummyForHorizontalAlignment = /* @__PURE__ */ new Map();
this.dummyToNodeForVerticalAlignment = /* @__PURE__ */ new Map();
this.dummyToNodeForHorizontalAlignment = /* @__PURE__ */ new Map();
this.fixedNodesOnHorizontal = /* @__PURE__ */ new Set();
this.fixedNodesOnVertical = /* @__PURE__ */ new Set();
this.fixedNodeSet.forEach(function(nodeId) {
self2.fixedNodesOnHorizontal.add(nodeId);
self2.fixedNodesOnVertical.add(nodeId);
});
if (this.constraints.alignmentConstraint) {
if (this.constraints.alignmentConstraint.vertical) {
var verticalAlignment2 = this.constraints.alignmentConstraint.vertical;
for (var i2 = 0; i2 < verticalAlignment2.length; i2++) {
this.dummyToNodeForVerticalAlignment.set("dummy" + i2, []);
verticalAlignment2[i2].forEach(function(nodeId) {
nodeToDummyForVerticalAlignment.set(nodeId, "dummy" + i2);
self2.dummyToNodeForVerticalAlignment.get("dummy" + i2).push(nodeId);
if (self2.fixedNodeSet.has(nodeId)) {
self2.fixedNodesOnHorizontal.add("dummy" + i2);
}
});
}
}
if (this.constraints.alignmentConstraint.horizontal) {
var horizontalAlignment = this.constraints.alignmentConstraint.horizontal;
for (var i2 = 0; i2 < horizontalAlignment.length; i2++) {
this.dummyToNodeForHorizontalAlignment.set("dummy" + i2, []);
horizontalAlignment[i2].forEach(function(nodeId) {
nodeToDummyForHorizontalAlignment.set(nodeId, "dummy" + i2);
self2.dummyToNodeForHorizontalAlignment.get("dummy" + i2).push(nodeId);
if (self2.fixedNodeSet.has(nodeId)) {
self2.fixedNodesOnVertical.add("dummy" + i2);
}
});
}
}
}
if (CoSEConstants.RELAX_MOVEMENT_ON_CONSTRAINTS) {
this.shuffle = function(array4) {
var j3, x5, i3;
for (i3 = array4.length - 1; i3 >= 2 * array4.length / 3; i3--) {
j3 = Math.floor(Math.random() * (i3 + 1));
x5 = array4[i3];
array4[i3] = array4[j3];
array4[j3] = x5;
}
return array4;
};
this.nodesInRelativeHorizontal = [];
this.nodesInRelativeVertical = [];
this.nodeToRelativeConstraintMapHorizontal = /* @__PURE__ */ new Map();
this.nodeToRelativeConstraintMapVertical = /* @__PURE__ */ new Map();
this.nodeToTempPositionMapHorizontal = /* @__PURE__ */ new Map();
this.nodeToTempPositionMapVertical = /* @__PURE__ */ new Map();
this.constraints.relativePlacementConstraint.forEach(function(constraint) {
if (constraint.left) {
var nodeIdLeft = nodeToDummyForVerticalAlignment.has(constraint.left) ? nodeToDummyForVerticalAlignment.get(constraint.left) : constraint.left;
var nodeIdRight = nodeToDummyForVerticalAlignment.has(constraint.right) ? nodeToDummyForVerticalAlignment.get(constraint.right) : constraint.right;
if (!self2.nodesInRelativeHorizontal.includes(nodeIdLeft)) {
self2.nodesInRelativeHorizontal.push(nodeIdLeft);
self2.nodeToRelativeConstraintMapHorizontal.set(nodeIdLeft, []);
if (self2.dummyToNodeForVerticalAlignment.has(nodeIdLeft)) {
self2.nodeToTempPositionMapHorizontal.set(nodeIdLeft, self2.idToNodeMap.get(self2.dummyToNodeForVerticalAlignment.get(nodeIdLeft)[0]).getCenterX());
} else {
self2.nodeToTempPositionMapHorizontal.set(nodeIdLeft, self2.idToNodeMap.get(nodeIdLeft).getCenterX());
}
}
if (!self2.nodesInRelativeHorizontal.includes(nodeIdRight)) {
self2.nodesInRelativeHorizontal.push(nodeIdRight);
self2.nodeToRelativeConstraintMapHorizontal.set(nodeIdRight, []);
if (self2.dummyToNodeForVerticalAlignment.has(nodeIdRight)) {
self2.nodeToTempPositionMapHorizontal.set(nodeIdRight, self2.idToNodeMap.get(self2.dummyToNodeForVerticalAlignment.get(nodeIdRight)[0]).getCenterX());
} else {
self2.nodeToTempPositionMapHorizontal.set(nodeIdRight, self2.idToNodeMap.get(nodeIdRight).getCenterX());
}
}
self2.nodeToRelativeConstraintMapHorizontal.get(nodeIdLeft).push({ right: nodeIdRight, gap: constraint.gap });
self2.nodeToRelativeConstraintMapHorizontal.get(nodeIdRight).push({ left: nodeIdLeft, gap: constraint.gap });
} else {
var nodeIdTop = nodeToDummyForHorizontalAlignment.has(constraint.top) ? nodeToDummyForHorizontalAlignment.get(constraint.top) : constraint.top;
var nodeIdBottom = nodeToDummyForHorizontalAlignment.has(constraint.bottom) ? nodeToDummyForHorizontalAlignment.get(constraint.bottom) : constraint.bottom;
if (!self2.nodesInRelativeVertical.includes(nodeIdTop)) {
self2.nodesInRelativeVertical.push(nodeIdTop);
self2.nodeToRelativeConstraintMapVertical.set(nodeIdTop, []);
if (self2.dummyToNodeForHorizontalAlignment.has(nodeIdTop)) {
self2.nodeToTempPositionMapVertical.set(nodeIdTop, self2.idToNodeMap.get(self2.dummyToNodeForHorizontalAlignment.get(nodeIdTop)[0]).getCenterY());
} else {
self2.nodeToTempPositionMapVertical.set(nodeIdTop, self2.idToNodeMap.get(nodeIdTop).getCenterY());
}
}
if (!self2.nodesInRelativeVertical.includes(nodeIdBottom)) {
self2.nodesInRelativeVertical.push(nodeIdBottom);
self2.nodeToRelativeConstraintMapVertical.set(nodeIdBottom, []);
if (self2.dummyToNodeForHorizontalAlignment.has(nodeIdBottom)) {
self2.nodeToTempPositionMapVertical.set(nodeIdBottom, self2.idToNodeMap.get(self2.dummyToNodeForHorizontalAlignment.get(nodeIdBottom)[0]).getCenterY());
} else {
self2.nodeToTempPositionMapVertical.set(nodeIdBottom, self2.idToNodeMap.get(nodeIdBottom).getCenterY());
}
}
self2.nodeToRelativeConstraintMapVertical.get(nodeIdTop).push({ bottom: nodeIdBottom, gap: constraint.gap });
self2.nodeToRelativeConstraintMapVertical.get(nodeIdBottom).push({ top: nodeIdTop, gap: constraint.gap });
}
});
} else {
var subGraphOnHorizontal = /* @__PURE__ */ new Map();
var subGraphOnVertical = /* @__PURE__ */ new Map();
this.constraints.relativePlacementConstraint.forEach(function(constraint) {
if (constraint.left) {
var left3 = nodeToDummyForVerticalAlignment.has(constraint.left) ? nodeToDummyForVerticalAlignment.get(constraint.left) : constraint.left;
var right3 = nodeToDummyForVerticalAlignment.has(constraint.right) ? nodeToDummyForVerticalAlignment.get(constraint.right) : constraint.right;
if (subGraphOnHorizontal.has(left3)) {
subGraphOnHorizontal.get(left3).push(right3);
} else {
subGraphOnHorizontal.set(left3, [right3]);
}
if (subGraphOnHorizontal.has(right3)) {
subGraphOnHorizontal.get(right3).push(left3);
} else {
subGraphOnHorizontal.set(right3, [left3]);
}
} else {
var top2 = nodeToDummyForHorizontalAlignment.has(constraint.top) ? nodeToDummyForHorizontalAlignment.get(constraint.top) : constraint.top;
var bottom2 = nodeToDummyForHorizontalAlignment.has(constraint.bottom) ? nodeToDummyForHorizontalAlignment.get(constraint.bottom) : constraint.bottom;
if (subGraphOnVertical.has(top2)) {
subGraphOnVertical.get(top2).push(bottom2);
} else {
subGraphOnVertical.set(top2, [bottom2]);
}
if (subGraphOnVertical.has(bottom2)) {
subGraphOnVertical.get(bottom2).push(top2);
} else {
subGraphOnVertical.set(bottom2, [top2]);
}
}
});
var constructComponents = /* @__PURE__ */ __name(function constructComponents2(graph, fixedNodes) {
var components3 = [];
var isFixed = [];
var queue = new LinkedList();
var visited = /* @__PURE__ */ new Set();
var count2 = 0;
graph.forEach(function(value2, key) {
if (!visited.has(key)) {
components3[count2] = [];
isFixed[count2] = false;
var currentNode = key;
queue.push(currentNode);
visited.add(currentNode);
components3[count2].push(currentNode);
while (queue.length != 0) {
currentNode = queue.shift();
if (fixedNodes.has(currentNode)) {
isFixed[count2] = true;
}
var neighbors = graph.get(currentNode);
neighbors.forEach(function(neighbor) {
if (!visited.has(neighbor)) {
queue.push(neighbor);
visited.add(neighbor);
components3[count2].push(neighbor);
}
});
}
count2++;
}
});
return { components: components3, isFixed };
}, "constructComponents");
var resultOnHorizontal = constructComponents(subGraphOnHorizontal, self2.fixedNodesOnHorizontal);
this.componentsOnHorizontal = resultOnHorizontal.components;
this.fixedComponentsOnHorizontal = resultOnHorizontal.isFixed;
var resultOnVertical = constructComponents(subGraphOnVertical, self2.fixedNodesOnVertical);
this.componentsOnVertical = resultOnVertical.components;
this.fixedComponentsOnVertical = resultOnVertical.isFixed;
}
}
};
CoSELayout.prototype.updateDisplacements = function() {
var self2 = this;
if (this.constraints.fixedNodeConstraint) {
this.constraints.fixedNodeConstraint.forEach(function(nodeData2) {
var fixedNode = self2.idToNodeMap.get(nodeData2.nodeId);
fixedNode.displacementX = 0;
fixedNode.displacementY = 0;
});
}
if (this.constraints.alignmentConstraint) {
if (this.constraints.alignmentConstraint.vertical) {
var allVerticalAlignments = this.constraints.alignmentConstraint.vertical;
for (var i2 = 0; i2 < allVerticalAlignments.length; i2++) {
var totalDisplacementX = 0;
for (var j3 = 0; j3 < allVerticalAlignments[i2].length; j3++) {
if (this.fixedNodeSet.has(allVerticalAlignments[i2][j3])) {
totalDisplacementX = 0;
break;
}
totalDisplacementX += this.idToNodeMap.get(allVerticalAlignments[i2][j3]).displacementX;
}
var averageDisplacementX = totalDisplacementX / allVerticalAlignments[i2].length;
for (var j3 = 0; j3 < allVerticalAlignments[i2].length; j3++) {
this.idToNodeMap.get(allVerticalAlignments[i2][j3]).displacementX = averageDisplacementX;
}
}
}
if (this.constraints.alignmentConstraint.horizontal) {
var allHorizontalAlignments = this.constraints.alignmentConstraint.horizontal;
for (var i2 = 0; i2 < allHorizontalAlignments.length; i2++) {
var totalDisplacementY = 0;
for (var j3 = 0; j3 < allHorizontalAlignments[i2].length; j3++) {
if (this.fixedNodeSet.has(allHorizontalAlignments[i2][j3])) {
totalDisplacementY = 0;
break;
}
totalDisplacementY += this.idToNodeMap.get(allHorizontalAlignments[i2][j3]).displacementY;
}
var averageDisplacementY = totalDisplacementY / allHorizontalAlignments[i2].length;
for (var j3 = 0; j3 < allHorizontalAlignments[i2].length; j3++) {
this.idToNodeMap.get(allHorizontalAlignments[i2][j3]).displacementY = averageDisplacementY;
}
}
}
}
if (this.constraints.relativePlacementConstraint) {
if (CoSEConstants.RELAX_MOVEMENT_ON_CONSTRAINTS) {
if (this.totalIterations % 10 == 0) {
this.shuffle(this.nodesInRelativeHorizontal);
this.shuffle(this.nodesInRelativeVertical);
}
this.nodesInRelativeHorizontal.forEach(function(nodeId) {
if (!self2.fixedNodesOnHorizontal.has(nodeId)) {
var displacement = 0;
if (self2.dummyToNodeForVerticalAlignment.has(nodeId)) {
displacement = self2.idToNodeMap.get(self2.dummyToNodeForVerticalAlignment.get(nodeId)[0]).displacementX;
} else {
displacement = self2.idToNodeMap.get(nodeId).displacementX;
}
self2.nodeToRelativeConstraintMapHorizontal.get(nodeId).forEach(function(constraint) {
if (constraint.right) {
var diff2 = self2.nodeToTempPositionMapHorizontal.get(constraint.right) - self2.nodeToTempPositionMapHorizontal.get(nodeId) - displacement;
if (diff2 < constraint.gap) {
displacement -= constraint.gap - diff2;
}
} else {
var diff2 = self2.nodeToTempPositionMapHorizontal.get(nodeId) - self2.nodeToTempPositionMapHorizontal.get(constraint.left) + displacement;
if (diff2 < constraint.gap) {
displacement += constraint.gap - diff2;
}
}
});
self2.nodeToTempPositionMapHorizontal.set(nodeId, self2.nodeToTempPositionMapHorizontal.get(nodeId) + displacement);
if (self2.dummyToNodeForVerticalAlignment.has(nodeId)) {
self2.dummyToNodeForVerticalAlignment.get(nodeId).forEach(function(nodeId2) {
self2.idToNodeMap.get(nodeId2).displacementX = displacement;
});
} else {
self2.idToNodeMap.get(nodeId).displacementX = displacement;
}
}
});
this.nodesInRelativeVertical.forEach(function(nodeId) {
if (!self2.fixedNodesOnHorizontal.has(nodeId)) {
var displacement = 0;
if (self2.dummyToNodeForHorizontalAlignment.has(nodeId)) {
displacement = self2.idToNodeMap.get(self2.dummyToNodeForHorizontalAlignment.get(nodeId)[0]).displacementY;
} else {
displacement = self2.idToNodeMap.get(nodeId).displacementY;
}
self2.nodeToRelativeConstraintMapVertical.get(nodeId).forEach(function(constraint) {
if (constraint.bottom) {
var diff2 = self2.nodeToTempPositionMapVertical.get(constraint.bottom) - self2.nodeToTempPositionMapVertical.get(nodeId) - displacement;
if (diff2 < constraint.gap) {
displacement -= constraint.gap - diff2;
}
} else {
var diff2 = self2.nodeToTempPositionMapVertical.get(nodeId) - self2.nodeToTempPositionMapVertical.get(constraint.top) + displacement;
if (diff2 < constraint.gap) {
displacement += constraint.gap - diff2;
}
}
});
self2.nodeToTempPositionMapVertical.set(nodeId, self2.nodeToTempPositionMapVertical.get(nodeId) + displacement);
if (self2.dummyToNodeForHorizontalAlignment.has(nodeId)) {
self2.dummyToNodeForHorizontalAlignment.get(nodeId).forEach(function(nodeId2) {
self2.idToNodeMap.get(nodeId2).displacementY = displacement;
});
} else {
self2.idToNodeMap.get(nodeId).displacementY = displacement;
}
}
});
} else {
for (var i2 = 0; i2 < this.componentsOnHorizontal.length; i2++) {
var component2 = this.componentsOnHorizontal[i2];
if (this.fixedComponentsOnHorizontal[i2]) {
for (var j3 = 0; j3 < component2.length; j3++) {
if (this.dummyToNodeForVerticalAlignment.has(component2[j3])) {
this.dummyToNodeForVerticalAlignment.get(component2[j3]).forEach(function(nodeId) {
self2.idToNodeMap.get(nodeId).displacementX = 0;
});
} else {
this.idToNodeMap.get(component2[j3]).displacementX = 0;
}
}
} else {
var sum2 = 0;
var count2 = 0;
for (var j3 = 0; j3 < component2.length; j3++) {
if (this.dummyToNodeForVerticalAlignment.has(component2[j3])) {
var actualNodes = this.dummyToNodeForVerticalAlignment.get(component2[j3]);
sum2 += actualNodes.length * this.idToNodeMap.get(actualNodes[0]).displacementX;
count2 += actualNodes.length;
} else {
sum2 += this.idToNodeMap.get(component2[j3]).displacementX;
count2++;
}
}
var averageDisplacement = sum2 / count2;
for (var j3 = 0; j3 < component2.length; j3++) {
if (this.dummyToNodeForVerticalAlignment.has(component2[j3])) {
this.dummyToNodeForVerticalAlignment.get(component2[j3]).forEach(function(nodeId) {
self2.idToNodeMap.get(nodeId).displacementX = averageDisplacement;
});
} else {
this.idToNodeMap.get(component2[j3]).displacementX = averageDisplacement;
}
}
}
}
for (var i2 = 0; i2 < this.componentsOnVertical.length; i2++) {
var component2 = this.componentsOnVertical[i2];
if (this.fixedComponentsOnVertical[i2]) {
for (var j3 = 0; j3 < component2.length; j3++) {
if (this.dummyToNodeForHorizontalAlignment.has(component2[j3])) {
this.dummyToNodeForHorizontalAlignment.get(component2[j3]).forEach(function(nodeId) {
self2.idToNodeMap.get(nodeId).displacementY = 0;
});
} else {
this.idToNodeMap.get(component2[j3]).displacementY = 0;
}
}
} else {
var sum2 = 0;
var count2 = 0;
for (var j3 = 0; j3 < component2.length; j3++) {
if (this.dummyToNodeForHorizontalAlignment.has(component2[j3])) {
var actualNodes = this.dummyToNodeForHorizontalAlignment.get(component2[j3]);
sum2 += actualNodes.length * this.idToNodeMap.get(actualNodes[0]).displacementY;
count2 += actualNodes.length;
} else {
sum2 += this.idToNodeMap.get(component2[j3]).displacementY;
count2++;
}
}
var averageDisplacement = sum2 / count2;
for (var j3 = 0; j3 < component2.length; j3++) {
if (this.dummyToNodeForHorizontalAlignment.has(component2[j3])) {
this.dummyToNodeForHorizontalAlignment.get(component2[j3]).forEach(function(nodeId) {
self2.idToNodeMap.get(nodeId).displacementY = averageDisplacement;
});
} else {
this.idToNodeMap.get(component2[j3]).displacementY = averageDisplacement;
}
}
}
}
}
}
};
CoSELayout.prototype.calculateNodesToApplyGravitationTo = function() {
var nodeList = [];
var graph;
var graphs = this.graphManager.getGraphs();
var size4 = graphs.length;
var i2;
for (i2 = 0; i2 < size4; i2++) {
graph = graphs[i2];
graph.updateConnected();
if (!graph.isConnected) {
nodeList = nodeList.concat(graph.getNodes());
}
}
return nodeList;
};
CoSELayout.prototype.createBendpoints = function() {
var edges3 = [];
edges3 = edges3.concat(this.graphManager.getAllEdges());
var visited = /* @__PURE__ */ new Set();
var i2;
for (i2 = 0; i2 < edges3.length; i2++) {
var edge = edges3[i2];
if (!visited.has(edge)) {
var source = edge.getSource();
var target = edge.getTarget();
if (source == target) {
edge.getBendpoints().push(new PointD());
edge.getBendpoints().push(new PointD());
this.createDummyNodesForBendpoints(edge);
visited.add(edge);
} else {
var edgeList2 = [];
edgeList2 = edgeList2.concat(source.getEdgeListToNode(target));
edgeList2 = edgeList2.concat(target.getEdgeListToNode(source));
if (!visited.has(edgeList2[0])) {
if (edgeList2.length > 1) {
var k2;
for (k2 = 0; k2 < edgeList2.length; k2++) {
var multiEdge = edgeList2[k2];
multiEdge.getBendpoints().push(new PointD());
this.createDummyNodesForBendpoints(multiEdge);
}
}
edgeList2.forEach(function(edge2) {
visited.add(edge2);
});
}
}
}
if (visited.size == edges3.length) {
break;
}
}
};
CoSELayout.prototype.positionNodesRadially = function(forest) {
var currentStartingPoint = new Point3(0, 0);
var numberOfColumns = Math.ceil(Math.sqrt(forest.length));
var height2 = 0;
var currentY = 0;
var currentX = 0;
var point8 = new PointD(0, 0);
for (var i2 = 0; i2 < forest.length; i2++) {
if (i2 % numberOfColumns == 0) {
currentX = 0;
currentY = height2;
if (i2 != 0) {
currentY += CoSEConstants.DEFAULT_COMPONENT_SEPERATION;
}
height2 = 0;
}
var tree = forest[i2];
var centerNode = Layout2.findCenterOfTree(tree);
currentStartingPoint.x = currentX;
currentStartingPoint.y = currentY;
point8 = CoSELayout.radialLayout(tree, centerNode, currentStartingPoint);
if (point8.y > height2) {
height2 = Math.floor(point8.y);
}
currentX = Math.floor(point8.x + CoSEConstants.DEFAULT_COMPONENT_SEPERATION);
}
this.transform(new PointD(LayoutConstants.WORLD_CENTER_X - point8.x / 2, LayoutConstants.WORLD_CENTER_Y - point8.y / 2));
};
CoSELayout.radialLayout = function(tree, centerNode, startingPoint) {
var radialSep = Math.max(this.maxDiagonalInTree(tree), CoSEConstants.DEFAULT_RADIAL_SEPARATION);
CoSELayout.branchRadialLayout(centerNode, null, 0, 359, 0, radialSep);
var bounds4 = LGraph.calculateBounds(tree);
var transform8 = new Transform2();
transform8.setDeviceOrgX(bounds4.getMinX());
transform8.setDeviceOrgY(bounds4.getMinY());
transform8.setWorldOrgX(startingPoint.x);
transform8.setWorldOrgY(startingPoint.y);
for (var i2 = 0; i2 < tree.length; i2++) {
var node2 = tree[i2];
node2.transform(transform8);
}
var bottomRight = new PointD(bounds4.getMaxX(), bounds4.getMaxY());
return transform8.inverseTransformPoint(bottomRight);
};
CoSELayout.branchRadialLayout = function(node2, parentOfNode, startAngle, endAngle, distance3, radialSeparation) {
var halfInterval = (endAngle - startAngle + 1) / 2;
if (halfInterval < 0) {
halfInterval += 180;
}
var nodeAngle = (halfInterval + startAngle) % 360;
var teta = nodeAngle * IGeometry.TWO_PI / 360;
var cos_teta = Math.cos(teta);
var x_ = distance3 * Math.cos(teta);
var y_ = distance3 * Math.sin(teta);
node2.setCenter(x_, y_);
var neighborEdges = [];
neighborEdges = neighborEdges.concat(node2.getEdges());
var childCount = neighborEdges.length;
if (parentOfNode != null) {
childCount--;
}
var branchCount = 0;
var incEdgesCount = neighborEdges.length;
var startIndex;
var edges3 = node2.getEdgesBetween(parentOfNode);
while (edges3.length > 1) {
var temp = edges3[0];
edges3.splice(0, 1);
var index = neighborEdges.indexOf(temp);
if (index >= 0) {
neighborEdges.splice(index, 1);
}
incEdgesCount--;
childCount--;
}
if (parentOfNode != null) {
startIndex = (neighborEdges.indexOf(edges3[0]) + 1) % incEdgesCount;
} else {
startIndex = 0;
}
var stepAngle = Math.abs(endAngle - startAngle) / childCount;
for (var i2 = startIndex; branchCount != childCount; i2 = ++i2 % incEdgesCount) {
var currentNeighbor = neighborEdges[i2].getOtherEnd(node2);
if (currentNeighbor == parentOfNode) {
continue;
}
var childStartAngle = (startAngle + branchCount * stepAngle) % 360;
var childEndAngle = (childStartAngle + stepAngle) % 360;
CoSELayout.branchRadialLayout(currentNeighbor, node2, childStartAngle, childEndAngle, distance3 + radialSeparation, radialSeparation);
branchCount++;
}
};
CoSELayout.maxDiagonalInTree = function(tree) {
var maxDiagonal = Integer.MIN_VALUE;
for (var i2 = 0; i2 < tree.length; i2++) {
var node2 = tree[i2];
var diagonal = node2.getDiagonal();
if (diagonal > maxDiagonal) {
maxDiagonal = diagonal;
}
}
return maxDiagonal;
};
CoSELayout.prototype.calcRepulsionRange = function() {
return 2 * (this.level + 1) * this.idealEdgeLength;
};
CoSELayout.prototype.groupZeroDegreeMembers = function() {
var self2 = this;
var tempMemberGroups = {};
this.memberGroups = {};
this.idToDummyNode = {};
var zeroDegree = [];
var allNodes = this.graphManager.getAllNodes();
for (var i2 = 0; i2 < allNodes.length; i2++) {
var node2 = allNodes[i2];
var parent4 = node2.getParent();
if (this.getNodeDegreeWithChildren(node2) === 0 && (parent4.id == void 0 || !this.getToBeTiled(parent4))) {
zeroDegree.push(node2);
}
}
for (var i2 = 0; i2 < zeroDegree.length; i2++) {
var node2 = zeroDegree[i2];
var p_id = node2.getParent().id;
if (typeof tempMemberGroups[p_id] === "undefined") tempMemberGroups[p_id] = [];
tempMemberGroups[p_id] = tempMemberGroups[p_id].concat(node2);
}
Object.keys(tempMemberGroups).forEach(function(p_id2) {
if (tempMemberGroups[p_id2].length > 1) {
var dummyCompoundId = "DummyCompound_" + p_id2;
self2.memberGroups[dummyCompoundId] = tempMemberGroups[p_id2];
var parent5 = tempMemberGroups[p_id2][0].getParent();
var dummyCompound = new CoSENode(self2.graphManager);
dummyCompound.id = dummyCompoundId;
dummyCompound.paddingLeft = parent5.paddingLeft || 0;
dummyCompound.paddingRight = parent5.paddingRight || 0;
dummyCompound.paddingBottom = parent5.paddingBottom || 0;
dummyCompound.paddingTop = parent5.paddingTop || 0;
self2.idToDummyNode[dummyCompoundId] = dummyCompound;
var dummyParentGraph = self2.getGraphManager().add(self2.newGraph(), dummyCompound);
var parentGraph = parent5.getChild();
parentGraph.add(dummyCompound);
for (var i3 = 0; i3 < tempMemberGroups[p_id2].length; i3++) {
var node3 = tempMemberGroups[p_id2][i3];
parentGraph.remove(node3);
dummyParentGraph.add(node3);
}
}
});
};
CoSELayout.prototype.clearCompounds = function() {
var childGraphMap = {};
var idToNode = {};
this.performDFSOnCompounds();
for (var i2 = 0; i2 < this.compoundOrder.length; i2++) {
idToNode[this.compoundOrder[i2].id] = this.compoundOrder[i2];
childGraphMap[this.compoundOrder[i2].id] = [].concat(this.compoundOrder[i2].getChild().getNodes());
this.graphManager.remove(this.compoundOrder[i2].getChild());
this.compoundOrder[i2].child = null;
}
this.graphManager.resetAllNodes();
this.tileCompoundMembers(childGraphMap, idToNode);
};
CoSELayout.prototype.clearZeroDegreeMembers = function() {
var self2 = this;
var tiledZeroDegreePack = this.tiledZeroDegreePack = [];
Object.keys(this.memberGroups).forEach(function(id32) {
var compoundNode = self2.idToDummyNode[id32];
tiledZeroDegreePack[id32] = self2.tileNodes(self2.memberGroups[id32], compoundNode.paddingLeft + compoundNode.paddingRight);
compoundNode.rect.width = tiledZeroDegreePack[id32].width;
compoundNode.rect.height = tiledZeroDegreePack[id32].height;
compoundNode.setCenter(tiledZeroDegreePack[id32].centerX, tiledZeroDegreePack[id32].centerY);
compoundNode.labelMarginLeft = 0;
compoundNode.labelMarginTop = 0;
if (CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS) {
var width3 = compoundNode.rect.width;
var height2 = compoundNode.rect.height;
if (compoundNode.labelWidth) {
if (compoundNode.labelPosHorizontal == "left") {
compoundNode.rect.x -= compoundNode.labelWidth;
compoundNode.setWidth(width3 + compoundNode.labelWidth);
compoundNode.labelMarginLeft = compoundNode.labelWidth;
} else if (compoundNode.labelPosHorizontal == "center" && compoundNode.labelWidth > width3) {
compoundNode.rect.x -= (compoundNode.labelWidth - width3) / 2;
compoundNode.setWidth(compoundNode.labelWidth);
compoundNode.labelMarginLeft = (compoundNode.labelWidth - width3) / 2;
} else if (compoundNode.labelPosHorizontal == "right") {
compoundNode.setWidth(width3 + compoundNode.labelWidth);
}
}
if (compoundNode.labelHeight) {
if (compoundNode.labelPosVertical == "top") {
compoundNode.rect.y -= compoundNode.labelHeight;
compoundNode.setHeight(height2 + compoundNode.labelHeight);
compoundNode.labelMarginTop = compoundNode.labelHeight;
} else if (compoundNode.labelPosVertical == "center" && compoundNode.labelHeight > height2) {
compoundNode.rect.y -= (compoundNode.labelHeight - height2) / 2;
compoundNode.setHeight(compoundNode.labelHeight);
compoundNode.labelMarginTop = (compoundNode.labelHeight - height2) / 2;
} else if (compoundNode.labelPosVertical == "bottom") {
compoundNode.setHeight(height2 + compoundNode.labelHeight);
}
}
}
});
};
CoSELayout.prototype.repopulateCompounds = function() {
for (var i2 = this.compoundOrder.length - 1; i2 >= 0; i2--) {
var lCompoundNode = this.compoundOrder[i2];
var id32 = lCompoundNode.id;
var horizontalMargin = lCompoundNode.paddingLeft;
var verticalMargin = lCompoundNode.paddingTop;
var labelMarginLeft = lCompoundNode.labelMarginLeft;
var labelMarginTop = lCompoundNode.labelMarginTop;
this.adjustLocations(this.tiledMemberPack[id32], lCompoundNode.rect.x, lCompoundNode.rect.y, horizontalMargin, verticalMargin, labelMarginLeft, labelMarginTop);
}
};
CoSELayout.prototype.repopulateZeroDegreeMembers = function() {
var self2 = this;
var tiledPack = this.tiledZeroDegreePack;
Object.keys(tiledPack).forEach(function(id32) {
var compoundNode = self2.idToDummyNode[id32];
var horizontalMargin = compoundNode.paddingLeft;
var verticalMargin = compoundNode.paddingTop;
var labelMarginLeft = compoundNode.labelMarginLeft;
var labelMarginTop = compoundNode.labelMarginTop;
self2.adjustLocations(tiledPack[id32], compoundNode.rect.x, compoundNode.rect.y, horizontalMargin, verticalMargin, labelMarginLeft, labelMarginTop);
});
};
CoSELayout.prototype.getToBeTiled = function(node2) {
var id32 = node2.id;
if (this.toBeTiled[id32] != null) {
return this.toBeTiled[id32];
}
var childGraph = node2.getChild();
if (childGraph == null) {
this.toBeTiled[id32] = false;
return false;
}
var children2 = childGraph.getNodes();
for (var i2 = 0; i2 < children2.length; i2++) {
var theChild = children2[i2];
if (this.getNodeDegree(theChild) > 0) {
this.toBeTiled[id32] = false;
return false;
}
if (theChild.getChild() == null) {
this.toBeTiled[theChild.id] = false;
continue;
}
if (!this.getToBeTiled(theChild)) {
this.toBeTiled[id32] = false;
return false;
}
}
this.toBeTiled[id32] = true;
return true;
};
CoSELayout.prototype.getNodeDegree = function(node2) {
var id32 = node2.id;
var edges3 = node2.getEdges();
var degree = 0;
for (var i2 = 0; i2 < edges3.length; i2++) {
var edge = edges3[i2];
if (edge.getSource().id !== edge.getTarget().id) {
degree = degree + 1;
}
}
return degree;
};
CoSELayout.prototype.getNodeDegreeWithChildren = function(node2) {
var degree = this.getNodeDegree(node2);
if (node2.getChild() == null) {
return degree;
}
var children2 = node2.getChild().getNodes();
for (var i2 = 0; i2 < children2.length; i2++) {
var child = children2[i2];
degree += this.getNodeDegreeWithChildren(child);
}
return degree;
};
CoSELayout.prototype.performDFSOnCompounds = function() {
this.compoundOrder = [];
this.fillCompexOrderByDFS(this.graphManager.getRoot().getNodes());
};
CoSELayout.prototype.fillCompexOrderByDFS = function(children2) {
for (var i2 = 0; i2 < children2.length; i2++) {
var child = children2[i2];
if (child.getChild() != null) {
this.fillCompexOrderByDFS(child.getChild().getNodes());
}
if (this.getToBeTiled(child)) {
this.compoundOrder.push(child);
}
}
};
CoSELayout.prototype.adjustLocations = function(organization, x5, y6, compoundHorizontalMargin, compoundVerticalMargin, compoundLabelMarginLeft, compoundLabelMarginTop) {
x5 += compoundHorizontalMargin + compoundLabelMarginLeft;
y6 += compoundVerticalMargin + compoundLabelMarginTop;
var left3 = x5;
for (var i2 = 0; i2 < organization.rows.length; i2++) {
var row = organization.rows[i2];
x5 = left3;
var maxHeight = 0;
for (var j3 = 0; j3 < row.length; j3++) {
var lnode = row[j3];
lnode.rect.x = x5;
lnode.rect.y = y6;
x5 += lnode.rect.width + organization.horizontalPadding;
if (lnode.rect.height > maxHeight) maxHeight = lnode.rect.height;
}
y6 += maxHeight + organization.verticalPadding;
}
};
CoSELayout.prototype.tileCompoundMembers = function(childGraphMap, idToNode) {
var self2 = this;
this.tiledMemberPack = [];
Object.keys(childGraphMap).forEach(function(id32) {
var compoundNode = idToNode[id32];
self2.tiledMemberPack[id32] = self2.tileNodes(childGraphMap[id32], compoundNode.paddingLeft + compoundNode.paddingRight);
compoundNode.rect.width = self2.tiledMemberPack[id32].width;
compoundNode.rect.height = self2.tiledMemberPack[id32].height;
compoundNode.setCenter(self2.tiledMemberPack[id32].centerX, self2.tiledMemberPack[id32].centerY);
compoundNode.labelMarginLeft = 0;
compoundNode.labelMarginTop = 0;
if (CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS) {
var width3 = compoundNode.rect.width;
var height2 = compoundNode.rect.height;
if (compoundNode.labelWidth) {
if (compoundNode.labelPosHorizontal == "left") {
compoundNode.rect.x -= compoundNode.labelWidth;
compoundNode.setWidth(width3 + compoundNode.labelWidth);
compoundNode.labelMarginLeft = compoundNode.labelWidth;
} else if (compoundNode.labelPosHorizontal == "center" && compoundNode.labelWidth > width3) {
compoundNode.rect.x -= (compoundNode.labelWidth - width3) / 2;
compoundNode.setWidth(compoundNode.labelWidth);
compoundNode.labelMarginLeft = (compoundNode.labelWidth - width3) / 2;
} else if (compoundNode.labelPosHorizontal == "right") {
compoundNode.setWidth(width3 + compoundNode.labelWidth);
}
}
if (compoundNode.labelHeight) {
if (compoundNode.labelPosVertical == "top") {
compoundNode.rect.y -= compoundNode.labelHeight;
compoundNode.setHeight(height2 + compoundNode.labelHeight);
compoundNode.labelMarginTop = compoundNode.labelHeight;
} else if (compoundNode.labelPosVertical == "center" && compoundNode.labelHeight > height2) {
compoundNode.rect.y -= (compoundNode.labelHeight - height2) / 2;
compoundNode.setHeight(compoundNode.labelHeight);
compoundNode.labelMarginTop = (compoundNode.labelHeight - height2) / 2;
} else if (compoundNode.labelPosVertical == "bottom") {
compoundNode.setHeight(height2 + compoundNode.labelHeight);
}
}
}
});
};
CoSELayout.prototype.tileNodes = function(nodes5, minWidth) {
var horizontalOrg = this.tileNodesByFavoringDim(nodes5, minWidth, true);
var verticalOrg = this.tileNodesByFavoringDim(nodes5, minWidth, false);
var horizontalRatio = this.getOrgRatio(horizontalOrg);
var verticalRatio = this.getOrgRatio(verticalOrg);
var bestOrg;
if (verticalRatio < horizontalRatio) {
bestOrg = verticalOrg;
} else {
bestOrg = horizontalOrg;
}
return bestOrg;
};
CoSELayout.prototype.getOrgRatio = function(organization) {
var width3 = organization.width;
var height2 = organization.height;
var ratio = width3 / height2;
if (ratio < 1) {
ratio = 1 / ratio;
}
return ratio;
};
CoSELayout.prototype.calcIdealRowWidth = function(members, favorHorizontalDim) {
var verticalPadding = CoSEConstants.TILING_PADDING_VERTICAL;
var horizontalPadding = CoSEConstants.TILING_PADDING_HORIZONTAL;
var membersSize = members.length;
var totalWidth = 0;
var totalHeight = 0;
var maxWidth2 = 0;
members.forEach(function(node2) {
totalWidth += node2.getWidth();
totalHeight += node2.getHeight();
if (node2.getWidth() > maxWidth2) {
maxWidth2 = node2.getWidth();
}
});
var averageWidth = totalWidth / membersSize;
var averageHeight = totalHeight / membersSize;
var delta = Math.pow(verticalPadding - horizontalPadding, 2) + 4 * (averageWidth + horizontalPadding) * (averageHeight + verticalPadding) * membersSize;
var horizontalCountDouble = (horizontalPadding - verticalPadding + Math.sqrt(delta)) / (2 * (averageWidth + horizontalPadding));
var horizontalCount;
if (favorHorizontalDim) {
horizontalCount = Math.ceil(horizontalCountDouble);
if (horizontalCount == horizontalCountDouble) {
horizontalCount++;
}
} else {
horizontalCount = Math.floor(horizontalCountDouble);
}
var idealWidth = horizontalCount * (averageWidth + horizontalPadding) - horizontalPadding;
if (maxWidth2 > idealWidth) {
idealWidth = maxWidth2;
}
idealWidth += horizontalPadding * 2;
return idealWidth;
};
CoSELayout.prototype.tileNodesByFavoringDim = function(nodes5, minWidth, favorHorizontalDim) {
var verticalPadding = CoSEConstants.TILING_PADDING_VERTICAL;
var horizontalPadding = CoSEConstants.TILING_PADDING_HORIZONTAL;
var tilingCompareBy = CoSEConstants.TILING_COMPARE_BY;
var organization = {
rows: [],
rowWidth: [],
rowHeight: [],
width: 0,
height: minWidth,
// assume minHeight equals to minWidth
verticalPadding,
horizontalPadding,
centerX: 0,
centerY: 0
};
if (tilingCompareBy) {
organization.idealRowWidth = this.calcIdealRowWidth(nodes5, favorHorizontalDim);
}
var getNodeArea = /* @__PURE__ */ __name(function getNodeArea2(n2) {
return n2.rect.width * n2.rect.height;
}, "getNodeArea");
var areaCompareFcn = /* @__PURE__ */ __name(function areaCompareFcn2(n1, n2) {
return getNodeArea(n2) - getNodeArea(n1);
}, "areaCompareFcn");
nodes5.sort(function(n1, n2) {
var cmpBy = areaCompareFcn;
if (organization.idealRowWidth) {
cmpBy = tilingCompareBy;
return cmpBy(n1.id, n2.id);
}
return cmpBy(n1, n2);
});
var sumCenterX = 0;
var sumCenterY = 0;
for (var i2 = 0; i2 < nodes5.length; i2++) {
var lNode = nodes5[i2];
sumCenterX += lNode.getCenterX();
sumCenterY += lNode.getCenterY();
}
organization.centerX = sumCenterX / nodes5.length;
organization.centerY = sumCenterY / nodes5.length;
for (var i2 = 0; i2 < nodes5.length; i2++) {
var lNode = nodes5[i2];
if (organization.rows.length == 0) {
this.insertNodeToRow(organization, lNode, 0, minWidth);
} else if (this.canAddHorizontal(organization, lNode.rect.width, lNode.rect.height)) {
var rowIndex = organization.rows.length - 1;
if (!organization.idealRowWidth) {
rowIndex = this.getShortestRowIndex(organization);
}
this.insertNodeToRow(organization, lNode, rowIndex, minWidth);
} else {
this.insertNodeToRow(organization, lNode, organization.rows.length, minWidth);
}
this.shiftToLastRow(organization);
}
return organization;
};
CoSELayout.prototype.insertNodeToRow = function(organization, node2, rowIndex, minWidth) {
var minCompoundSize = minWidth;
if (rowIndex == organization.rows.length) {
var secondDimension = [];
organization.rows.push(secondDimension);
organization.rowWidth.push(minCompoundSize);
organization.rowHeight.push(0);
}
var w4 = organization.rowWidth[rowIndex] + node2.rect.width;
if (organization.rows[rowIndex].length > 0) {
w4 += organization.horizontalPadding;
}
organization.rowWidth[rowIndex] = w4;
if (organization.width < w4) {
organization.width = w4;
}
var h3 = node2.rect.height;
if (rowIndex > 0) h3 += organization.verticalPadding;
var extraHeight = 0;
if (h3 > organization.rowHeight[rowIndex]) {
extraHeight = organization.rowHeight[rowIndex];
organization.rowHeight[rowIndex] = h3;
extraHeight = organization.rowHeight[rowIndex] - extraHeight;
}
organization.height += extraHeight;
organization.rows[rowIndex].push(node2);
};
CoSELayout.prototype.getShortestRowIndex = function(organization) {
var r2 = -1;
var min9 = Number.MAX_VALUE;
for (var i2 = 0; i2 < organization.rows.length; i2++) {
if (organization.rowWidth[i2] < min9) {
r2 = i2;
min9 = organization.rowWidth[i2];
}
}
return r2;
};
CoSELayout.prototype.getLongestRowIndex = function(organization) {
var r2 = -1;
var max10 = Number.MIN_VALUE;
for (var i2 = 0; i2 < organization.rows.length; i2++) {
if (organization.rowWidth[i2] > max10) {
r2 = i2;
max10 = organization.rowWidth[i2];
}
}
return r2;
};
CoSELayout.prototype.canAddHorizontal = function(organization, extraWidth, extraHeight) {
if (organization.idealRowWidth) {
var lastRowIndex = organization.rows.length - 1;
var lastRowWidth = organization.rowWidth[lastRowIndex];
return lastRowWidth + extraWidth + organization.horizontalPadding <= organization.idealRowWidth;
}
var sri = this.getShortestRowIndex(organization);
if (sri < 0) {
return true;
}
var min9 = organization.rowWidth[sri];
if (min9 + organization.horizontalPadding + extraWidth <= organization.width) return true;
var hDiff = 0;
if (organization.rowHeight[sri] < extraHeight) {
if (sri > 0) hDiff = extraHeight + organization.verticalPadding - organization.rowHeight[sri];
}
var add_to_row_ratio;
if (organization.width - min9 >= extraWidth + organization.horizontalPadding) {
add_to_row_ratio = (organization.height + hDiff) / (min9 + extraWidth + organization.horizontalPadding);
} else {
add_to_row_ratio = (organization.height + hDiff) / organization.width;
}
hDiff = extraHeight + organization.verticalPadding;
var add_new_row_ratio;
if (organization.width < extraWidth) {
add_new_row_ratio = (organization.height + hDiff) / extraWidth;
} else {
add_new_row_ratio = (organization.height + hDiff) / organization.width;
}
if (add_new_row_ratio < 1) add_new_row_ratio = 1 / add_new_row_ratio;
if (add_to_row_ratio < 1) add_to_row_ratio = 1 / add_to_row_ratio;
return add_to_row_ratio < add_new_row_ratio;
};
CoSELayout.prototype.shiftToLastRow = function(organization) {
var longest = this.getLongestRowIndex(organization);
var last3 = organization.rowWidth.length - 1;
var row = organization.rows[longest];
var node2 = row[row.length - 1];
var diff2 = node2.width + organization.horizontalPadding;
if (organization.width - organization.rowWidth[last3] > diff2 && longest != last3) {
row.splice(-1, 1);
organization.rows[last3].push(node2);
organization.rowWidth[longest] = organization.rowWidth[longest] - diff2;
organization.rowWidth[last3] = organization.rowWidth[last3] + diff2;
organization.width = organization.rowWidth[instance.getLongestRowIndex(organization)];
var maxHeight = Number.MIN_VALUE;
for (var i2 = 0; i2 < row.length; i2++) {
if (row[i2].height > maxHeight) maxHeight = row[i2].height;
}
if (longest > 0) maxHeight += organization.verticalPadding;
var prevTotal = organization.rowHeight[longest] + organization.rowHeight[last3];
organization.rowHeight[longest] = maxHeight;
if (organization.rowHeight[last3] < node2.height + organization.verticalPadding) organization.rowHeight[last3] = node2.height + organization.verticalPadding;
var finalTotal = organization.rowHeight[longest] + organization.rowHeight[last3];
organization.height += finalTotal - prevTotal;
this.shiftToLastRow(organization);
}
};
CoSELayout.prototype.tilingPreLayout = function() {
if (CoSEConstants.TILE) {
this.groupZeroDegreeMembers();
this.clearCompounds();
this.clearZeroDegreeMembers();
}
};
CoSELayout.prototype.tilingPostLayout = function() {
if (CoSEConstants.TILE) {
this.repopulateZeroDegreeMembers();
this.repopulateCompounds();
}
};
CoSELayout.prototype.reduceTrees = function() {
var prunedNodesAll = [];
var containsLeaf = true;
var node2;
while (containsLeaf) {
var allNodes = this.graphManager.getAllNodes();
var prunedNodesInStepTemp = [];
containsLeaf = false;
for (var i2 = 0; i2 < allNodes.length; i2++) {
node2 = allNodes[i2];
if (node2.getEdges().length == 1 && !node2.getEdges()[0].isInterGraph && node2.getChild() == null) {
if (CoSEConstants.PURE_INCREMENTAL) {
var otherEnd = node2.getEdges()[0].getOtherEnd(node2);
var relativePosition2 = new DimensionD2(node2.getCenterX() - otherEnd.getCenterX(), node2.getCenterY() - otherEnd.getCenterY());
prunedNodesInStepTemp.push([node2, node2.getEdges()[0], node2.getOwner(), relativePosition2]);
} else {
prunedNodesInStepTemp.push([node2, node2.getEdges()[0], node2.getOwner()]);
}
containsLeaf = true;
}
}
if (containsLeaf == true) {
var prunedNodesInStep = [];
for (var j3 = 0; j3 < prunedNodesInStepTemp.length; j3++) {
if (prunedNodesInStepTemp[j3][0].getEdges().length == 1) {
prunedNodesInStep.push(prunedNodesInStepTemp[j3]);
prunedNodesInStepTemp[j3][0].getOwner().remove(prunedNodesInStepTemp[j3][0]);
}
}
prunedNodesAll.push(prunedNodesInStep);
this.graphManager.resetAllNodes();
this.graphManager.resetAllEdges();
}
}
this.prunedNodesAll = prunedNodesAll;
};
CoSELayout.prototype.growTree = function(prunedNodesAll) {
var lengthOfPrunedNodesInStep = prunedNodesAll.length;
var prunedNodesInStep = prunedNodesAll[lengthOfPrunedNodesInStep - 1];
var nodeData2;
for (var i2 = 0; i2 < prunedNodesInStep.length; i2++) {
nodeData2 = prunedNodesInStep[i2];
this.findPlaceforPrunedNode(nodeData2);
nodeData2[2].add(nodeData2[0]);
nodeData2[2].add(nodeData2[1], nodeData2[1].source, nodeData2[1].target);
}
prunedNodesAll.splice(prunedNodesAll.length - 1, 1);
this.graphManager.resetAllNodes();
this.graphManager.resetAllEdges();
};
CoSELayout.prototype.findPlaceforPrunedNode = function(nodeData2) {
var gridForPrunedNode;
var nodeToConnect;
var prunedNode = nodeData2[0];
if (prunedNode == nodeData2[1].source) {
nodeToConnect = nodeData2[1].target;
} else {
nodeToConnect = nodeData2[1].source;
}
if (CoSEConstants.PURE_INCREMENTAL) {
prunedNode.setCenter(nodeToConnect.getCenterX() + nodeData2[3].getWidth(), nodeToConnect.getCenterY() + nodeData2[3].getHeight());
} else {
var startGridX = nodeToConnect.startX;
var finishGridX = nodeToConnect.finishX;
var startGridY = nodeToConnect.startY;
var finishGridY = nodeToConnect.finishY;
var upNodeCount = 0;
var downNodeCount = 0;
var rightNodeCount = 0;
var leftNodeCount = 0;
var controlRegions = [upNodeCount, rightNodeCount, downNodeCount, leftNodeCount];
if (startGridY > 0) {
for (var i2 = startGridX; i2 <= finishGridX; i2++) {
controlRegions[0] += this.grid[i2][startGridY - 1].length + this.grid[i2][startGridY].length - 1;
}
}
if (finishGridX < this.grid.length - 1) {
for (var i2 = startGridY; i2 <= finishGridY; i2++) {
controlRegions[1] += this.grid[finishGridX + 1][i2].length + this.grid[finishGridX][i2].length - 1;
}
}
if (finishGridY < this.grid[0].length - 1) {
for (var i2 = startGridX; i2 <= finishGridX; i2++) {
controlRegions[2] += this.grid[i2][finishGridY + 1].length + this.grid[i2][finishGridY].length - 1;
}
}
if (startGridX > 0) {
for (var i2 = startGridY; i2 <= finishGridY; i2++) {
controlRegions[3] += this.grid[startGridX - 1][i2].length + this.grid[startGridX][i2].length - 1;
}
}
var min9 = Integer.MAX_VALUE;
var minCount;
var minIndex;
for (var j3 = 0; j3 < controlRegions.length; j3++) {
if (controlRegions[j3] < min9) {
min9 = controlRegions[j3];
minCount = 1;
minIndex = j3;
} else if (controlRegions[j3] == min9) {
minCount++;
}
}
if (minCount == 3 && min9 == 0) {
if (controlRegions[0] == 0 && controlRegions[1] == 0 && controlRegions[2] == 0) {
gridForPrunedNode = 1;
} else if (controlRegions[0] == 0 && controlRegions[1] == 0 && controlRegions[3] == 0) {
gridForPrunedNode = 0;
} else if (controlRegions[0] == 0 && controlRegions[2] == 0 && controlRegions[3] == 0) {
gridForPrunedNode = 3;
} else if (controlRegions[1] == 0 && controlRegions[2] == 0 && controlRegions[3] == 0) {
gridForPrunedNode = 2;
}
} else if (minCount == 2 && min9 == 0) {
var random2 = Math.floor(Math.random() * 2);
if (controlRegions[0] == 0 && controlRegions[1] == 0) {
;
if (random2 == 0) {
gridForPrunedNode = 0;
} else {
gridForPrunedNode = 1;
}
} else if (controlRegions[0] == 0 && controlRegions[2] == 0) {
if (random2 == 0) {
gridForPrunedNode = 0;
} else {
gridForPrunedNode = 2;
}
} else if (controlRegions[0] == 0 && controlRegions[3] == 0) {
if (random2 == 0) {
gridForPrunedNode = 0;
} else {
gridForPrunedNode = 3;
}
} else if (controlRegions[1] == 0 && controlRegions[2] == 0) {
if (random2 == 0) {
gridForPrunedNode = 1;
} else {
gridForPrunedNode = 2;
}
} else if (controlRegions[1] == 0 && controlRegions[3] == 0) {
if (random2 == 0) {
gridForPrunedNode = 1;
} else {
gridForPrunedNode = 3;
}
} else {
if (random2 == 0) {
gridForPrunedNode = 2;
} else {
gridForPrunedNode = 3;
}
}
} else if (minCount == 4 && min9 == 0) {
var random2 = Math.floor(Math.random() * 4);
gridForPrunedNode = random2;
} else {
gridForPrunedNode = minIndex;
}
if (gridForPrunedNode == 0) {
prunedNode.setCenter(nodeToConnect.getCenterX(), nodeToConnect.getCenterY() - nodeToConnect.getHeight() / 2 - FDLayoutConstants.DEFAULT_EDGE_LENGTH - prunedNode.getHeight() / 2);
} else if (gridForPrunedNode == 1) {
prunedNode.setCenter(nodeToConnect.getCenterX() + nodeToConnect.getWidth() / 2 + FDLayoutConstants.DEFAULT_EDGE_LENGTH + prunedNode.getWidth() / 2, nodeToConnect.getCenterY());
} else if (gridForPrunedNode == 2) {
prunedNode.setCenter(nodeToConnect.getCenterX(), nodeToConnect.getCenterY() + nodeToConnect.getHeight() / 2 + FDLayoutConstants.DEFAULT_EDGE_LENGTH + prunedNode.getHeight() / 2);
} else {
prunedNode.setCenter(nodeToConnect.getCenterX() - nodeToConnect.getWidth() / 2 - FDLayoutConstants.DEFAULT_EDGE_LENGTH - prunedNode.getWidth() / 2, nodeToConnect.getCenterY());
}
}
};
module3.exports = CoSELayout;
})
),
/***/
991: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var FDLayoutNode = __webpack_require__2(551).FDLayoutNode;
var IMath = __webpack_require__2(551).IMath;
function CoSENode(gm, loc, size4, vNode) {
FDLayoutNode.call(this, gm, loc, size4, vNode);
}
__name(CoSENode, "CoSENode");
CoSENode.prototype = Object.create(FDLayoutNode.prototype);
for (var prop in FDLayoutNode) {
CoSENode[prop] = FDLayoutNode[prop];
}
CoSENode.prototype.calculateDisplacement = function() {
var layout7 = this.graphManager.getLayout();
if (this.getChild() != null && this.fixedNodeWeight) {
this.displacementX += layout7.coolingFactor * (this.springForceX + this.repulsionForceX + this.gravitationForceX) / this.fixedNodeWeight;
this.displacementY += layout7.coolingFactor * (this.springForceY + this.repulsionForceY + this.gravitationForceY) / this.fixedNodeWeight;
} else {
this.displacementX += layout7.coolingFactor * (this.springForceX + this.repulsionForceX + this.gravitationForceX) / this.noOfChildren;
this.displacementY += layout7.coolingFactor * (this.springForceY + this.repulsionForceY + this.gravitationForceY) / this.noOfChildren;
}
if (Math.abs(this.displacementX) > layout7.coolingFactor * layout7.maxNodeDisplacement) {
this.displacementX = layout7.coolingFactor * layout7.maxNodeDisplacement * IMath.sign(this.displacementX);
}
if (Math.abs(this.displacementY) > layout7.coolingFactor * layout7.maxNodeDisplacement) {
this.displacementY = layout7.coolingFactor * layout7.maxNodeDisplacement * IMath.sign(this.displacementY);
}
if (this.child && this.child.getNodes().length > 0) {
this.propogateDisplacementToChildren(this.displacementX, this.displacementY);
}
};
CoSENode.prototype.propogateDisplacementToChildren = function(dX, dY) {
var nodes5 = this.getChild().getNodes();
var node2;
for (var i2 = 0; i2 < nodes5.length; i2++) {
node2 = nodes5[i2];
if (node2.getChild() == null) {
node2.displacementX += dX;
node2.displacementY += dY;
} else {
node2.propogateDisplacementToChildren(dX, dY);
}
}
};
CoSENode.prototype.move = function() {
var layout7 = this.graphManager.getLayout();
if (this.child == null || this.child.getNodes().length == 0) {
this.moveBy(this.displacementX, this.displacementY);
layout7.totalDisplacement += Math.abs(this.displacementX) + Math.abs(this.displacementY);
}
this.springForceX = 0;
this.springForceY = 0;
this.repulsionForceX = 0;
this.repulsionForceY = 0;
this.gravitationForceX = 0;
this.gravitationForceY = 0;
this.displacementX = 0;
this.displacementY = 0;
};
CoSENode.prototype.setPred1 = function(pred12) {
this.pred1 = pred12;
};
CoSENode.prototype.getPred1 = function() {
return pred1;
};
CoSENode.prototype.getPred2 = function() {
return pred2;
};
CoSENode.prototype.setNext = function(next3) {
this.next = next3;
};
CoSENode.prototype.getNext = function() {
return next;
};
CoSENode.prototype.setProcessed = function(processed2) {
this.processed = processed2;
};
CoSENode.prototype.isProcessed = function() {
return processed;
};
module3.exports = CoSENode;
})
),
/***/
902: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
function _toConsumableArray2(arr) {
if (Array.isArray(arr)) {
for (var i2 = 0, arr2 = Array(arr.length); i2 < arr.length; i2++) {
arr2[i2] = arr[i2];
}
return arr2;
} else {
return Array.from(arr);
}
}
__name(_toConsumableArray2, "_toConsumableArray");
var CoSEConstants = __webpack_require__2(806);
var LinkedList = __webpack_require__2(551).LinkedList;
var Matrix = __webpack_require__2(551).Matrix;
var SVD = __webpack_require__2(551).SVD;
function ConstraintHandler() {
}
__name(ConstraintHandler, "ConstraintHandler");
ConstraintHandler.handleConstraints = function(layout7) {
var constraints = {};
constraints.fixedNodeConstraint = layout7.constraints.fixedNodeConstraint;
constraints.alignmentConstraint = layout7.constraints.alignmentConstraint;
constraints.relativePlacementConstraint = layout7.constraints.relativePlacementConstraint;
var idToNodeMap = /* @__PURE__ */ new Map();
var nodeIndexes = /* @__PURE__ */ new Map();
var xCoords = [];
var yCoords = [];
var allNodes = layout7.getAllNodes();
var index = 0;
for (var i2 = 0; i2 < allNodes.length; i2++) {
var node2 = allNodes[i2];
if (node2.getChild() == null) {
nodeIndexes.set(node2.id, index++);
xCoords.push(node2.getCenterX());
yCoords.push(node2.getCenterY());
idToNodeMap.set(node2.id, node2);
}
}
if (constraints.relativePlacementConstraint) {
constraints.relativePlacementConstraint.forEach(function(constraint) {
if (!constraint.gap && constraint.gap != 0) {
if (constraint.left) {
constraint.gap = CoSEConstants.DEFAULT_EDGE_LENGTH + idToNodeMap.get(constraint.left).getWidth() / 2 + idToNodeMap.get(constraint.right).getWidth() / 2;
} else {
constraint.gap = CoSEConstants.DEFAULT_EDGE_LENGTH + idToNodeMap.get(constraint.top).getHeight() / 2 + idToNodeMap.get(constraint.bottom).getHeight() / 2;
}
}
});
}
var calculatePositionDiff = /* @__PURE__ */ __name(function calculatePositionDiff2(pos1, pos2) {
return { x: pos1.x - pos2.x, y: pos1.y - pos2.y };
}, "calculatePositionDiff");
var calculateAvgPosition = /* @__PURE__ */ __name(function calculateAvgPosition2(nodeIdSet) {
var xPosSum = 0;
var yPosSum = 0;
nodeIdSet.forEach(function(nodeId) {
xPosSum += xCoords[nodeIndexes.get(nodeId)];
yPosSum += yCoords[nodeIndexes.get(nodeId)];
});
return { x: xPosSum / nodeIdSet.size, y: yPosSum / nodeIdSet.size };
}, "calculateAvgPosition");
var findAppropriatePositionForRelativePlacement = /* @__PURE__ */ __name(function findAppropriatePositionForRelativePlacement2(graph, direction, fixedNodes2, dummyPositions, componentSources) {
function setUnion(setA, setB) {
var union2 = new Set(setA);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = void 0;
try {
for (var _iterator = setB[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var elem = _step.value;
union2.add(elem);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return union2;
}
__name(setUnion, "setUnion");
var inDegrees = /* @__PURE__ */ new Map();
graph.forEach(function(value2, key) {
inDegrees.set(key, 0);
});
graph.forEach(function(value2, key) {
value2.forEach(function(adjacent) {
inDegrees.set(adjacent.id, inDegrees.get(adjacent.id) + 1);
});
});
var positionMap = /* @__PURE__ */ new Map();
var pastMap = /* @__PURE__ */ new Map();
var queue = new LinkedList();
inDegrees.forEach(function(value2, key) {
if (value2 == 0) {
queue.push(key);
if (!fixedNodes2) {
if (direction == "horizontal") {
positionMap.set(key, nodeIndexes.has(key) ? xCoords[nodeIndexes.get(key)] : dummyPositions.get(key));
} else {
positionMap.set(key, nodeIndexes.has(key) ? yCoords[nodeIndexes.get(key)] : dummyPositions.get(key));
}
}
} else {
positionMap.set(key, Number.NEGATIVE_INFINITY);
}
if (fixedNodes2) {
pastMap.set(key, /* @__PURE__ */ new Set([key]));
}
});
if (fixedNodes2) {
componentSources.forEach(function(component2) {
var fixedIds = [];
component2.forEach(function(nodeId) {
if (fixedNodes2.has(nodeId)) {
fixedIds.push(nodeId);
}
});
if (fixedIds.length > 0) {
var position5 = 0;
fixedIds.forEach(function(fixedId) {
if (direction == "horizontal") {
positionMap.set(fixedId, nodeIndexes.has(fixedId) ? xCoords[nodeIndexes.get(fixedId)] : dummyPositions.get(fixedId));
position5 += positionMap.get(fixedId);
} else {
positionMap.set(fixedId, nodeIndexes.has(fixedId) ? yCoords[nodeIndexes.get(fixedId)] : dummyPositions.get(fixedId));
position5 += positionMap.get(fixedId);
}
});
position5 = position5 / fixedIds.length;
component2.forEach(function(nodeId) {
if (!fixedNodes2.has(nodeId)) {
positionMap.set(nodeId, position5);
}
});
} else {
var _position = 0;
component2.forEach(function(nodeId) {
if (direction == "horizontal") {
_position += nodeIndexes.has(nodeId) ? xCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);
} else {
_position += nodeIndexes.has(nodeId) ? yCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);
}
});
_position = _position / component2.length;
component2.forEach(function(nodeId) {
positionMap.set(nodeId, _position);
});
}
});
}
var _loop = /* @__PURE__ */ __name(function _loop2() {
var currentNode = queue.shift();
var neighbors = graph.get(currentNode);
neighbors.forEach(function(neighbor) {
if (positionMap.get(neighbor.id) < positionMap.get(currentNode) + neighbor.gap) {
if (fixedNodes2 && fixedNodes2.has(neighbor.id)) {
var fixedPosition = void 0;
if (direction == "horizontal") {
fixedPosition = nodeIndexes.has(neighbor.id) ? xCoords[nodeIndexes.get(neighbor.id)] : dummyPositions.get(neighbor.id);
} else {
fixedPosition = nodeIndexes.has(neighbor.id) ? yCoords[nodeIndexes.get(neighbor.id)] : dummyPositions.get(neighbor.id);
}
positionMap.set(neighbor.id, fixedPosition);
if (fixedPosition < positionMap.get(currentNode) + neighbor.gap) {
var diff2 = positionMap.get(currentNode) + neighbor.gap - fixedPosition;
pastMap.get(currentNode).forEach(function(nodeId) {
positionMap.set(nodeId, positionMap.get(nodeId) - diff2);
});
}
} else {
positionMap.set(neighbor.id, positionMap.get(currentNode) + neighbor.gap);
}
}
inDegrees.set(neighbor.id, inDegrees.get(neighbor.id) - 1);
if (inDegrees.get(neighbor.id) == 0) {
queue.push(neighbor.id);
}
if (fixedNodes2) {
pastMap.set(neighbor.id, setUnion(pastMap.get(currentNode), pastMap.get(neighbor.id)));
}
});
}, "_loop");
while (queue.length != 0) {
_loop();
}
if (fixedNodes2) {
var sinkNodes = /* @__PURE__ */ new Set();
graph.forEach(function(value2, key) {
if (value2.length == 0) {
sinkNodes.add(key);
}
});
var _components = [];
pastMap.forEach(function(value2, key) {
if (sinkNodes.has(key)) {
var isFixedComponent = false;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = void 0;
try {
for (var _iterator2 = value2[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var nodeId = _step2.value;
if (fixedNodes2.has(nodeId)) {
isFixedComponent = true;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
if (!isFixedComponent) {
var isExist = false;
var existAt = void 0;
_components.forEach(function(component2, index2) {
if (component2.has([].concat(_toConsumableArray2(value2))[0])) {
isExist = true;
existAt = index2;
}
});
if (!isExist) {
_components.push(new Set(value2));
} else {
value2.forEach(function(ele) {
_components[existAt].add(ele);
});
}
}
}
});
_components.forEach(function(component2, index2) {
var minBefore = Number.POSITIVE_INFINITY;
var minAfter = Number.POSITIVE_INFINITY;
var maxBefore = Number.NEGATIVE_INFINITY;
var maxAfter = Number.NEGATIVE_INFINITY;
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = void 0;
try {
for (var _iterator3 = component2[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var nodeId = _step3.value;
var posBefore = void 0;
if (direction == "horizontal") {
posBefore = nodeIndexes.has(nodeId) ? xCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);
} else {
posBefore = nodeIndexes.has(nodeId) ? yCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);
}
var posAfter = positionMap.get(nodeId);
if (posBefore < minBefore) {
minBefore = posBefore;
}
if (posBefore > maxBefore) {
maxBefore = posBefore;
}
if (posAfter < minAfter) {
minAfter = posAfter;
}
if (posAfter > maxAfter) {
maxAfter = posAfter;
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
var diff2 = (minBefore + maxBefore) / 2 - (minAfter + maxAfter) / 2;
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = void 0;
try {
for (var _iterator4 = component2[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var _nodeId = _step4.value;
positionMap.set(_nodeId, positionMap.get(_nodeId) + diff2);
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
});
}
return positionMap;
}, "findAppropriatePositionForRelativePlacement");
var applyReflectionForRelativePlacement = /* @__PURE__ */ __name(function applyReflectionForRelativePlacement2(relativePlacementConstraints) {
var reflectOnY = 0, notReflectOnY = 0;
var reflectOnX = 0, notReflectOnX = 0;
relativePlacementConstraints.forEach(function(constraint) {
if (constraint.left) {
xCoords[nodeIndexes.get(constraint.left)] - xCoords[nodeIndexes.get(constraint.right)] >= 0 ? reflectOnY++ : notReflectOnY++;
} else {
yCoords[nodeIndexes.get(constraint.top)] - yCoords[nodeIndexes.get(constraint.bottom)] >= 0 ? reflectOnX++ : notReflectOnX++;
}
});
if (reflectOnY > notReflectOnY && reflectOnX > notReflectOnX) {
for (var _i = 0; _i < nodeIndexes.size; _i++) {
xCoords[_i] = -1 * xCoords[_i];
yCoords[_i] = -1 * yCoords[_i];
}
} else if (reflectOnY > notReflectOnY) {
for (var _i2 = 0; _i2 < nodeIndexes.size; _i2++) {
xCoords[_i2] = -1 * xCoords[_i2];
}
} else if (reflectOnX > notReflectOnX) {
for (var _i3 = 0; _i3 < nodeIndexes.size; _i3++) {
yCoords[_i3] = -1 * yCoords[_i3];
}
}
}, "applyReflectionForRelativePlacement");
var findComponents = /* @__PURE__ */ __name(function findComponents2(graph) {
var components4 = [];
var queue = new LinkedList();
var visited = /* @__PURE__ */ new Set();
var count2 = 0;
graph.forEach(function(value2, key) {
if (!visited.has(key)) {
components4[count2] = [];
var _currentNode = key;
queue.push(_currentNode);
visited.add(_currentNode);
components4[count2].push(_currentNode);
while (queue.length != 0) {
_currentNode = queue.shift();
var neighbors = graph.get(_currentNode);
neighbors.forEach(function(neighbor) {
if (!visited.has(neighbor.id)) {
queue.push(neighbor.id);
visited.add(neighbor.id);
components4[count2].push(neighbor.id);
}
});
}
count2++;
}
});
return components4;
}, "findComponents");
var dagToUndirected = /* @__PURE__ */ __name(function dagToUndirected2(dag2) {
var undirected = /* @__PURE__ */ new Map();
dag2.forEach(function(value2, key) {
undirected.set(key, []);
});
dag2.forEach(function(value2, key) {
value2.forEach(function(adjacent) {
undirected.get(key).push(adjacent);
undirected.get(adjacent.id).push({ id: key, gap: adjacent.gap, direction: adjacent.direction });
});
});
return undirected;
}, "dagToUndirected");
var dagToReversed = /* @__PURE__ */ __name(function dagToReversed2(dag2) {
var reversed = /* @__PURE__ */ new Map();
dag2.forEach(function(value2, key) {
reversed.set(key, []);
});
dag2.forEach(function(value2, key) {
value2.forEach(function(adjacent) {
reversed.get(adjacent.id).push({ id: key, gap: adjacent.gap, direction: adjacent.direction });
});
});
return reversed;
}, "dagToReversed");
var targetMatrix = [];
var sourceMatrix = [];
var standardTransformation = false;
var reflectionType = false;
var fixedNodes = /* @__PURE__ */ new Set();
var dag = /* @__PURE__ */ new Map();
var dagUndirected = /* @__PURE__ */ new Map();
var components3 = [];
if (constraints.fixedNodeConstraint) {
constraints.fixedNodeConstraint.forEach(function(nodeData2) {
fixedNodes.add(nodeData2.nodeId);
});
}
if (constraints.relativePlacementConstraint) {
constraints.relativePlacementConstraint.forEach(function(constraint) {
if (constraint.left) {
if (dag.has(constraint.left)) {
dag.get(constraint.left).push({ id: constraint.right, gap: constraint.gap, direction: "horizontal" });
} else {
dag.set(constraint.left, [{ id: constraint.right, gap: constraint.gap, direction: "horizontal" }]);
}
if (!dag.has(constraint.right)) {
dag.set(constraint.right, []);
}
} else {
if (dag.has(constraint.top)) {
dag.get(constraint.top).push({ id: constraint.bottom, gap: constraint.gap, direction: "vertical" });
} else {
dag.set(constraint.top, [{ id: constraint.bottom, gap: constraint.gap, direction: "vertical" }]);
}
if (!dag.has(constraint.bottom)) {
dag.set(constraint.bottom, []);
}
}
});
dagUndirected = dagToUndirected(dag);
components3 = findComponents(dagUndirected);
}
if (CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING) {
if (constraints.fixedNodeConstraint && constraints.fixedNodeConstraint.length > 1) {
constraints.fixedNodeConstraint.forEach(function(nodeData2, i3) {
targetMatrix[i3] = [nodeData2.position.x, nodeData2.position.y];
sourceMatrix[i3] = [xCoords[nodeIndexes.get(nodeData2.nodeId)], yCoords[nodeIndexes.get(nodeData2.nodeId)]];
});
standardTransformation = true;
} else if (constraints.alignmentConstraint) {
(function() {
var count2 = 0;
if (constraints.alignmentConstraint.vertical) {
var verticalAlign = constraints.alignmentConstraint.vertical;
var _loop2 = /* @__PURE__ */ __name(function _loop22(_i42) {
var alignmentSet = /* @__PURE__ */ new Set();
verticalAlign[_i42].forEach(function(nodeId) {
alignmentSet.add(nodeId);
});
var intersection4 = new Set([].concat(_toConsumableArray2(alignmentSet)).filter(function(x5) {
return fixedNodes.has(x5);
}));
var xPos = void 0;
if (intersection4.size > 0) xPos = xCoords[nodeIndexes.get(intersection4.values().next().value)];
else xPos = calculateAvgPosition(alignmentSet).x;
verticalAlign[_i42].forEach(function(nodeId) {
targetMatrix[count2] = [xPos, yCoords[nodeIndexes.get(nodeId)]];
sourceMatrix[count2] = [xCoords[nodeIndexes.get(nodeId)], yCoords[nodeIndexes.get(nodeId)]];
count2++;
});
}, "_loop2");
for (var _i4 = 0; _i4 < verticalAlign.length; _i4++) {
_loop2(_i4);
}
standardTransformation = true;
}
if (constraints.alignmentConstraint.horizontal) {
var horizontalAlign = constraints.alignmentConstraint.horizontal;
var _loop3 = /* @__PURE__ */ __name(function _loop32(_i52) {
var alignmentSet = /* @__PURE__ */ new Set();
horizontalAlign[_i52].forEach(function(nodeId) {
alignmentSet.add(nodeId);
});
var intersection4 = new Set([].concat(_toConsumableArray2(alignmentSet)).filter(function(x5) {
return fixedNodes.has(x5);
}));
var yPos = void 0;
if (intersection4.size > 0) yPos = xCoords[nodeIndexes.get(intersection4.values().next().value)];
else yPos = calculateAvgPosition(alignmentSet).y;
horizontalAlign[_i52].forEach(function(nodeId) {
targetMatrix[count2] = [xCoords[nodeIndexes.get(nodeId)], yPos];
sourceMatrix[count2] = [xCoords[nodeIndexes.get(nodeId)], yCoords[nodeIndexes.get(nodeId)]];
count2++;
});
}, "_loop3");
for (var _i5 = 0; _i5 < horizontalAlign.length; _i5++) {
_loop3(_i5);
}
standardTransformation = true;
}
if (constraints.relativePlacementConstraint) {
reflectionType = true;
}
})();
} else if (constraints.relativePlacementConstraint) {
var largestComponentSize = 0;
var largestComponentIndex = 0;
for (var _i6 = 0; _i6 < components3.length; _i6++) {
if (components3[_i6].length > largestComponentSize) {
largestComponentSize = components3[_i6].length;
largestComponentIndex = _i6;
}
}
if (largestComponentSize < dagUndirected.size / 2) {
applyReflectionForRelativePlacement(constraints.relativePlacementConstraint);
standardTransformation = false;
reflectionType = false;
} else {
var subGraphOnHorizontal = /* @__PURE__ */ new Map();
var subGraphOnVertical = /* @__PURE__ */ new Map();
var constraintsInlargestComponent = [];
components3[largestComponentIndex].forEach(function(nodeId) {
dag.get(nodeId).forEach(function(adjacent) {
if (adjacent.direction == "horizontal") {
if (subGraphOnHorizontal.has(nodeId)) {
subGraphOnHorizontal.get(nodeId).push(adjacent);
} else {
subGraphOnHorizontal.set(nodeId, [adjacent]);
}
if (!subGraphOnHorizontal.has(adjacent.id)) {
subGraphOnHorizontal.set(adjacent.id, []);
}
constraintsInlargestComponent.push({ left: nodeId, right: adjacent.id });
} else {
if (subGraphOnVertical.has(nodeId)) {
subGraphOnVertical.get(nodeId).push(adjacent);
} else {
subGraphOnVertical.set(nodeId, [adjacent]);
}
if (!subGraphOnVertical.has(adjacent.id)) {
subGraphOnVertical.set(adjacent.id, []);
}
constraintsInlargestComponent.push({ top: nodeId, bottom: adjacent.id });
}
});
});
applyReflectionForRelativePlacement(constraintsInlargestComponent);
reflectionType = false;
var positionMapHorizontal = findAppropriatePositionForRelativePlacement(subGraphOnHorizontal, "horizontal");
var positionMapVertical = findAppropriatePositionForRelativePlacement(subGraphOnVertical, "vertical");
components3[largestComponentIndex].forEach(function(nodeId, i3) {
sourceMatrix[i3] = [xCoords[nodeIndexes.get(nodeId)], yCoords[nodeIndexes.get(nodeId)]];
targetMatrix[i3] = [];
if (positionMapHorizontal.has(nodeId)) {
targetMatrix[i3][0] = positionMapHorizontal.get(nodeId);
} else {
targetMatrix[i3][0] = xCoords[nodeIndexes.get(nodeId)];
}
if (positionMapVertical.has(nodeId)) {
targetMatrix[i3][1] = positionMapVertical.get(nodeId);
} else {
targetMatrix[i3][1] = yCoords[nodeIndexes.get(nodeId)];
}
});
standardTransformation = true;
}
}
if (standardTransformation) {
var transformationMatrix = void 0;
var targetMatrixTranspose = Matrix.transpose(targetMatrix);
var sourceMatrixTranspose = Matrix.transpose(sourceMatrix);
for (var _i7 = 0; _i7 < targetMatrixTranspose.length; _i7++) {
targetMatrixTranspose[_i7] = Matrix.multGamma(targetMatrixTranspose[_i7]);
sourceMatrixTranspose[_i7] = Matrix.multGamma(sourceMatrixTranspose[_i7]);
}
var tempMatrix = Matrix.multMat(targetMatrixTranspose, Matrix.transpose(sourceMatrixTranspose));
var SVDResult = SVD.svd(tempMatrix);
transformationMatrix = Matrix.multMat(SVDResult.V, Matrix.transpose(SVDResult.U));
for (var _i8 = 0; _i8 < nodeIndexes.size; _i8++) {
var temp1 = [xCoords[_i8], yCoords[_i8]];
var temp2 = [transformationMatrix[0][0], transformationMatrix[1][0]];
var temp3 = [transformationMatrix[0][1], transformationMatrix[1][1]];
xCoords[_i8] = Matrix.dotProduct(temp1, temp2);
yCoords[_i8] = Matrix.dotProduct(temp1, temp3);
}
if (reflectionType) {
applyReflectionForRelativePlacement(constraints.relativePlacementConstraint);
}
}
}
if (CoSEConstants.ENFORCE_CONSTRAINTS) {
if (constraints.fixedNodeConstraint && constraints.fixedNodeConstraint.length > 0) {
var translationAmount = { x: 0, y: 0 };
constraints.fixedNodeConstraint.forEach(function(nodeData2, i3) {
var posInTheory = { x: xCoords[nodeIndexes.get(nodeData2.nodeId)], y: yCoords[nodeIndexes.get(nodeData2.nodeId)] };
var posDesired = nodeData2.position;
var posDiff = calculatePositionDiff(posDesired, posInTheory);
translationAmount.x += posDiff.x;
translationAmount.y += posDiff.y;
});
translationAmount.x /= constraints.fixedNodeConstraint.length;
translationAmount.y /= constraints.fixedNodeConstraint.length;
xCoords.forEach(function(value2, i3) {
xCoords[i3] += translationAmount.x;
});
yCoords.forEach(function(value2, i3) {
yCoords[i3] += translationAmount.y;
});
constraints.fixedNodeConstraint.forEach(function(nodeData2) {
xCoords[nodeIndexes.get(nodeData2.nodeId)] = nodeData2.position.x;
yCoords[nodeIndexes.get(nodeData2.nodeId)] = nodeData2.position.y;
});
}
if (constraints.alignmentConstraint) {
if (constraints.alignmentConstraint.vertical) {
var xAlign = constraints.alignmentConstraint.vertical;
var _loop4 = /* @__PURE__ */ __name(function _loop42(_i92) {
var alignmentSet = /* @__PURE__ */ new Set();
xAlign[_i92].forEach(function(nodeId) {
alignmentSet.add(nodeId);
});
var intersection4 = new Set([].concat(_toConsumableArray2(alignmentSet)).filter(function(x5) {
return fixedNodes.has(x5);
}));
var xPos = void 0;
if (intersection4.size > 0) xPos = xCoords[nodeIndexes.get(intersection4.values().next().value)];
else xPos = calculateAvgPosition(alignmentSet).x;
alignmentSet.forEach(function(nodeId) {
if (!fixedNodes.has(nodeId)) xCoords[nodeIndexes.get(nodeId)] = xPos;
});
}, "_loop4");
for (var _i9 = 0; _i9 < xAlign.length; _i9++) {
_loop4(_i9);
}
}
if (constraints.alignmentConstraint.horizontal) {
var yAlign = constraints.alignmentConstraint.horizontal;
var _loop5 = /* @__PURE__ */ __name(function _loop52(_i102) {
var alignmentSet = /* @__PURE__ */ new Set();
yAlign[_i102].forEach(function(nodeId) {
alignmentSet.add(nodeId);
});
var intersection4 = new Set([].concat(_toConsumableArray2(alignmentSet)).filter(function(x5) {
return fixedNodes.has(x5);
}));
var yPos = void 0;
if (intersection4.size > 0) yPos = yCoords[nodeIndexes.get(intersection4.values().next().value)];
else yPos = calculateAvgPosition(alignmentSet).y;
alignmentSet.forEach(function(nodeId) {
if (!fixedNodes.has(nodeId)) yCoords[nodeIndexes.get(nodeId)] = yPos;
});
}, "_loop5");
for (var _i10 = 0; _i10 < yAlign.length; _i10++) {
_loop5(_i10);
}
}
}
if (constraints.relativePlacementConstraint) {
(function() {
var nodeToDummyForVerticalAlignment = /* @__PURE__ */ new Map();
var nodeToDummyForHorizontalAlignment = /* @__PURE__ */ new Map();
var dummyToNodeForVerticalAlignment = /* @__PURE__ */ new Map();
var dummyToNodeForHorizontalAlignment = /* @__PURE__ */ new Map();
var dummyPositionsForVerticalAlignment = /* @__PURE__ */ new Map();
var dummyPositionsForHorizontalAlignment = /* @__PURE__ */ new Map();
var fixedNodesOnHorizontal = /* @__PURE__ */ new Set();
var fixedNodesOnVertical = /* @__PURE__ */ new Set();
fixedNodes.forEach(function(nodeId2) {
fixedNodesOnHorizontal.add(nodeId2);
fixedNodesOnVertical.add(nodeId2);
});
if (constraints.alignmentConstraint) {
if (constraints.alignmentConstraint.vertical) {
var verticalAlignment2 = constraints.alignmentConstraint.vertical;
var _loop6 = /* @__PURE__ */ __name(function _loop62(_i112) {
dummyToNodeForVerticalAlignment.set("dummy" + _i112, []);
verticalAlignment2[_i112].forEach(function(nodeId2) {
nodeToDummyForVerticalAlignment.set(nodeId2, "dummy" + _i112);
dummyToNodeForVerticalAlignment.get("dummy" + _i112).push(nodeId2);
if (fixedNodes.has(nodeId2)) {
fixedNodesOnHorizontal.add("dummy" + _i112);
}
});
dummyPositionsForVerticalAlignment.set("dummy" + _i112, xCoords[nodeIndexes.get(verticalAlignment2[_i112][0])]);
}, "_loop6");
for (var _i11 = 0; _i11 < verticalAlignment2.length; _i11++) {
_loop6(_i11);
}
}
if (constraints.alignmentConstraint.horizontal) {
var horizontalAlignment = constraints.alignmentConstraint.horizontal;
var _loop7 = /* @__PURE__ */ __name(function _loop72(_i122) {
dummyToNodeForHorizontalAlignment.set("dummy" + _i122, []);
horizontalAlignment[_i122].forEach(function(nodeId2) {
nodeToDummyForHorizontalAlignment.set(nodeId2, "dummy" + _i122);
dummyToNodeForHorizontalAlignment.get("dummy" + _i122).push(nodeId2);
if (fixedNodes.has(nodeId2)) {
fixedNodesOnVertical.add("dummy" + _i122);
}
});
dummyPositionsForHorizontalAlignment.set("dummy" + _i122, yCoords[nodeIndexes.get(horizontalAlignment[_i122][0])]);
}, "_loop7");
for (var _i12 = 0; _i12 < horizontalAlignment.length; _i12++) {
_loop7(_i12);
}
}
}
var dagOnHorizontal = /* @__PURE__ */ new Map();
var dagOnVertical = /* @__PURE__ */ new Map();
var _loop8 = /* @__PURE__ */ __name(function _loop82(nodeId2) {
dag.get(nodeId2).forEach(function(adjacent) {
var sourceId = void 0;
var targetNode = void 0;
if (adjacent["direction"] == "horizontal") {
sourceId = nodeToDummyForVerticalAlignment.get(nodeId2) ? nodeToDummyForVerticalAlignment.get(nodeId2) : nodeId2;
if (nodeToDummyForVerticalAlignment.get(adjacent.id)) {
targetNode = { id: nodeToDummyForVerticalAlignment.get(adjacent.id), gap: adjacent.gap, direction: adjacent.direction };
} else {
targetNode = adjacent;
}
if (dagOnHorizontal.has(sourceId)) {
dagOnHorizontal.get(sourceId).push(targetNode);
} else {
dagOnHorizontal.set(sourceId, [targetNode]);
}
if (!dagOnHorizontal.has(targetNode.id)) {
dagOnHorizontal.set(targetNode.id, []);
}
} else {
sourceId = nodeToDummyForHorizontalAlignment.get(nodeId2) ? nodeToDummyForHorizontalAlignment.get(nodeId2) : nodeId2;
if (nodeToDummyForHorizontalAlignment.get(adjacent.id)) {
targetNode = { id: nodeToDummyForHorizontalAlignment.get(adjacent.id), gap: adjacent.gap, direction: adjacent.direction };
} else {
targetNode = adjacent;
}
if (dagOnVertical.has(sourceId)) {
dagOnVertical.get(sourceId).push(targetNode);
} else {
dagOnVertical.set(sourceId, [targetNode]);
}
if (!dagOnVertical.has(targetNode.id)) {
dagOnVertical.set(targetNode.id, []);
}
}
});
}, "_loop8");
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = void 0;
try {
for (var _iterator5 = dag.keys()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var nodeId = _step5.value;
_loop8(nodeId);
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
var undirectedOnHorizontal = dagToUndirected(dagOnHorizontal);
var undirectedOnVertical = dagToUndirected(dagOnVertical);
var componentsOnHorizontal = findComponents(undirectedOnHorizontal);
var componentsOnVertical = findComponents(undirectedOnVertical);
var reversedDagOnHorizontal = dagToReversed(dagOnHorizontal);
var reversedDagOnVertical = dagToReversed(dagOnVertical);
var componentSourcesOnHorizontal = [];
var componentSourcesOnVertical = [];
componentsOnHorizontal.forEach(function(component2, index2) {
componentSourcesOnHorizontal[index2] = [];
component2.forEach(function(nodeId2) {
if (reversedDagOnHorizontal.get(nodeId2).length == 0) {
componentSourcesOnHorizontal[index2].push(nodeId2);
}
});
});
componentsOnVertical.forEach(function(component2, index2) {
componentSourcesOnVertical[index2] = [];
component2.forEach(function(nodeId2) {
if (reversedDagOnVertical.get(nodeId2).length == 0) {
componentSourcesOnVertical[index2].push(nodeId2);
}
});
});
var positionMapHorizontal2 = findAppropriatePositionForRelativePlacement(dagOnHorizontal, "horizontal", fixedNodesOnHorizontal, dummyPositionsForVerticalAlignment, componentSourcesOnHorizontal);
var positionMapVertical2 = findAppropriatePositionForRelativePlacement(dagOnVertical, "vertical", fixedNodesOnVertical, dummyPositionsForHorizontalAlignment, componentSourcesOnVertical);
var _loop9 = /* @__PURE__ */ __name(function _loop92(key2) {
if (dummyToNodeForVerticalAlignment.get(key2)) {
dummyToNodeForVerticalAlignment.get(key2).forEach(function(nodeId2) {
xCoords[nodeIndexes.get(nodeId2)] = positionMapHorizontal2.get(key2);
});
} else {
xCoords[nodeIndexes.get(key2)] = positionMapHorizontal2.get(key2);
}
}, "_loop9");
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = void 0;
try {
for (var _iterator6 = positionMapHorizontal2.keys()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var key = _step6.value;
_loop9(key);
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6.return) {
_iterator6.return();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
var _loop10 = /* @__PURE__ */ __name(function _loop102(key2) {
if (dummyToNodeForHorizontalAlignment.get(key2)) {
dummyToNodeForHorizontalAlignment.get(key2).forEach(function(nodeId2) {
yCoords[nodeIndexes.get(nodeId2)] = positionMapVertical2.get(key2);
});
} else {
yCoords[nodeIndexes.get(key2)] = positionMapVertical2.get(key2);
}
}, "_loop10");
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = void 0;
try {
for (var _iterator7 = positionMapVertical2.keys()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var key = _step7.value;
_loop10(key);
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
})();
}
}
for (var _i13 = 0; _i13 < allNodes.length; _i13++) {
var _node = allNodes[_i13];
if (_node.getChild() == null) {
_node.setCenter(xCoords[nodeIndexes.get(_node.id)], yCoords[nodeIndexes.get(_node.id)]);
}
}
};
module3.exports = ConstraintHandler;
})
),
/***/
551: (
/***/
((module3) => {
module3.exports = __WEBPACK_EXTERNAL_MODULE__551__;
})
)
/******/
};
var __webpack_module_cache__ = {};
function __webpack_require__(moduleId) {
var cachedModule = __webpack_module_cache__[moduleId];
if (cachedModule !== void 0) {
return cachedModule.exports;
}
var module3 = __webpack_module_cache__[moduleId] = {
/******/
// no module.id needed
/******/
// no module.loaded needed
/******/
exports: {}
/******/
};
__webpack_modules__[moduleId](module3, module3.exports, __webpack_require__);
return module3.exports;
}
__name(__webpack_require__, "__webpack_require__");
var __webpack_exports__ = __webpack_require__(45);
return __webpack_exports__;
})()
);
});
}
});
// ../../node_modules/.pnpm/cytoscape-fcose@2.2.0_cytoscape@3.33.1/node_modules/cytoscape-fcose/cytoscape-fcose.js
var require_cytoscape_fcose = __commonJS({
"../../node_modules/.pnpm/cytoscape-fcose@2.2.0_cytoscape@3.33.1/node_modules/cytoscape-fcose/cytoscape-fcose.js"(exports2, module2) {
"use strict";
(/* @__PURE__ */ __name((function webpackUniversalModuleDefinition(root3, factory) {
if (typeof exports2 === "object" && typeof module2 === "object")
module2.exports = factory(require_cose_base2());
else if (typeof define === "function" && define.amd)
define(["cose-base"], factory);
else if (typeof exports2 === "object")
exports2["cytoscapeFcose"] = factory(require_cose_base2());
else
root3["cytoscapeFcose"] = factory(root3["coseBase"]);
}), "webpackUniversalModuleDefinition"))(exports2, function(__WEBPACK_EXTERNAL_MODULE__140__) {
return (
/******/
(() => {
"use strict";
var __webpack_modules__ = {
/***/
658: (
/***/
((module3) => {
module3.exports = Object.assign != null ? Object.assign.bind(Object) : function(tgt) {
for (var _len = arguments.length, srcs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
srcs[_key - 1] = arguments[_key];
}
srcs.forEach(function(src) {
Object.keys(src).forEach(function(k2) {
return tgt[k2] = src[k2];
});
});
return tgt;
};
})
),
/***/
548: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var _slicedToArray2 = /* @__PURE__ */ (function() {
function sliceIterator(arr, i2) {
var _arr = [];
var _n = true;
var _d = false;
var _e2 = void 0;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i2 && _arr.length === i2) break;
}
} catch (err) {
_d = true;
_e2 = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e2;
}
}
return _arr;
}
__name(sliceIterator, "sliceIterator");
return function(arr, i2) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i2);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
})();
var LinkedList = __webpack_require__2(140).layoutBase.LinkedList;
var auxiliary = {};
auxiliary.getTopMostNodes = function(nodes5) {
var nodesMap2 = {};
for (var i2 = 0; i2 < nodes5.length; i2++) {
nodesMap2[nodes5[i2].id()] = true;
}
var roots = nodes5.filter(function(ele, i3) {
if (typeof ele === "number") {
ele = i3;
}
var parent4 = ele.parent()[0];
while (parent4 != null) {
if (nodesMap2[parent4.id()]) {
return false;
}
parent4 = parent4.parent()[0];
}
return true;
});
return roots;
};
auxiliary.connectComponents = function(cy, eles, topMostNodes, dummyNodes) {
var queue = new LinkedList();
var visited = /* @__PURE__ */ new Set();
var visitedTopMostNodes = [];
var currentNeighbor = void 0;
var minDegreeNode = void 0;
var minDegree = void 0;
var isConnected = false;
var count2 = 1;
var nodesConnectedToDummy = [];
var components3 = [];
var _loop = /* @__PURE__ */ __name(function _loop2() {
var cmpt = cy.collection();
components3.push(cmpt);
var currentNode = topMostNodes[0];
var childrenOfCurrentNode = cy.collection();
childrenOfCurrentNode.merge(currentNode).merge(currentNode.descendants().intersection(eles));
visitedTopMostNodes.push(currentNode);
childrenOfCurrentNode.forEach(function(node2) {
queue.push(node2);
visited.add(node2);
cmpt.merge(node2);
});
var _loop22 = /* @__PURE__ */ __name(function _loop23() {
currentNode = queue.shift();
var neighborNodes = cy.collection();
currentNode.neighborhood().nodes().forEach(function(node2) {
if (eles.intersection(currentNode.edgesWith(node2)).length > 0) {
neighborNodes.merge(node2);
}
});
for (var i2 = 0; i2 < neighborNodes.length; i2++) {
var neighborNode = neighborNodes[i2];
currentNeighbor = topMostNodes.intersection(neighborNode.union(neighborNode.ancestors()));
if (currentNeighbor != null && !visited.has(currentNeighbor[0])) {
var childrenOfNeighbor = currentNeighbor.union(currentNeighbor.descendants());
childrenOfNeighbor.forEach(function(node2) {
queue.push(node2);
visited.add(node2);
cmpt.merge(node2);
if (topMostNodes.has(node2)) {
visitedTopMostNodes.push(node2);
}
});
}
}
}, "_loop2");
while (queue.length != 0) {
_loop22();
}
cmpt.forEach(function(node2) {
eles.intersection(node2.connectedEdges()).forEach(function(e3) {
if (cmpt.has(e3.source()) && cmpt.has(e3.target())) {
cmpt.merge(e3);
}
});
});
if (visitedTopMostNodes.length == topMostNodes.length) {
isConnected = true;
}
if (!isConnected || isConnected && count2 > 1) {
minDegreeNode = visitedTopMostNodes[0];
minDegree = minDegreeNode.connectedEdges().length;
visitedTopMostNodes.forEach(function(node2) {
if (node2.connectedEdges().length < minDegree) {
minDegree = node2.connectedEdges().length;
minDegreeNode = node2;
}
});
nodesConnectedToDummy.push(minDegreeNode.id());
var temp = cy.collection();
temp.merge(visitedTopMostNodes[0]);
visitedTopMostNodes.forEach(function(node2) {
temp.merge(node2);
});
visitedTopMostNodes = [];
topMostNodes = topMostNodes.difference(temp);
count2++;
}
}, "_loop");
do {
_loop();
} while (!isConnected);
if (dummyNodes) {
if (nodesConnectedToDummy.length > 0) {
dummyNodes.set("dummy" + (dummyNodes.size + 1), nodesConnectedToDummy);
}
}
return components3;
};
auxiliary.relocateComponent = function(originalCenter, componentResult, options2) {
if (!options2.fixedNodeConstraint) {
var minXCoord = Number.POSITIVE_INFINITY;
var maxXCoord = Number.NEGATIVE_INFINITY;
var minYCoord = Number.POSITIVE_INFINITY;
var maxYCoord = Number.NEGATIVE_INFINITY;
if (options2.quality == "draft") {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = void 0;
try {
for (var _iterator = componentResult.nodeIndexes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _ref = _step.value;
var _ref2 = _slicedToArray2(_ref, 2);
var key = _ref2[0];
var value2 = _ref2[1];
var cyNode = options2.cy.getElementById(key);
if (cyNode) {
var nodeBB = cyNode.boundingBox();
var leftX = componentResult.xCoords[value2] - nodeBB.w / 2;
var rightX = componentResult.xCoords[value2] + nodeBB.w / 2;
var topY = componentResult.yCoords[value2] - nodeBB.h / 2;
var bottomY = componentResult.yCoords[value2] + nodeBB.h / 2;
if (leftX < minXCoord) minXCoord = leftX;
if (rightX > maxXCoord) maxXCoord = rightX;
if (topY < minYCoord) minYCoord = topY;
if (bottomY > maxYCoord) maxYCoord = bottomY;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var diffOnX = originalCenter.x - (maxXCoord + minXCoord) / 2;
var diffOnY = originalCenter.y - (maxYCoord + minYCoord) / 2;
componentResult.xCoords = componentResult.xCoords.map(function(x5) {
return x5 + diffOnX;
});
componentResult.yCoords = componentResult.yCoords.map(function(y6) {
return y6 + diffOnY;
});
} else {
Object.keys(componentResult).forEach(function(item) {
var node2 = componentResult[item];
var leftX2 = node2.getRect().x;
var rightX2 = node2.getRect().x + node2.getRect().width;
var topY2 = node2.getRect().y;
var bottomY2 = node2.getRect().y + node2.getRect().height;
if (leftX2 < minXCoord) minXCoord = leftX2;
if (rightX2 > maxXCoord) maxXCoord = rightX2;
if (topY2 < minYCoord) minYCoord = topY2;
if (bottomY2 > maxYCoord) maxYCoord = bottomY2;
});
var _diffOnX = originalCenter.x - (maxXCoord + minXCoord) / 2;
var _diffOnY = originalCenter.y - (maxYCoord + minYCoord) / 2;
Object.keys(componentResult).forEach(function(item) {
var node2 = componentResult[item];
node2.setCenter(node2.getCenterX() + _diffOnX, node2.getCenterY() + _diffOnY);
});
}
}
};
auxiliary.calcBoundingBox = function(parentNode, xCoords, yCoords, nodeIndexes) {
var left3 = Number.MAX_SAFE_INTEGER;
var right3 = Number.MIN_SAFE_INTEGER;
var top2 = Number.MAX_SAFE_INTEGER;
var bottom2 = Number.MIN_SAFE_INTEGER;
var nodeLeft = void 0;
var nodeRight = void 0;
var nodeTop = void 0;
var nodeBottom = void 0;
var nodes5 = parentNode.descendants().not(":parent");
var s2 = nodes5.length;
for (var i2 = 0; i2 < s2; i2++) {
var node2 = nodes5[i2];
nodeLeft = xCoords[nodeIndexes.get(node2.id())] - node2.width() / 2;
nodeRight = xCoords[nodeIndexes.get(node2.id())] + node2.width() / 2;
nodeTop = yCoords[nodeIndexes.get(node2.id())] - node2.height() / 2;
nodeBottom = yCoords[nodeIndexes.get(node2.id())] + node2.height() / 2;
if (left3 > nodeLeft) {
left3 = nodeLeft;
}
if (right3 < nodeRight) {
right3 = nodeRight;
}
if (top2 > nodeTop) {
top2 = nodeTop;
}
if (bottom2 < nodeBottom) {
bottom2 = nodeBottom;
}
}
var boundingBox3 = {};
boundingBox3.topLeftX = left3;
boundingBox3.topLeftY = top2;
boundingBox3.width = right3 - left3;
boundingBox3.height = bottom2 - top2;
return boundingBox3;
};
auxiliary.calcParentsWithoutChildren = function(cy, eles) {
var parentsWithoutChildren = cy.collection();
eles.nodes(":parent").forEach(function(parent4) {
var check = false;
parent4.children().forEach(function(child) {
if (child.css("display") != "none") {
check = true;
}
});
if (!check) {
parentsWithoutChildren.merge(parent4);
}
});
return parentsWithoutChildren;
};
module3.exports = auxiliary;
})
),
/***/
816: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var aux = __webpack_require__2(548);
var CoSELayout = __webpack_require__2(140).CoSELayout;
var CoSENode = __webpack_require__2(140).CoSENode;
var PointD = __webpack_require__2(140).layoutBase.PointD;
var DimensionD2 = __webpack_require__2(140).layoutBase.DimensionD;
var LayoutConstants = __webpack_require__2(140).layoutBase.LayoutConstants;
var FDLayoutConstants = __webpack_require__2(140).layoutBase.FDLayoutConstants;
var CoSEConstants = __webpack_require__2(140).CoSEConstants;
var coseLayout = /* @__PURE__ */ __name(function coseLayout2(options2, spectralResult) {
var cy = options2.cy;
var eles = options2.eles;
var nodes5 = eles.nodes();
var edges3 = eles.edges();
var nodeIndexes = void 0;
var xCoords = void 0;
var yCoords = void 0;
var idToLNode = {};
if (options2.randomize) {
nodeIndexes = spectralResult["nodeIndexes"];
xCoords = spectralResult["xCoords"];
yCoords = spectralResult["yCoords"];
}
var isFn = /* @__PURE__ */ __name(function isFn2(fn3) {
return typeof fn3 === "function";
}, "isFn");
var optFn = /* @__PURE__ */ __name(function optFn2(opt, ele) {
if (isFn(opt)) {
return opt(ele);
} else {
return opt;
}
}, "optFn");
var parentsWithoutChildren = aux.calcParentsWithoutChildren(cy, eles);
var processChildrenList = /* @__PURE__ */ __name(function processChildrenList2(parent4, children2, layout7, options3) {
var size4 = children2.length;
for (var i2 = 0; i2 < size4; i2++) {
var theChild = children2[i2];
var children_of_children = null;
if (theChild.intersection(parentsWithoutChildren).length == 0) {
children_of_children = theChild.children();
}
var theNode = void 0;
var dimensions2 = theChild.layoutDimensions({
nodeDimensionsIncludeLabels: options3.nodeDimensionsIncludeLabels
});
if (theChild.outerWidth() != null && theChild.outerHeight() != null) {
if (options3.randomize) {
if (!theChild.isParent()) {
theNode = parent4.add(new CoSENode(layout7.graphManager, new PointD(xCoords[nodeIndexes.get(theChild.id())] - dimensions2.w / 2, yCoords[nodeIndexes.get(theChild.id())] - dimensions2.h / 2), new DimensionD2(parseFloat(dimensions2.w), parseFloat(dimensions2.h))));
} else {
var parentInfo = aux.calcBoundingBox(theChild, xCoords, yCoords, nodeIndexes);
if (theChild.intersection(parentsWithoutChildren).length == 0) {
theNode = parent4.add(new CoSENode(layout7.graphManager, new PointD(parentInfo.topLeftX, parentInfo.topLeftY), new DimensionD2(parentInfo.width, parentInfo.height)));
} else {
theNode = parent4.add(new CoSENode(layout7.graphManager, new PointD(parentInfo.topLeftX, parentInfo.topLeftY), new DimensionD2(parseFloat(dimensions2.w), parseFloat(dimensions2.h))));
}
}
} else {
theNode = parent4.add(new CoSENode(layout7.graphManager, new PointD(theChild.position("x") - dimensions2.w / 2, theChild.position("y") - dimensions2.h / 2), new DimensionD2(parseFloat(dimensions2.w), parseFloat(dimensions2.h))));
}
} else {
theNode = parent4.add(new CoSENode(this.graphManager));
}
theNode.id = theChild.data("id");
theNode.nodeRepulsion = optFn(options3.nodeRepulsion, theChild);
theNode.paddingLeft = parseInt(theChild.css("padding"));
theNode.paddingTop = parseInt(theChild.css("padding"));
theNode.paddingRight = parseInt(theChild.css("padding"));
theNode.paddingBottom = parseInt(theChild.css("padding"));
if (options3.nodeDimensionsIncludeLabels) {
theNode.labelWidth = theChild.boundingBox({ includeLabels: true, includeNodes: false, includeOverlays: false }).w;
theNode.labelHeight = theChild.boundingBox({ includeLabels: true, includeNodes: false, includeOverlays: false }).h;
theNode.labelPosVertical = theChild.css("text-valign");
theNode.labelPosHorizontal = theChild.css("text-halign");
}
idToLNode[theChild.data("id")] = theNode;
if (isNaN(theNode.rect.x)) {
theNode.rect.x = 0;
}
if (isNaN(theNode.rect.y)) {
theNode.rect.y = 0;
}
if (children_of_children != null && children_of_children.length > 0) {
var theNewGraph = void 0;
theNewGraph = layout7.getGraphManager().add(layout7.newGraph(), theNode);
processChildrenList2(theNewGraph, children_of_children, layout7, options3);
}
}
}, "processChildrenList");
var processEdges = /* @__PURE__ */ __name(function processEdges2(layout7, gm2, edges4) {
var idealLengthTotal = 0;
var edgeCount3 = 0;
for (var i2 = 0; i2 < edges4.length; i2++) {
var edge = edges4[i2];
var sourceNode = idToLNode[edge.data("source")];
var targetNode = idToLNode[edge.data("target")];
if (sourceNode && targetNode && sourceNode !== targetNode && sourceNode.getEdgesBetween(targetNode).length == 0) {
var e1 = gm2.add(layout7.newEdge(), sourceNode, targetNode);
e1.id = edge.id();
e1.idealLength = optFn(options2.idealEdgeLength, edge);
e1.edgeElasticity = optFn(options2.edgeElasticity, edge);
idealLengthTotal += e1.idealLength;
edgeCount3++;
}
}
if (options2.idealEdgeLength != null) {
if (edgeCount3 > 0) CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = idealLengthTotal / edgeCount3;
else if (!isFn(options2.idealEdgeLength))
CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = options2.idealEdgeLength;
else
CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = 50;
CoSEConstants.MIN_REPULSION_DIST = FDLayoutConstants.MIN_REPULSION_DIST = FDLayoutConstants.DEFAULT_EDGE_LENGTH / 10;
CoSEConstants.DEFAULT_RADIAL_SEPARATION = FDLayoutConstants.DEFAULT_EDGE_LENGTH;
}
}, "processEdges");
var processConstraints = /* @__PURE__ */ __name(function processConstraints2(layout7, options3) {
if (options3.fixedNodeConstraint) {
layout7.constraints["fixedNodeConstraint"] = options3.fixedNodeConstraint;
}
if (options3.alignmentConstraint) {
layout7.constraints["alignmentConstraint"] = options3.alignmentConstraint;
}
if (options3.relativePlacementConstraint) {
layout7.constraints["relativePlacementConstraint"] = options3.relativePlacementConstraint;
}
}, "processConstraints");
if (options2.nestingFactor != null) CoSEConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = options2.nestingFactor;
if (options2.gravity != null) CoSEConstants.DEFAULT_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH = options2.gravity;
if (options2.numIter != null) CoSEConstants.MAX_ITERATIONS = FDLayoutConstants.MAX_ITERATIONS = options2.numIter;
if (options2.gravityRange != null) CoSEConstants.DEFAULT_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR = options2.gravityRange;
if (options2.gravityCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = options2.gravityCompound;
if (options2.gravityRangeCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = options2.gravityRangeCompound;
if (options2.initialEnergyOnIncremental != null) CoSEConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = options2.initialEnergyOnIncremental;
if (options2.tilingCompareBy != null) CoSEConstants.TILING_COMPARE_BY = options2.tilingCompareBy;
if (options2.quality == "proof") LayoutConstants.QUALITY = 2;
else LayoutConstants.QUALITY = 0;
CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS = FDLayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = options2.nodeDimensionsIncludeLabels;
CoSEConstants.DEFAULT_INCREMENTAL = FDLayoutConstants.DEFAULT_INCREMENTAL = LayoutConstants.DEFAULT_INCREMENTAL = !options2.randomize;
CoSEConstants.ANIMATE = FDLayoutConstants.ANIMATE = LayoutConstants.ANIMATE = options2.animate;
CoSEConstants.TILE = options2.tile;
CoSEConstants.TILING_PADDING_VERTICAL = typeof options2.tilingPaddingVertical === "function" ? options2.tilingPaddingVertical.call() : options2.tilingPaddingVertical;
CoSEConstants.TILING_PADDING_HORIZONTAL = typeof options2.tilingPaddingHorizontal === "function" ? options2.tilingPaddingHorizontal.call() : options2.tilingPaddingHorizontal;
CoSEConstants.DEFAULT_INCREMENTAL = FDLayoutConstants.DEFAULT_INCREMENTAL = LayoutConstants.DEFAULT_INCREMENTAL = true;
CoSEConstants.PURE_INCREMENTAL = !options2.randomize;
LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES = options2.uniformNodeDimensions;
if (options2.step == "transformed") {
CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;
CoSEConstants.ENFORCE_CONSTRAINTS = false;
CoSEConstants.APPLY_LAYOUT = false;
}
if (options2.step == "enforced") {
CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;
CoSEConstants.ENFORCE_CONSTRAINTS = true;
CoSEConstants.APPLY_LAYOUT = false;
}
if (options2.step == "cose") {
CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;
CoSEConstants.ENFORCE_CONSTRAINTS = false;
CoSEConstants.APPLY_LAYOUT = true;
}
if (options2.step == "all") {
if (options2.randomize) CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;
else CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;
CoSEConstants.ENFORCE_CONSTRAINTS = true;
CoSEConstants.APPLY_LAYOUT = true;
}
if (options2.fixedNodeConstraint || options2.alignmentConstraint || options2.relativePlacementConstraint) {
CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = false;
} else {
CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = true;
}
var coseLayout3 = new CoSELayout();
var gm = coseLayout3.newGraphManager();
processChildrenList(gm.addRoot(), aux.getTopMostNodes(nodes5), coseLayout3, options2);
processEdges(coseLayout3, gm, edges3);
processConstraints(coseLayout3, options2);
coseLayout3.runLayout();
return idToLNode;
}, "coseLayout");
module3.exports = { coseLayout };
})
),
/***/
212: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var _createClass2 = /* @__PURE__ */ (function() {
function defineProperties(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
__name(defineProperties, "defineProperties");
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
function _classCallCheck2(instance2, Constructor) {
if (!(instance2 instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
__name(_classCallCheck2, "_classCallCheck");
var assign7 = __webpack_require__2(658);
var aux = __webpack_require__2(548);
var _require = __webpack_require__2(657), spectralLayout = _require.spectralLayout;
var _require2 = __webpack_require__2(816), coseLayout = _require2.coseLayout;
var defaults4 = Object.freeze({
// 'draft', 'default' or 'proof'
// - 'draft' only applies spectral layout
// - 'default' improves the quality with subsequent CoSE layout (fast cooling rate)
// - 'proof' improves the quality with subsequent CoSE layout (slow cooling rate)
quality: "default",
// Use random node positions at beginning of layout
// if this is set to false, then quality option must be "proof"
randomize: true,
// Whether or not to animate the layout
animate: true,
// Duration of animation in ms, if enabled
animationDuration: 1e3,
// Easing of animation, if enabled
animationEasing: void 0,
// Fit the viewport to the repositioned nodes
fit: true,
// Padding around layout
padding: 30,
// Whether to include labels in node dimensions. Valid in "proof" quality
nodeDimensionsIncludeLabels: false,
// Whether or not simple nodes (non-compound nodes) are of uniform dimensions
uniformNodeDimensions: false,
// Whether to pack disconnected components - valid only if randomize: true
packComponents: true,
// Layout step - all, transformed, enforced, cose - for debug purpose only
step: "all",
/* spectral layout options */
// False for random, true for greedy
samplingType: true,
// Sample size to construct distance matrix
sampleSize: 25,
// Separation amount between nodes
nodeSeparation: 75,
// Power iteration tolerance
piTol: 1e-7,
/* CoSE layout options */
// Node repulsion (non overlapping) multiplier
nodeRepulsion: /* @__PURE__ */ __name(function nodeRepulsion4(node2) {
return 4500;
}, "nodeRepulsion"),
// Ideal edge (non nested) length
idealEdgeLength: /* @__PURE__ */ __name(function idealEdgeLength2(edge) {
return 50;
}, "idealEdgeLength"),
// Divisor to compute edge forces
edgeElasticity: /* @__PURE__ */ __name(function edgeElasticity2(edge) {
return 0.45;
}, "edgeElasticity"),
// Nesting factor (multiplier) to compute ideal edge length for nested edges
nestingFactor: 0.1,
// Gravity force (constant)
gravity: 0.25,
// Maximum number of iterations to perform
numIter: 2500,
// For enabling tiling
tile: true,
// The function that specifies the criteria for comparing nodes while sorting them during tiling operation.
// Takes the node id as a parameter and the default tiling operation is perfomed when this option is not set.
tilingCompareBy: void 0,
// Represents the amount of the vertical space to put between the zero degree members during the tiling operation(can also be a function)
tilingPaddingVertical: 10,
// Represents the amount of the horizontal space to put between the zero degree members during the tiling operation(can also be a function)
tilingPaddingHorizontal: 10,
// Gravity range (constant) for compounds
gravityRangeCompound: 1.5,
// Gravity force (constant) for compounds
gravityCompound: 1,
// Gravity range (constant)
gravityRange: 3.8,
// Initial cooling factor for incremental layout
initialEnergyOnIncremental: 0.3,
/* constraint options */
// Fix required nodes to predefined positions
// [{nodeId: 'n1', position: {x: 100, y: 200}, {...}]
fixedNodeConstraint: void 0,
// Align required nodes in vertical/horizontal direction
// {vertical: [['n1', 'n2')], ['n3', 'n4']], horizontal: ['n2', 'n4']}
alignmentConstraint: void 0,
// Place two nodes relatively in vertical/horizontal direction
// [{top: 'n1', bottom: 'n2', gap: 100}, {left: 'n3', right: 'n4', gap: 75}]
relativePlacementConstraint: void 0,
/* layout event callbacks */
ready: /* @__PURE__ */ __name(function ready4() {
}, "ready"),
// on layoutready
stop: /* @__PURE__ */ __name(function stop5() {
}, "stop")
// on layoutstop
});
var Layout2 = (function() {
function Layout3(options2) {
_classCallCheck2(this, Layout3);
this.options = assign7({}, defaults4, options2);
}
__name(Layout3, "Layout");
_createClass2(Layout3, [{
key: "run",
value: /* @__PURE__ */ __name(function run5() {
var layout7 = this;
var options2 = this.options;
var cy = options2.cy;
var eles = options2.eles;
var spectralResult = [];
var xCoords = void 0;
var yCoords = void 0;
var coseResult = [];
var components3 = void 0;
var componentCenters = [];
if (options2.fixedNodeConstraint && (!Array.isArray(options2.fixedNodeConstraint) || options2.fixedNodeConstraint.length == 0)) {
options2.fixedNodeConstraint = void 0;
}
if (options2.alignmentConstraint) {
if (options2.alignmentConstraint.vertical && (!Array.isArray(options2.alignmentConstraint.vertical) || options2.alignmentConstraint.vertical.length == 0)) {
options2.alignmentConstraint.vertical = void 0;
}
if (options2.alignmentConstraint.horizontal && (!Array.isArray(options2.alignmentConstraint.horizontal) || options2.alignmentConstraint.horizontal.length == 0)) {
options2.alignmentConstraint.horizontal = void 0;
}
}
if (options2.relativePlacementConstraint && (!Array.isArray(options2.relativePlacementConstraint) || options2.relativePlacementConstraint.length == 0)) {
options2.relativePlacementConstraint = void 0;
}
var constraintExist = options2.fixedNodeConstraint || options2.alignmentConstraint || options2.relativePlacementConstraint;
if (constraintExist) {
options2.tile = false;
options2.packComponents = false;
}
var layUtil = void 0;
var packingEnabled = false;
if (cy.layoutUtilities && options2.packComponents) {
layUtil = cy.layoutUtilities("get");
if (!layUtil) layUtil = cy.layoutUtilities();
packingEnabled = true;
}
if (eles.nodes().length > 0) {
if (!packingEnabled) {
var boundingBox3 = options2.eles.boundingBox();
componentCenters.push({ x: boundingBox3.x1 + boundingBox3.w / 2, y: boundingBox3.y1 + boundingBox3.h / 2 });
if (options2.randomize) {
var result = spectralLayout(options2);
spectralResult.push(result);
}
if (options2.quality == "default" || options2.quality == "proof") {
coseResult.push(coseLayout(options2, spectralResult[0]));
aux.relocateComponent(componentCenters[0], coseResult[0], options2);
} else {
aux.relocateComponent(componentCenters[0], spectralResult[0], options2);
}
} else {
var topMostNodes = aux.getTopMostNodes(options2.eles.nodes());
components3 = aux.connectComponents(cy, options2.eles, topMostNodes);
components3.forEach(function(component2) {
var boundingBox4 = component2.boundingBox();
componentCenters.push({ x: boundingBox4.x1 + boundingBox4.w / 2, y: boundingBox4.y1 + boundingBox4.h / 2 });
});
if (options2.randomize) {
components3.forEach(function(component2) {
options2.eles = component2;
spectralResult.push(spectralLayout(options2));
});
}
if (options2.quality == "default" || options2.quality == "proof") {
var toBeTiledNodes = cy.collection();
if (options2.tile) {
var nodeIndexes = /* @__PURE__ */ new Map();
var _xCoords = [];
var _yCoords = [];
var count2 = 0;
var tempSpectralResult = { nodeIndexes, xCoords: _xCoords, yCoords: _yCoords };
var indexesToBeDeleted = [];
components3.forEach(function(component2, index) {
if (component2.edges().length == 0) {
component2.nodes().forEach(function(node2, i3) {
toBeTiledNodes.merge(component2.nodes()[i3]);
if (!node2.isParent()) {
tempSpectralResult.nodeIndexes.set(component2.nodes()[i3].id(), count2++);
tempSpectralResult.xCoords.push(component2.nodes()[0].position().x);
tempSpectralResult.yCoords.push(component2.nodes()[0].position().y);
}
});
indexesToBeDeleted.push(index);
}
});
if (toBeTiledNodes.length > 1) {
var _boundingBox = toBeTiledNodes.boundingBox();
componentCenters.push({ x: _boundingBox.x1 + _boundingBox.w / 2, y: _boundingBox.y1 + _boundingBox.h / 2 });
components3.push(toBeTiledNodes);
spectralResult.push(tempSpectralResult);
for (var i2 = indexesToBeDeleted.length - 1; i2 >= 0; i2--) {
components3.splice(indexesToBeDeleted[i2], 1);
spectralResult.splice(indexesToBeDeleted[i2], 1);
componentCenters.splice(indexesToBeDeleted[i2], 1);
}
;
}
}
components3.forEach(function(component2, index) {
options2.eles = component2;
coseResult.push(coseLayout(options2, spectralResult[index]));
aux.relocateComponent(componentCenters[index], coseResult[index], options2);
});
} else {
components3.forEach(function(component2, index) {
aux.relocateComponent(componentCenters[index], spectralResult[index], options2);
});
}
var componentsEvaluated = /* @__PURE__ */ new Set();
if (components3.length > 1) {
var subgraphs = [];
var hiddenEles = eles.filter(function(ele) {
return ele.css("display") == "none";
});
components3.forEach(function(component2, index) {
var nodeIndexes2 = void 0;
if (options2.quality == "draft") {
nodeIndexes2 = spectralResult[index].nodeIndexes;
}
if (component2.nodes().not(hiddenEles).length > 0) {
var subgraph = {};
subgraph.edges = [];
subgraph.nodes = [];
var nodeIndex = void 0;
component2.nodes().not(hiddenEles).forEach(function(node2) {
if (options2.quality == "draft") {
if (!node2.isParent()) {
nodeIndex = nodeIndexes2.get(node2.id());
subgraph.nodes.push({ x: spectralResult[index].xCoords[nodeIndex] - node2.boundingbox().w / 2, y: spectralResult[index].yCoords[nodeIndex] - node2.boundingbox().h / 2, width: node2.boundingbox().w, height: node2.boundingbox().h });
} else {
var parentInfo = aux.calcBoundingBox(node2, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes2);
subgraph.nodes.push({ x: parentInfo.topLeftX, y: parentInfo.topLeftY, width: parentInfo.width, height: parentInfo.height });
}
} else {
if (coseResult[index][node2.id()]) {
subgraph.nodes.push({ x: coseResult[index][node2.id()].getLeft(), y: coseResult[index][node2.id()].getTop(), width: coseResult[index][node2.id()].getWidth(), height: coseResult[index][node2.id()].getHeight() });
}
}
});
component2.edges().forEach(function(edge) {
var source = edge.source();
var target = edge.target();
if (source.css("display") != "none" && target.css("display") != "none") {
if (options2.quality == "draft") {
var sourceNodeIndex = nodeIndexes2.get(source.id());
var targetNodeIndex = nodeIndexes2.get(target.id());
var sourceCenter = [];
var targetCenter = [];
if (source.isParent()) {
var parentInfo = aux.calcBoundingBox(source, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes2);
sourceCenter.push(parentInfo.topLeftX + parentInfo.width / 2);
sourceCenter.push(parentInfo.topLeftY + parentInfo.height / 2);
} else {
sourceCenter.push(spectralResult[index].xCoords[sourceNodeIndex]);
sourceCenter.push(spectralResult[index].yCoords[sourceNodeIndex]);
}
if (target.isParent()) {
var _parentInfo = aux.calcBoundingBox(target, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes2);
targetCenter.push(_parentInfo.topLeftX + _parentInfo.width / 2);
targetCenter.push(_parentInfo.topLeftY + _parentInfo.height / 2);
} else {
targetCenter.push(spectralResult[index].xCoords[targetNodeIndex]);
targetCenter.push(spectralResult[index].yCoords[targetNodeIndex]);
}
subgraph.edges.push({ startX: sourceCenter[0], startY: sourceCenter[1], endX: targetCenter[0], endY: targetCenter[1] });
} else {
if (coseResult[index][source.id()] && coseResult[index][target.id()]) {
subgraph.edges.push({ startX: coseResult[index][source.id()].getCenterX(), startY: coseResult[index][source.id()].getCenterY(), endX: coseResult[index][target.id()].getCenterX(), endY: coseResult[index][target.id()].getCenterY() });
}
}
}
});
if (subgraph.nodes.length > 0) {
subgraphs.push(subgraph);
componentsEvaluated.add(index);
}
}
});
var shiftResult = layUtil.packComponents(subgraphs, options2.randomize).shifts;
if (options2.quality == "draft") {
spectralResult.forEach(function(result2, index) {
var newXCoords = result2.xCoords.map(function(x5) {
return x5 + shiftResult[index].dx;
});
var newYCoords = result2.yCoords.map(function(y6) {
return y6 + shiftResult[index].dy;
});
result2.xCoords = newXCoords;
result2.yCoords = newYCoords;
});
} else {
var _count = 0;
componentsEvaluated.forEach(function(index) {
Object.keys(coseResult[index]).forEach(function(item) {
var nodeRectangle = coseResult[index][item];
nodeRectangle.setCenter(nodeRectangle.getCenterX() + shiftResult[_count].dx, nodeRectangle.getCenterY() + shiftResult[_count].dy);
});
_count++;
});
}
}
}
}
var getPositions = /* @__PURE__ */ __name(function getPositions2(ele, i3) {
if (options2.quality == "default" || options2.quality == "proof") {
if (typeof ele === "number") {
ele = i3;
}
var pos = void 0;
var node2 = void 0;
var theId = ele.data("id");
coseResult.forEach(function(result2) {
if (theId in result2) {
pos = { x: result2[theId].getRect().getCenterX(), y: result2[theId].getRect().getCenterY() };
node2 = result2[theId];
}
});
if (options2.nodeDimensionsIncludeLabels) {
if (node2.labelWidth) {
if (node2.labelPosHorizontal == "left") {
pos.x += node2.labelWidth / 2;
} else if (node2.labelPosHorizontal == "right") {
pos.x -= node2.labelWidth / 2;
}
}
if (node2.labelHeight) {
if (node2.labelPosVertical == "top") {
pos.y += node2.labelHeight / 2;
} else if (node2.labelPosVertical == "bottom") {
pos.y -= node2.labelHeight / 2;
}
}
}
if (pos == void 0) pos = { x: ele.position("x"), y: ele.position("y") };
return {
x: pos.x,
y: pos.y
};
} else {
var _pos = void 0;
spectralResult.forEach(function(result2) {
var index = result2.nodeIndexes.get(ele.id());
if (index != void 0) {
_pos = { x: result2.xCoords[index], y: result2.yCoords[index] };
}
});
if (_pos == void 0) _pos = { x: ele.position("x"), y: ele.position("y") };
return {
x: _pos.x,
y: _pos.y
};
}
}, "getPositions");
if (options2.quality == "default" || options2.quality == "proof" || options2.randomize) {
var parentsWithoutChildren = aux.calcParentsWithoutChildren(cy, eles);
var _hiddenEles = eles.filter(function(ele) {
return ele.css("display") == "none";
});
options2.eles = eles.not(_hiddenEles);
eles.nodes().not(":parent").not(_hiddenEles).layoutPositions(layout7, options2, getPositions);
if (parentsWithoutChildren.length > 0) {
parentsWithoutChildren.forEach(function(ele) {
ele.position(getPositions(ele));
});
}
} else {
console.log("If randomize option is set to false, then quality option must be 'default' or 'proof'.");
}
}, "run")
}]);
return Layout3;
})();
module3.exports = Layout2;
})
),
/***/
657: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var aux = __webpack_require__2(548);
var Matrix = __webpack_require__2(140).layoutBase.Matrix;
var SVD = __webpack_require__2(140).layoutBase.SVD;
var spectralLayout = /* @__PURE__ */ __name(function spectralLayout2(options2) {
var cy = options2.cy;
var eles = options2.eles;
var nodes5 = eles.nodes();
var parentNodes = eles.nodes(":parent");
var dummyNodes = /* @__PURE__ */ new Map();
var nodeIndexes = /* @__PURE__ */ new Map();
var parentChildMap = /* @__PURE__ */ new Map();
var allNodesNeighborhood = [];
var xCoords = [];
var yCoords = [];
var samplesColumn = [];
var minDistancesColumn = [];
var C3 = [];
var PHI = [];
var INV = [];
var firstSample = void 0;
var nodeSize = void 0;
var infinity = 1e8;
var small = 1e-9;
var piTol = options2.piTol;
var samplingType = options2.samplingType;
var nodeSeparation = options2.nodeSeparation;
var sampleSize = void 0;
var randomSampleCR = /* @__PURE__ */ __name(function randomSampleCR2() {
var sample2 = 0;
var count2 = 0;
var flag = false;
while (count2 < sampleSize) {
sample2 = Math.floor(Math.random() * nodeSize);
flag = false;
for (var i3 = 0; i3 < count2; i3++) {
if (samplesColumn[i3] == sample2) {
flag = true;
break;
}
}
if (!flag) {
samplesColumn[count2] = sample2;
count2++;
} else {
continue;
}
}
}, "randomSampleCR");
var BFS = /* @__PURE__ */ __name(function BFS2(pivot, index2, samplingMethod) {
var path4 = [];
var front = 0;
var back = 0;
var current = 0;
var temp = void 0;
var distance3 = [];
var max_dist = 0;
var max_ind = 1;
for (var i3 = 0; i3 < nodeSize; i3++) {
distance3[i3] = infinity;
}
path4[back] = pivot;
distance3[pivot] = 0;
while (back >= front) {
current = path4[front++];
var neighbors = allNodesNeighborhood[current];
for (var _i = 0; _i < neighbors.length; _i++) {
temp = nodeIndexes.get(neighbors[_i]);
if (distance3[temp] == infinity) {
distance3[temp] = distance3[current] + 1;
path4[++back] = temp;
}
}
C3[current][index2] = distance3[current] * nodeSeparation;
}
if (samplingMethod) {
for (var _i2 = 0; _i2 < nodeSize; _i2++) {
if (C3[_i2][index2] < minDistancesColumn[_i2]) minDistancesColumn[_i2] = C3[_i2][index2];
}
for (var _i3 = 0; _i3 < nodeSize; _i3++) {
if (minDistancesColumn[_i3] > max_dist) {
max_dist = minDistancesColumn[_i3];
max_ind = _i3;
}
}
}
return max_ind;
}, "BFS");
var allBFS = /* @__PURE__ */ __name(function allBFS2(samplingMethod) {
var sample2 = void 0;
if (!samplingMethod) {
randomSampleCR();
for (var i3 = 0; i3 < sampleSize; i3++) {
BFS(samplesColumn[i3], i3, samplingMethod, false);
}
} else {
sample2 = Math.floor(Math.random() * nodeSize);
firstSample = sample2;
for (var _i4 = 0; _i4 < nodeSize; _i4++) {
minDistancesColumn[_i4] = infinity;
}
for (var _i5 = 0; _i5 < sampleSize; _i5++) {
samplesColumn[_i5] = sample2;
sample2 = BFS(sample2, _i5, samplingMethod);
}
}
for (var _i6 = 0; _i6 < nodeSize; _i6++) {
for (var j3 = 0; j3 < sampleSize; j3++) {
C3[_i6][j3] *= C3[_i6][j3];
}
}
for (var _i7 = 0; _i7 < sampleSize; _i7++) {
PHI[_i7] = [];
}
for (var _i8 = 0; _i8 < sampleSize; _i8++) {
for (var _j = 0; _j < sampleSize; _j++) {
PHI[_i8][_j] = C3[samplesColumn[_j]][_i8];
}
}
}, "allBFS");
var sample = /* @__PURE__ */ __name(function sample2() {
var SVDResult = SVD.svd(PHI);
var a_q = SVDResult.S;
var a_u = SVDResult.U;
var a_v = SVDResult.V;
var max_s = a_q[0] * a_q[0] * a_q[0];
var a_Sig = [];
for (var i3 = 0; i3 < sampleSize; i3++) {
a_Sig[i3] = [];
for (var j3 = 0; j3 < sampleSize; j3++) {
a_Sig[i3][j3] = 0;
if (i3 == j3) {
a_Sig[i3][j3] = a_q[i3] / (a_q[i3] * a_q[i3] + max_s / (a_q[i3] * a_q[i3]));
}
}
}
INV = Matrix.multMat(Matrix.multMat(a_v, a_Sig), Matrix.transpose(a_u));
}, "sample");
var powerIteration = /* @__PURE__ */ __name(function powerIteration2() {
var theta1 = void 0;
var theta2 = void 0;
var Y1 = [];
var Y22 = [];
var V1 = [];
var V22 = [];
for (var i3 = 0; i3 < nodeSize; i3++) {
Y1[i3] = Math.random();
Y22[i3] = Math.random();
}
Y1 = Matrix.normalize(Y1);
Y22 = Matrix.normalize(Y22);
var count2 = 0;
var current = small;
var previous = small;
var temp = void 0;
while (true) {
count2++;
for (var _i9 = 0; _i9 < nodeSize; _i9++) {
V1[_i9] = Y1[_i9];
}
Y1 = Matrix.multGamma(Matrix.multL(Matrix.multGamma(V1), C3, INV));
theta1 = Matrix.dotProduct(V1, Y1);
Y1 = Matrix.normalize(Y1);
current = Matrix.dotProduct(V1, Y1);
temp = Math.abs(current / previous);
if (temp <= 1 + piTol && temp >= 1) {
break;
}
previous = current;
}
for (var _i10 = 0; _i10 < nodeSize; _i10++) {
V1[_i10] = Y1[_i10];
}
count2 = 0;
previous = small;
while (true) {
count2++;
for (var _i11 = 0; _i11 < nodeSize; _i11++) {
V22[_i11] = Y22[_i11];
}
V22 = Matrix.minusOp(V22, Matrix.multCons(V1, Matrix.dotProduct(V1, V22)));
Y22 = Matrix.multGamma(Matrix.multL(Matrix.multGamma(V22), C3, INV));
theta2 = Matrix.dotProduct(V22, Y22);
Y22 = Matrix.normalize(Y22);
current = Matrix.dotProduct(V22, Y22);
temp = Math.abs(current / previous);
if (temp <= 1 + piTol && temp >= 1) {
break;
}
previous = current;
}
for (var _i12 = 0; _i12 < nodeSize; _i12++) {
V22[_i12] = Y22[_i12];
}
xCoords = Matrix.multCons(V1, Math.sqrt(Math.abs(theta1)));
yCoords = Matrix.multCons(V22, Math.sqrt(Math.abs(theta2)));
}, "powerIteration");
aux.connectComponents(cy, eles, aux.getTopMostNodes(nodes5), dummyNodes);
parentNodes.forEach(function(ele) {
aux.connectComponents(cy, eles, aux.getTopMostNodes(ele.descendants().intersection(eles)), dummyNodes);
});
var index = 0;
for (var i2 = 0; i2 < nodes5.length; i2++) {
if (!nodes5[i2].isParent()) {
nodeIndexes.set(nodes5[i2].id(), index++);
}
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = void 0;
try {
for (var _iterator = dummyNodes.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
nodeIndexes.set(key, index++);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
for (var _i13 = 0; _i13 < nodeIndexes.size; _i13++) {
allNodesNeighborhood[_i13] = [];
}
parentNodes.forEach(function(ele) {
var children2 = ele.children().intersection(eles);
while (children2.nodes(":childless").length == 0) {
children2 = children2.nodes()[0].children().intersection(eles);
}
var index2 = 0;
var min9 = children2.nodes(":childless")[0].connectedEdges().length;
children2.nodes(":childless").forEach(function(ele2, i3) {
if (ele2.connectedEdges().length < min9) {
min9 = ele2.connectedEdges().length;
index2 = i3;
}
});
parentChildMap.set(ele.id(), children2.nodes(":childless")[index2].id());
});
nodes5.forEach(function(ele) {
var eleIndex = void 0;
if (ele.isParent()) eleIndex = nodeIndexes.get(parentChildMap.get(ele.id()));
else eleIndex = nodeIndexes.get(ele.id());
ele.neighborhood().nodes().forEach(function(node2) {
if (eles.intersection(ele.edgesWith(node2)).length > 0) {
if (node2.isParent()) allNodesNeighborhood[eleIndex].push(parentChildMap.get(node2.id()));
else allNodesNeighborhood[eleIndex].push(node2.id());
}
});
});
var _loop = /* @__PURE__ */ __name(function _loop2(_key2) {
var eleIndex = nodeIndexes.get(_key2);
var disconnectedId = void 0;
dummyNodes.get(_key2).forEach(function(id32) {
if (cy.getElementById(id32).isParent()) disconnectedId = parentChildMap.get(id32);
else disconnectedId = id32;
allNodesNeighborhood[eleIndex].push(disconnectedId);
allNodesNeighborhood[nodeIndexes.get(disconnectedId)].push(_key2);
});
}, "_loop");
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = void 0;
try {
for (var _iterator2 = dummyNodes.keys()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var _key = _step2.value;
_loop(_key);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
nodeSize = nodeIndexes.size;
var spectralResult = void 0;
if (nodeSize > 2) {
sampleSize = nodeSize < options2.sampleSize ? nodeSize : options2.sampleSize;
for (var _i14 = 0; _i14 < nodeSize; _i14++) {
C3[_i14] = [];
}
for (var _i15 = 0; _i15 < sampleSize; _i15++) {
INV[_i15] = [];
}
if (options2.quality == "draft" || options2.step == "all") {
allBFS(samplingType);
sample();
powerIteration();
spectralResult = { nodeIndexes, xCoords, yCoords };
} else {
nodeIndexes.forEach(function(value2, key2) {
xCoords.push(cy.getElementById(key2).position("x"));
yCoords.push(cy.getElementById(key2).position("y"));
});
spectralResult = { nodeIndexes, xCoords, yCoords };
}
return spectralResult;
} else {
var iterator = nodeIndexes.keys();
var firstNode = cy.getElementById(iterator.next().value);
var firstNodePos = firstNode.position();
var firstNodeWidth = firstNode.outerWidth();
xCoords.push(firstNodePos.x);
yCoords.push(firstNodePos.y);
if (nodeSize == 2) {
var secondNode = cy.getElementById(iterator.next().value);
var secondNodeWidth = secondNode.outerWidth();
xCoords.push(firstNodePos.x + firstNodeWidth / 2 + secondNodeWidth / 2 + options2.idealEdgeLength);
yCoords.push(firstNodePos.y);
}
spectralResult = { nodeIndexes, xCoords, yCoords };
return spectralResult;
}
}, "spectralLayout");
module3.exports = { spectralLayout };
})
),
/***/
579: (
/***/
((module3, __unused_webpack_exports, __webpack_require__2) => {
var impl2 = __webpack_require__2(212);
var register = /* @__PURE__ */ __name(function register2(cytoscape4) {
if (!cytoscape4) {
return;
}
cytoscape4("layout", "fcose", impl2);
}, "register");
if (typeof cytoscape !== "undefined") {
register(cytoscape);
}
module3.exports = register;
})
),
/***/
140: (
/***/
((module3) => {
module3.exports = __WEBPACK_EXTERNAL_MODULE__140__;
})
)
/******/
};
var __webpack_module_cache__ = {};
function __webpack_require__(moduleId) {
var cachedModule = __webpack_module_cache__[moduleId];
if (cachedModule !== void 0) {
return cachedModule.exports;
}
var module3 = __webpack_module_cache__[moduleId] = {
/******/
// no module.id needed
/******/
// no module.loaded needed
/******/
exports: {}
/******/
};
__webpack_modules__[moduleId](module3, module3.exports, __webpack_require__);
return module3.exports;
}
__name(__webpack_require__, "__webpack_require__");
var __webpack_exports__ = __webpack_require__(579);
return __webpack_exports__;
})()
);
});
}
});
// src/diagrams/architecture/architectureIcons.ts
var wrapIcon, architectureIcons;
var init_architectureIcons = __esm({
"src/diagrams/architecture/architectureIcons.ts"() {
"use strict";
init_icons();
wrapIcon = /* @__PURE__ */ __name((icon2) => {
return `
|\n/), "splitLines");
wrapText = /* @__PURE__ */ __name((text4, maxChars) => {
if (text4.length <= maxChars) {
return text4;
}
const lines = [];
for (const word of text4.split(/\s+/)) {
const last3 = lines.length - 1;
if (last3 >= 0 && lines[last3].length + 1 + word.length <= maxChars) {
lines[last3] += " " + word;
} else {
lines.push(word);
}
}
return lines.join("\n");
}, "wrapText");
drawMultilineText = /* @__PURE__ */ __name((g2, text4, x5, y6, cls, anchor2, fontSize) => {
const lines = splitLines(text4);
const lh = fontSize * 1.05;
const el = g2.append("text").attr("class", cls).attr("text-anchor", anchor2).attr("x", x5).attr("y", y6 - (lines.length - 1) * lh / 2);
for (const [i2, line2] of lines.entries()) {
el.append("tspan").attr("x", x5).attr("dy", i2 === 0 ? 0 : lh).text(line2);
}
return el;
}, "drawMultilineText");
lerp = /* @__PURE__ */ __name((a2, b3, t4) => a2 + (b3 - a2) * t4, "lerp");
drawLine = /* @__PURE__ */ __name((g2, x1, y1, x22, y22, cls, roughContext) => {
if (roughContext) {
const roughNode = roughContext.roughSvg.line(x1, y1, x22, y22, {
roughness: 1.5,
seed: roughContext.seed,
stroke: roughContext.lineColor,
strokeWidth: 2
});
g2.append(() => roughNode).attr("class", cls);
return void 0;
}
return g2.append("line").attr("class", cls).attr("x1", x1).attr("y1", y1).attr("x2", x22).attr("y2", y22);
}, "drawLine");
renderer9 = { draw: draw25 };
}
});
// src/diagrams/ishikawa/ishikawaStyles.ts
var getStyles19, ishikawaStyles_default;
var init_ishikawaStyles = __esm({
"src/diagrams/ishikawa/ishikawaStyles.ts"() {
"use strict";
getStyles19 = /* @__PURE__ */ __name((options2) => `
.ishikawa .ishikawa-spine,
.ishikawa .ishikawa-branch,
.ishikawa .ishikawa-sub-branch {
stroke: ${options2.lineColor};
stroke-width: 2;
fill: none;
}
.ishikawa .ishikawa-sub-branch {
stroke-width: 1;
}
.ishikawa .ishikawa-arrow {
fill: ${options2.lineColor};
}
.ishikawa .ishikawa-head {
fill: ${options2.mainBkg};
stroke: ${options2.lineColor};
stroke-width: 2;
}
.ishikawa .ishikawa-label-box {
fill: ${options2.mainBkg};
stroke: ${options2.lineColor};
stroke-width: 2;
}
.ishikawa text {
font-family: ${options2.fontFamily};
font-size: ${options2.fontSize};
fill: ${options2.textColor};
}
.ishikawa .ishikawa-head-label {
font-weight: 600;
text-anchor: middle;
dominant-baseline: middle;
font-size: 14px;
}
.ishikawa .ishikawa-label {
text-anchor: end;
}
.ishikawa .ishikawa-label.cause {
text-anchor: middle;
dominant-baseline: middle;
}
.ishikawa .ishikawa-label.align {
text-anchor: end;
dominant-baseline: middle;
}
.ishikawa .ishikawa-label.up {
dominant-baseline: baseline;
}
.ishikawa .ishikawa-label.down {
dominant-baseline: hanging;
}
`, "getStyles");
ishikawaStyles_default = getStyles19;
}
});
// src/diagrams/ishikawa/ishikawaDiagram.ts
var ishikawaDiagram_exports = {};
__export(ishikawaDiagram_exports, {
diagram: () => diagram26
});
var diagram26;
var init_ishikawaDiagram = __esm({
"src/diagrams/ishikawa/ishikawaDiagram.ts"() {
"use strict";
init_ishikawa();
init_ishikawaDb();
init_ishikawaRenderer();
init_ishikawaStyles();
diagram26 = {
parser: ishikawa_default,
get db() {
return new IshikawaDB();
},
renderer: renderer9,
styles: ishikawaStyles_default
};
}
});
// src/diagrams/venn/parser/venn.jison
var parser24, venn_default;
var init_venn = __esm({
"src/diagrams/venn/parser/venn.jison"() {
"use strict";
parser24 = (function() {
var o2 = /* @__PURE__ */ __name(function(k2, v3, o3, l4) {
for (o3 = o3 || {}, l4 = k2.length; l4--; o3[k2[l4]] = v3) ;
return o3;
}, "o"), $V0 = [5, 8], $V1 = [7, 8, 11, 12, 17, 19, 22, 24], $V2 = [1, 17], $V3 = [1, 18], $V4 = [7, 8, 11, 12, 14, 15, 16, 17, 19, 20, 21, 22, 24, 27], $V5 = [1, 31], $V6 = [1, 39], $V7 = [7, 8, 11, 12, 17, 19, 22, 24, 27], $V8 = [1, 57], $V9 = [1, 56], $Va = [1, 58], $Vb = [1, 59], $Vc = [1, 60], $Vd = [7, 8, 11, 12, 16, 17, 19, 20, 22, 24, 27, 31, 32, 33];
var parser26 = {
trace: /* @__PURE__ */ __name(function trace() {
}, "trace"),
yy: {},
symbols_: { "error": 2, "start": 3, "optNewlines": 4, "VENN": 5, "document": 6, "EOF": 7, "NEWLINE": 8, "line": 9, "statement": 10, "TITLE": 11, "SET": 12, "identifier": 13, "BRACKET_LABEL": 14, "COLON": 15, "NUMERIC": 16, "UNION": 17, "identifierList": 18, "TEXT": 19, "IDENTIFIER": 20, "STRING": 21, "INDENT_TEXT": 22, "indentedTextTail": 23, "STYLE": 24, "stylesOpt": 25, "styleField": 26, "COMMA": 27, "styleValue": 28, "valueTokens": 29, "valueToken": 30, "HEXCOLOR": 31, "RGBCOLOR": 32, "RGBACOLOR": 33, "$accept": 0, "$end": 1 },
terminals_: { 2: "error", 5: "VENN", 7: "EOF", 8: "NEWLINE", 11: "TITLE", 12: "SET", 14: "BRACKET_LABEL", 15: "COLON", 16: "NUMERIC", 17: "UNION", 19: "TEXT", 20: "IDENTIFIER", 21: "STRING", 22: "INDENT_TEXT", 24: "STYLE", 27: "COMMA", 31: "HEXCOLOR", 32: "RGBCOLOR", 33: "RGBACOLOR" },
productions_: [0, [3, 4], [4, 0], [4, 2], [6, 0], [6, 2], [9, 1], [9, 1], [10, 1], [10, 2], [10, 3], [10, 4], [10, 5], [10, 2], [10, 3], [10, 4], [10, 5], [10, 3], [10, 3], [10, 3], [10, 4], [10, 4], [10, 2], [10, 3], [23, 1], [23, 1], [23, 1], [23, 2], [23, 2], [25, 1], [25, 3], [26, 3], [28, 1], [28, 1], [29, 1], [29, 2], [30, 1], [30, 1], [30, 1], [30, 1], [30, 1], [18, 1], [18, 3], [13, 1], [13, 1]],
performAction: /* @__PURE__ */ __name(function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {
var $0 = $$.length - 1;
switch (yystate) {
case 1:
return $$[$0 - 1];
break;
case 2:
case 3:
case 4:
this.$ = [];
break;
case 5:
$$[$0 - 1].push($$[$0]);
this.$ = $$[$0 - 1];
break;
case 6:
this.$ = [];
break;
case 7:
case 22:
case 32:
case 36:
case 37:
case 38:
case 39:
case 40:
this.$ = $$[$0];
break;
case 8:
yy.setDiagramTitle($$[$0].substr(6));
this.$ = $$[$0].substr(6);
break;
case 9:
yy.addSubsetData([$$[$0]], void 0, void 0);
if (yy.setIndentMode) {
yy.setIndentMode(true);
}
break;
case 10:
yy.addSubsetData([$$[$0 - 1]], $$[$0], void 0);
if (yy.setIndentMode) {
yy.setIndentMode(true);
}
break;
case 11:
yy.addSubsetData([$$[$0 - 2]], void 0, parseFloat($$[$0]));
if (yy.setIndentMode) {
yy.setIndentMode(true);
}
break;
case 12:
yy.addSubsetData([$$[$0 - 3]], $$[$0 - 2], parseFloat($$[$0]));
if (yy.setIndentMode) {
yy.setIndentMode(true);
}
break;
case 13:
if ($$[$0].length < 2) {
throw new Error("union requires multiple identifiers");
}
if (yy.validateUnionIdentifiers) {
yy.validateUnionIdentifiers($$[$0]);
}
yy.addSubsetData($$[$0], void 0, void 0);
if (yy.setIndentMode) {
yy.setIndentMode(true);
}
break;
case 14:
if ($$[$0 - 1].length < 2) {
throw new Error("union requires multiple identifiers");
}
if (yy.validateUnionIdentifiers) {
yy.validateUnionIdentifiers($$[$0 - 1]);
}
yy.addSubsetData($$[$0 - 1], $$[$0], void 0);
if (yy.setIndentMode) {
yy.setIndentMode(true);
}
break;
case 15:
if ($$[$0 - 2].length < 2) {
throw new Error("union requires multiple identifiers");
}
if (yy.validateUnionIdentifiers) {
yy.validateUnionIdentifiers($$[$0 - 2]);
}
yy.addSubsetData($$[$0 - 2], void 0, parseFloat($$[$0]));
if (yy.setIndentMode) {
yy.setIndentMode(true);
}
break;
case 16:
if ($$[$0 - 3].length < 2) {
throw new Error("union requires multiple identifiers");
}
if (yy.validateUnionIdentifiers) {
yy.validateUnionIdentifiers($$[$0 - 3]);
}
yy.addSubsetData($$[$0 - 3], $$[$0 - 2], parseFloat($$[$0]));
if (yy.setIndentMode) {
yy.setIndentMode(true);
}
break;
case 17:
case 18:
case 19:
yy.addTextData($$[$0 - 1], $$[$0], void 0);
break;
case 20:
case 21:
yy.addTextData($$[$0 - 2], $$[$0 - 1], $$[$0]);
break;
case 23:
yy.addStyleData($$[$0 - 1], $$[$0]);
break;
case 24:
case 25:
case 26:
var cs = yy.getCurrentSets();
if (!cs) throw new Error("text requires set");
yy.addTextData(cs, $$[$0], void 0);
break;
case 27:
case 28:
var cs = yy.getCurrentSets();
if (!cs) throw new Error("text requires set");
yy.addTextData(cs, $$[$0 - 1], $$[$0]);
break;
case 29:
case 41:
this.$ = [$$[$0]];
break;
case 30:
case 42:
this.$ = [...$$[$0 - 2], $$[$0]];
break;
case 31:
this.$ = [$$[$0 - 2], $$[$0]];
break;
case 33:
this.$ = $$[$0].join(" ");
break;
case 34:
this.$ = [$$[$0]];
break;
case 35:
$$[$0 - 1].push($$[$0]);
this.$ = $$[$0 - 1];
break;
case 43:
case 44:
this.$ = $$[$0];
break;
}
}, "anonymous"),
table: [o2($V0, [2, 2], { 3: 1, 4: 2 }), { 1: [3] }, { 5: [1, 3], 8: [1, 4] }, o2($V1, [2, 4], { 6: 5 }), o2($V0, [2, 3]), { 7: [1, 6], 8: [1, 8], 9: 7, 10: 9, 11: [1, 10], 12: [1, 11], 17: [1, 12], 19: [1, 13], 22: [1, 14], 24: [1, 15] }, { 1: [2, 1] }, o2($V1, [2, 5]), o2($V1, [2, 6]), o2($V1, [2, 7]), o2($V1, [2, 8]), { 13: 16, 20: $V2, 21: $V3 }, { 13: 20, 18: 19, 20: $V2, 21: $V3 }, { 13: 20, 18: 21, 20: $V2, 21: $V3 }, { 16: [1, 25], 20: [1, 23], 21: [1, 24], 23: 22 }, { 13: 20, 18: 26, 20: $V2, 21: $V3 }, o2($V1, [2, 9], { 14: [1, 27], 15: [1, 28] }), o2($V4, [2, 43]), o2($V4, [2, 44]), o2($V1, [2, 13], { 14: [1, 29], 15: [1, 30], 27: $V5 }), o2($V4, [2, 41]), { 16: [1, 34], 20: [1, 32], 21: [1, 33], 27: $V5 }, o2($V1, [2, 22]), o2($V1, [2, 24], { 14: [1, 35] }), o2($V1, [2, 25], { 14: [1, 36] }), o2($V1, [2, 26]), { 20: $V6, 25: 37, 26: 38, 27: $V5 }, o2($V1, [2, 10], { 15: [1, 40] }), { 16: [1, 41] }, o2($V1, [2, 14], { 15: [1, 42] }), { 16: [1, 43] }, { 13: 44, 20: $V2, 21: $V3 }, o2($V1, [2, 17], { 14: [1, 45] }), o2($V1, [2, 18], { 14: [1, 46] }), o2($V1, [2, 19]), o2($V1, [2, 27]), o2($V1, [2, 28]), o2($V1, [2, 23], { 27: [1, 47] }), o2($V7, [2, 29]), { 15: [1, 48] }, { 16: [1, 49] }, o2($V1, [2, 11]), { 16: [1, 50] }, o2($V1, [2, 15]), o2($V4, [2, 42]), o2($V1, [2, 20]), o2($V1, [2, 21]), { 20: $V6, 26: 51 }, { 16: $V8, 20: $V9, 21: [1, 53], 28: 52, 29: 54, 30: 55, 31: $Va, 32: $Vb, 33: $Vc }, o2($V1, [2, 12]), o2($V1, [2, 16]), o2($V7, [2, 30]), o2($V7, [2, 31]), o2($V7, [2, 32]), o2($V7, [2, 33], { 30: 61, 16: $V8, 20: $V9, 31: $Va, 32: $Vb, 33: $Vc }), o2($Vd, [2, 34]), o2($Vd, [2, 36]), o2($Vd, [2, 37]), o2($Vd, [2, 38]), o2($Vd, [2, 39]), o2($Vd, [2, 40]), o2($Vd, [2, 35])],
defaultActions: { 6: [2, 1] },
parseError: /* @__PURE__ */ __name(function parseError(str2, hash) {
if (hash.recoverable) {
this.trace(str2);
} else {
var error3 = new Error(str2);
error3.hash = hash;
throw error3;
}
}, "parseError"),
parse: /* @__PURE__ */ __name(function parse7(input) {
var self2 = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF2 = 1;
var args = lstack.slice.call(arguments, 1);
var lexer2 = Object.create(this.lexer);
var sharedState = { yy: {} };
for (var k2 in this.yy) {
if (Object.prototype.hasOwnProperty.call(this.yy, k2)) {
sharedState.yy[k2] = this.yy[k2];
}
}
lexer2.setInput(input, sharedState.yy);
sharedState.yy.lexer = lexer2;
sharedState.yy.parser = this;
if (typeof lexer2.yylloc == "undefined") {
lexer2.yylloc = {};
}
var yyloc = lexer2.yylloc;
lstack.push(yyloc);
var ranges = lexer2.options && lexer2.options.ranges;
if (typeof sharedState.yy.parseError === "function") {
this.parseError = sharedState.yy.parseError;
} else {
this.parseError = Object.getPrototypeOf(this).parseError;
}
function popStack(n2) {
stack.length = stack.length - 2 * n2;
vstack.length = vstack.length - n2;
lstack.length = lstack.length - n2;
}
__name(popStack, "popStack");
function lex() {
var token2;
token2 = tstack.pop() || lexer2.lex() || EOF2;
if (typeof token2 !== "number") {
if (token2 instanceof Array) {
tstack = token2;
token2 = tstack.pop();
}
token2 = self2.symbols_[token2] || token2;
}
return token2;
}
__name(lex, "lex");
var symbol, preErrorSymbol, state3, action, a2, r2, yyval = {}, p3, len, newState2, expected;
while (true) {
state3 = stack[stack.length - 1];
if (this.defaultActions[state3]) {
action = this.defaultActions[state3];
} else {
if (symbol === null || typeof symbol == "undefined") {
symbol = lex();
}
action = table[state3] && table[state3][symbol];
}
if (typeof action === "undefined" || !action.length || !action[0]) {
var errStr = "";
expected = [];
for (p3 in table[state3]) {
if (this.terminals_[p3] && p3 > TERROR) {
expected.push("'" + this.terminals_[p3] + "'");
}
}
if (lexer2.showPosition) {
errStr = "Parse error on line " + (yylineno + 1) + ":\n" + lexer2.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
} else {
errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == EOF2 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
}
this.parseError(errStr, {
text: lexer2.match,
token: this.terminals_[symbol] || symbol,
line: lexer2.yylineno,
loc: yyloc,
expected
});
}
if (action[0] instanceof Array && action.length > 1) {
throw new Error("Parse Error: multiple actions possible at state: " + state3 + ", token: " + symbol);
}
switch (action[0]) {
case 1:
stack.push(symbol);
vstack.push(lexer2.yytext);
lstack.push(lexer2.yylloc);
stack.push(action[1]);
symbol = null;
if (!preErrorSymbol) {
yyleng = lexer2.yyleng;
yytext = lexer2.yytext;
yylineno = lexer2.yylineno;
yyloc = lexer2.yylloc;
if (recovering > 0) {
recovering--;
}
} else {
symbol = preErrorSymbol;
preErrorSymbol = null;
}
break;
case 2:
len = this.productions_[action[1]][1];
yyval.$ = vstack[vstack.length - len];
yyval._$ = {
first_line: lstack[lstack.length - (len || 1)].first_line,
last_line: lstack[lstack.length - 1].last_line,
first_column: lstack[lstack.length - (len || 1)].first_column,
last_column: lstack[lstack.length - 1].last_column
};
if (ranges) {
yyval._$.range = [
lstack[lstack.length - (len || 1)].range[0],
lstack[lstack.length - 1].range[1]
];
}
r2 = this.performAction.apply(yyval, [
yytext,
yyleng,
yylineno,
sharedState.yy,
action[1],
vstack,
lstack
].concat(args));
if (typeof r2 !== "undefined") {
return r2;
}
if (len) {
stack = stack.slice(0, -1 * len * 2);
vstack = vstack.slice(0, -1 * len);
lstack = lstack.slice(0, -1 * len);
}
stack.push(this.productions_[action[1]][0]);
vstack.push(yyval.$);
lstack.push(yyval._$);
newState2 = table[stack[stack.length - 2]][stack[stack.length - 1]];
stack.push(newState2);
break;
case 3:
return true;
}
}
return true;
}, "parse")
};
var lexer = /* @__PURE__ */ (function() {
var lexer2 = {
EOF: 1,
parseError: /* @__PURE__ */ __name(function parseError(str2, hash) {
if (this.yy.parser) {
this.yy.parser.parseError(str2, hash);
} else {
throw new Error(str2);
}
}, "parseError"),
// resets the lexer, sets new input
setInput: /* @__PURE__ */ __name(function(input, yy) {
this.yy = yy || this.yy || {};
this._input = input;
this._more = this._backtrack = this.done = false;
this.yylineno = this.yyleng = 0;
this.yytext = this.matched = this.match = "";
this.conditionStack = ["INITIAL"];
this.yylloc = {
first_line: 1,
first_column: 0,
last_line: 1,
last_column: 0
};
if (this.options.ranges) {
this.yylloc.range = [0, 0];
}
this.offset = 0;
return this;
}, "setInput"),
// consumes and returns one char from the input
input: /* @__PURE__ */ __name(function() {
var ch = this._input[0];
this.yytext += ch;
this.yyleng++;
this.offset++;
this.match += ch;
this.matched += ch;
var lines = ch.match(/(?:\r\n?|\n).*/g);
if (lines) {
this.yylineno++;
this.yylloc.last_line++;
} else {
this.yylloc.last_column++;
}
if (this.options.ranges) {
this.yylloc.range[1]++;
}
this._input = this._input.slice(1);
return ch;
}, "input"),
// unshifts one char (or a string) into the input
unput: /* @__PURE__ */ __name(function(ch) {
var len = ch.length;
var lines = ch.split(/(?:\r\n?|\n)/g);
this._input = ch + this._input;
this.yytext = this.yytext.substr(0, this.yytext.length - len);
this.offset -= len;
var oldLines = this.match.split(/(?:\r\n?|\n)/g);
this.match = this.match.substr(0, this.match.length - 1);
this.matched = this.matched.substr(0, this.matched.length - 1);
if (lines.length - 1) {
this.yylineno -= lines.length - 1;
}
var r2 = this.yylloc.range;
this.yylloc = {
first_line: this.yylloc.first_line,
last_line: this.yylineno + 1,
first_column: this.yylloc.first_column,
last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
};
if (this.options.ranges) {
this.yylloc.range = [r2[0], r2[0] + this.yyleng - len];
}
this.yyleng = this.yytext.length;
return this;
}, "unput"),
// When called from action, caches matched text and appends it on next action
more: /* @__PURE__ */ __name(function() {
this._more = true;
return this;
}, "more"),
// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.
reject: /* @__PURE__ */ __name(function() {
if (this.options.backtrack_lexer) {
this._backtrack = true;
} else {
return this.parseError("Lexical error on line " + (this.yylineno + 1) + ". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n" + this.showPosition(), {
text: "",
token: null,
line: this.yylineno
});
}
return this;
}, "reject"),
// retain first n characters of the match
less: /* @__PURE__ */ __name(function(n2) {
this.unput(this.match.slice(n2));
}, "less"),
// displays already matched input, i.e. for error messages
pastInput: /* @__PURE__ */ __name(function() {
var past = this.matched.substr(0, this.matched.length - this.match.length);
return (past.length > 20 ? "..." : "") + past.substr(-20).replace(/\n/g, "");
}, "pastInput"),
// displays upcoming input, i.e. for error messages
upcomingInput: /* @__PURE__ */ __name(function() {
var next3 = this.match;
if (next3.length < 20) {
next3 += this._input.substr(0, 20 - next3.length);
}
return (next3.substr(0, 20) + (next3.length > 20 ? "..." : "")).replace(/\n/g, "");
}, "upcomingInput"),
// displays the character position where the lexing error occurred, i.e. for error messages
showPosition: /* @__PURE__ */ __name(function() {
var pre = this.pastInput();
var c3 = new Array(pre.length + 1).join("-");
return pre + this.upcomingInput() + "\n" + c3 + "^";
}, "showPosition"),
// test the lexed token: return FALSE when not a match, otherwise return token
test_match: /* @__PURE__ */ __name(function(match2, indexed_rule) {
var token2, lines, backup;
if (this.options.backtrack_lexer) {
backup = {
yylineno: this.yylineno,
yylloc: {
first_line: this.yylloc.first_line,
last_line: this.last_line,
first_column: this.yylloc.first_column,
last_column: this.yylloc.last_column
},
yytext: this.yytext,
match: this.match,
matches: this.matches,
matched: this.matched,
yyleng: this.yyleng,
offset: this.offset,
_more: this._more,
_input: this._input,
yy: this.yy,
conditionStack: this.conditionStack.slice(0),
done: this.done
};
if (this.options.ranges) {
backup.yylloc.range = this.yylloc.range.slice(0);
}
}
lines = match2[0].match(/(?:\r\n?|\n).*/g);
if (lines) {
this.yylineno += lines.length;
}
this.yylloc = {
first_line: this.yylloc.last_line,
last_line: this.yylineno + 1,
first_column: this.yylloc.last_column,
last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match2[0].length
};
this.yytext += match2[0];
this.match += match2[0];
this.matches = match2;
this.yyleng = this.yytext.length;
if (this.options.ranges) {
this.yylloc.range = [this.offset, this.offset += this.yyleng];
}
this._more = false;
this._backtrack = false;
this._input = this._input.slice(match2[0].length);
this.matched += match2[0];
token2 = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);
if (this.done && this._input) {
this.done = false;
}
if (token2) {
return token2;
} else if (this._backtrack) {
for (var k2 in backup) {
this[k2] = backup[k2];
}
return false;
}
return false;
}, "test_match"),
// return next match in input
next: /* @__PURE__ */ __name(function() {
if (this.done) {
return this.EOF;
}
if (!this._input) {
this.done = true;
}
var token2, match2, tempMatch, index;
if (!this._more) {
this.yytext = "";
this.match = "";
}
var rules = this._currentRules();
for (var i2 = 0; i2 < rules.length; i2++) {
tempMatch = this._input.match(this.rules[rules[i2]]);
if (tempMatch && (!match2 || tempMatch[0].length > match2[0].length)) {
match2 = tempMatch;
index = i2;
if (this.options.backtrack_lexer) {
token2 = this.test_match(tempMatch, rules[i2]);
if (token2 !== false) {
return token2;
} else if (this._backtrack) {
match2 = false;
continue;
} else {
return false;
}
} else if (!this.options.flex) {
break;
}
}
}
if (match2) {
token2 = this.test_match(match2, rules[index]);
if (token2 !== false) {
return token2;
}
return false;
}
if (this._input === "") {
return this.EOF;
} else {
return this.parseError("Lexical error on line " + (this.yylineno + 1) + ". Unrecognized text.\n" + this.showPosition(), {
text: "",
token: null,
line: this.yylineno
});
}
}, "next"),
// return next match that has a token
lex: /* @__PURE__ */ __name(function lex() {
var r2 = this.next();
if (r2) {
return r2;
} else {
return this.lex();
}
}, "lex"),
// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)
begin: /* @__PURE__ */ __name(function begin(condition) {
this.conditionStack.push(condition);
}, "begin"),
// pop the previously active lexer condition state off the condition stack
popState: /* @__PURE__ */ __name(function popState() {
var n2 = this.conditionStack.length - 1;
if (n2 > 0) {
return this.conditionStack.pop();
} else {
return this.conditionStack[0];
}
}, "popState"),
// produce the lexer rule set which is active for the currently active lexer condition state
_currentRules: /* @__PURE__ */ __name(function _currentRules() {
if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {
return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
} else {
return this.conditions["INITIAL"].rules;
}
}, "_currentRules"),
// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available
topState: /* @__PURE__ */ __name(function topState(n2) {
n2 = this.conditionStack.length - 1 - Math.abs(n2 || 0);
if (n2 >= 0) {
return this.conditionStack[n2];
} else {
return "INITIAL";
}
}, "topState"),
// alias for begin(condition)
pushState: /* @__PURE__ */ __name(function pushState(condition) {
this.begin(condition);
}, "pushState"),
// return the number of states currently on the stack
stateStackSize: /* @__PURE__ */ __name(function stateStackSize() {
return this.conditionStack.length;
}, "stateStackSize"),
options: { "case-insensitive": true },
performAction: /* @__PURE__ */ __name(function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {
var YYSTATE = YY_START;
switch ($avoiding_name_collisions) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
if (yy.getIndentMode && yy.getIndentMode()) {
yy.consumeIndentText = true;
this.begin("INITIAL");
return 22;
}
break;
case 4:
break;
case 5:
if (yy.setIndentMode) {
yy.setIndentMode(false);
}
this.begin("INITIAL");
this.unput(yy_.yytext);
break;
case 6:
this.begin("bol");
return 8;
break;
case 7:
break;
case 8:
break;
case 9:
return 7;
break;
case 10:
return 11;
break;
case 11:
return 5;
break;
case 12:
return 12;
break;
case 13:
return 17;
break;
case 14:
if (yy.consumeIndentText) {
yy.consumeIndentText = false;
} else {
return 19;
}
break;
case 15:
return 24;
break;
case 16:
yy_.yytext = yy_.yytext.slice(2, -2);
return 14;
break;
case 17:
yy_.yytext = yy_.yytext.slice(1, -1).trim();
return 14;
break;
case 18:
return 16;
break;
case 19:
return 31;
break;
case 20:
return 33;
break;
case 21:
return 32;
break;
case 22:
return 20;
break;
case 23:
return 21;
break;
case 24:
return 27;
break;
case 25:
return 15;
break;
}
}, "anonymous"),
rules: [/^(?:%%(?!\{)[^\n]*)/i, /^(?:[^\}]%%[^\n]*)/i, /^(?:[ \t]+(?=[\n\r]))/i, /^(?:[ \t]+(?=text\b))/i, /^(?:[ \t]+)/i, /^(?:[^ \t\n\r])/i, /^(?:[\n\r]+)/i, /^(?:%%[^\n]*)/i, /^(?:[ \t]+)/i, /^(?:$)/i, /^(?:title\s[^#\n;]+)/i, /^(?:venn-beta\b)/i, /^(?:set\b)/i, /^(?:union\b)/i, /^(?:text\b)/i, /^(?:style\b)/i, /^(?:\["[^\"]*"\])/i, /^(?:\[[^\]\"]+\])/i, /^(?:[+-]?(\d+(\.\d+)?|\.\d+))/i, /^(?:#[0-9a-fA-F]{3,8})/i, /^(?:rgba\(\s*[0-9.]+\s*[,]\s*[0-9.]+\s*[,]\s*[0-9.]+\s*[,]\s*[0-9.]+\s*\))/i, /^(?:rgb\(\s*[0-9.]+\s*[,]\s*[0-9.]+\s*[,]\s*[0-9.]+\s*\))/i, /^(?:[A-Za-z_][A-Za-z0-9\-_]*)/i, /^(?:"[^\"]*")/i, /^(?:,)/i, /^(?::)/i],
conditions: { "bol": { "rules": [0, 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], "inclusive": true }, "INITIAL": { "rules": [0, 1, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25], "inclusive": true } }
};
return lexer2;
})();
parser26.lexer = lexer;
function Parser3() {
this.yy = {};
}
__name(Parser3, "Parser");
Parser3.prototype = parser26;
parser26.Parser = Parser3;
return new Parser3();
})();
parser24.parser = parser24;
venn_default = parser24;
}
});
// src/diagrams/venn/vennDB.ts
function getConfig6() {
return cleanAndMerge(DEFAULT_VENN_CONFIG, getConfig().venn);
}
var subsets, textNodes, styleEntries, knownSets, currentSets, indentMode, addSubsetData, getSubsetData, normalizeText, normalizeStyleValue, addTextData, addStyleData, getStyleData, normalizeIdentifierList, validateUnionIdentifiers, getTextData, getCurrentSets, getIndentMode, setIndentMode, DEFAULT_VENN_CONFIG, customClear, db7;
var init_vennDB = __esm({
"src/diagrams/venn/vennDB.ts"() {
"use strict";
init_utils2();
init_config();
init_commonDb();
init_defaultConfig();
subsets = [];
textNodes = [];
styleEntries = [];
knownSets = /* @__PURE__ */ new Set();
indentMode = false;
addSubsetData = /* @__PURE__ */ __name((identifierList, label, size4) => {
const sets = normalizeIdentifierList(identifierList).sort();
const resolvedSize = size4 ?? 10 / Math.pow(identifierList.length, 2);
currentSets = sets;
if (sets.length === 1) {
knownSets.add(sets[0]);
}
subsets.push({
sets,
size: resolvedSize,
label: label ? normalizeText(label) : void 0
});
}, "addSubsetData");
getSubsetData = /* @__PURE__ */ __name(() => {
return subsets;
}, "getSubsetData");
normalizeText = /* @__PURE__ */ __name((text4) => {
const trimmed = text4.trim();
if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
return trimmed.slice(1, -1);
}
return trimmed;
}, "normalizeText");
normalizeStyleValue = /* @__PURE__ */ __name((value2) => {
return value2 ? normalizeText(value2) : value2;
}, "normalizeStyleValue");
addTextData = /* @__PURE__ */ __name((identifierList, id32, label) => {
const normalizedId = normalizeText(id32);
textNodes.push({
sets: normalizeIdentifierList(identifierList).sort(),
id: normalizedId,
label: label ? normalizeText(label) : void 0
});
}, "addTextData");
addStyleData = /* @__PURE__ */ __name((identifierList, data5) => {
const targets = normalizeIdentifierList(identifierList).sort();
const styles4 = {};
for (const [key, value2] of data5) {
styles4[key] = normalizeStyleValue(value2) ?? value2;
}
styleEntries.push({ targets, styles: styles4 });
}, "addStyleData");
getStyleData = /* @__PURE__ */ __name(() => {
return styleEntries;
}, "getStyleData");
normalizeIdentifierList = /* @__PURE__ */ __name((identifierList) => {
return identifierList.map((identifier2) => normalizeText(identifier2));
}, "normalizeIdentifierList");
validateUnionIdentifiers = /* @__PURE__ */ __name((identifierList) => {
const normalized = normalizeIdentifierList(identifierList);
const unknown = normalized.filter((identifier2) => !knownSets.has(identifier2));
if (unknown.length > 0) {
throw new Error(`unknown set identifier: ${unknown.join(", ")}`);
}
}, "validateUnionIdentifiers");
getTextData = /* @__PURE__ */ __name(() => {
return textNodes;
}, "getTextData");
getCurrentSets = /* @__PURE__ */ __name(() => currentSets, "getCurrentSets");
getIndentMode = /* @__PURE__ */ __name(() => indentMode, "getIndentMode");
setIndentMode = /* @__PURE__ */ __name((enabled) => {
indentMode = enabled;
}, "setIndentMode");
DEFAULT_VENN_CONFIG = defaultConfig_default.venn;
__name(getConfig6, "getConfig");
customClear = /* @__PURE__ */ __name(() => {
clear();
subsets.length = 0;
textNodes.length = 0;
styleEntries.length = 0;
knownSets.clear();
currentSets = void 0;
indentMode = false;
}, "customClear");
db7 = {
getConfig: getConfig6,
clear: customClear,
setAccTitle,
getAccTitle,
setDiagramTitle,
getDiagramTitle,
getAccDescription,
setAccDescription,
addSubsetData,
getSubsetData,
addTextData,
addStyleData,
validateUnionIdentifiers,
getTextData,
getStyleData,
getCurrentSets,
getIndentMode,
setIndentMode
};
}
});
// src/diagrams/venn/styles.ts
var getStyles20, styles_default17;
var init_styles19 = __esm({
"src/diagrams/venn/styles.ts"() {
"use strict";
getStyles20 = /* @__PURE__ */ __name((options2) => `
.venn-title {
font-size: 32px;
fill: ${options2.vennTitleTextColor};
font-family: ${options2.fontFamily};
}
.venn-circle text {
font-size: 48px;
font-family: ${options2.fontFamily};
}
.venn-intersection text {
font-size: 48px;
fill: ${options2.vennSetTextColor};
font-family: ${options2.fontFamily};
}
.venn-text-node {
font-family: ${options2.fontFamily};
color: ${options2.vennSetTextColor};
}
`, "getStyles");
styles_default17 = getStyles20;
}
});
// ../../node_modules/.pnpm/@upsetjs+venn.js@2.0.0/node_modules/@upsetjs/venn.js/build/venn.esm.js
function intersectionArea(circles, stats) {
const intersectionPoints = getIntersectionPoints(circles);
const innerPoints = intersectionPoints.filter((p3) => containedInCircles(p3, circles));
let arcArea = 0;
let polygonArea = 0;
const arcs = [];
if (innerPoints.length > 1) {
const center4 = getCenter(innerPoints);
for (let i2 = 0; i2 < innerPoints.length; ++i2) {
const p3 = innerPoints[i2];
p3.angle = Math.atan2(p3.x - center4.x, p3.y - center4.y);
}
innerPoints.sort((a2, b3) => b3.angle - a2.angle);
let p22 = innerPoints[innerPoints.length - 1];
for (let i2 = 0; i2 < innerPoints.length; ++i2) {
const p1 = innerPoints[i2];
polygonArea += (p22.x + p1.x) * (p1.y - p22.y);
const midPoint = { x: (p1.x + p22.x) / 2, y: (p1.y + p22.y) / 2 };
let arc = null;
for (let j3 = 0; j3 < p1.parentIndex.length; ++j3) {
if (p22.parentIndex.includes(p1.parentIndex[j3])) {
const circle6 = circles[p1.parentIndex[j3]];
const a1 = Math.atan2(p1.x - circle6.x, p1.y - circle6.y);
const a2 = Math.atan2(p22.x - circle6.x, p22.y - circle6.y);
let angleDiff = a2 - a1;
if (angleDiff < 0) {
angleDiff += 2 * Math.PI;
}
const a3 = a2 - angleDiff / 2;
let width3 = distance2(midPoint, {
x: circle6.x + circle6.radius * Math.sin(a3),
y: circle6.y + circle6.radius * Math.cos(a3)
});
if (width3 > circle6.radius * 2) {
width3 = circle6.radius * 2;
}
if (arc == null || arc.width > width3) {
arc = { circle: circle6, width: width3, p1, p2: p22, large: width3 > circle6.radius, sweep: true };
}
}
}
if (arc != null) {
arcs.push(arc);
arcArea += circleArea(arc.circle.radius, arc.width);
p22 = p1;
}
}
} else {
let smallest = circles[0];
for (let i2 = 1; i2 < circles.length; ++i2) {
if (circles[i2].radius < smallest.radius) {
smallest = circles[i2];
}
}
let disjoint = false;
for (let i2 = 0; i2 < circles.length; ++i2) {
if (distance2(circles[i2], smallest) > Math.abs(smallest.radius - circles[i2].radius)) {
disjoint = true;
break;
}
}
if (disjoint) {
arcArea = polygonArea = 0;
} else {
arcArea = smallest.radius * smallest.radius * Math.PI;
arcs.push({
circle: smallest,
p1: { x: smallest.x, y: smallest.y + smallest.radius },
p2: { x: smallest.x - SMALL$1, y: smallest.y + smallest.radius },
width: smallest.radius * 2,
large: true,
sweep: true
});
}
}
polygonArea /= 2;
if (stats) {
stats.area = arcArea + polygonArea;
stats.arcArea = arcArea;
stats.polygonArea = polygonArea;
stats.arcs = arcs;
stats.innerPoints = innerPoints;
stats.intersectionPoints = intersectionPoints;
}
return arcArea + polygonArea;
}
function containedInCircles(point8, circles) {
return circles.every((circle6) => distance2(point8, circle6) < circle6.radius + SMALL$1);
}
function getIntersectionPoints(circles) {
const ret = [];
for (let i2 = 0; i2 < circles.length; ++i2) {
for (let j3 = i2 + 1; j3 < circles.length; ++j3) {
const intersect3 = circleCircleIntersection(circles[i2], circles[j3]);
for (const p3 of intersect3) {
p3.parentIndex = [i2, j3];
ret.push(p3);
}
}
}
return ret;
}
function circleArea(r2, width3) {
return r2 * r2 * Math.acos(1 - width3 / r2) - (r2 - width3) * Math.sqrt(width3 * (2 * r2 - width3));
}
function distance2(p1, p22) {
return Math.sqrt((p1.x - p22.x) * (p1.x - p22.x) + (p1.y - p22.y) * (p1.y - p22.y));
}
function circleOverlap(r1, r2, d3) {
if (d3 >= r1 + r2) {
return 0;
}
if (d3 <= Math.abs(r1 - r2)) {
return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
}
const w1 = r1 - (d3 * d3 - r2 * r2 + r1 * r1) / (2 * d3);
const w22 = r2 - (d3 * d3 - r1 * r1 + r2 * r2) / (2 * d3);
return circleArea(r1, w1) + circleArea(r2, w22);
}
function circleCircleIntersection(p1, p22) {
const d3 = distance2(p1, p22);
const r1 = p1.radius;
const r2 = p22.radius;
if (d3 >= r1 + r2 || d3 <= Math.abs(r1 - r2)) {
return [];
}
const a2 = (r1 * r1 - r2 * r2 + d3 * d3) / (2 * d3);
const h3 = Math.sqrt(r1 * r1 - a2 * a2);
const x0 = p1.x + a2 * (p22.x - p1.x) / d3;
const y0 = p1.y + a2 * (p22.y - p1.y) / d3;
const rx = -(p22.y - p1.y) * (h3 / d3);
const ry = -(p22.x - p1.x) * (h3 / d3);
return [
{ x: x0 + rx, y: y0 - ry },
{ x: x0 - rx, y: y0 + ry }
];
}
function getCenter(points) {
const center4 = { x: 0, y: 0 };
for (const point8 of points) {
center4.x += point8.x;
center4.y += point8.y;
}
center4.x /= points.length;
center4.y /= points.length;
return center4;
}
function bisect(f2, a2, b3, parameters) {
parameters = parameters || {};
const maxIterations = parameters.maxIterations || 100;
const tolerance = parameters.tolerance || 1e-10;
const fA = f2(a2);
const fB = f2(b3);
let delta = b3 - a2;
if (fA * fB > 0) {
throw "Initial bisect points must have opposite signs";
}
if (fA === 0) return a2;
if (fB === 0) return b3;
for (let i2 = 0; i2 < maxIterations; ++i2) {
delta /= 2;
const mid = a2 + delta;
const fMid = f2(mid);
if (fMid * fA >= 0) {
a2 = mid;
}
if (Math.abs(delta) < tolerance || fMid === 0) {
return mid;
}
}
return a2 + delta;
}
function zeros(x5) {
const r2 = new Array(x5);
for (let i2 = 0; i2 < x5; ++i2) {
r2[i2] = 0;
}
return r2;
}
function zerosM(x5, y6) {
return zeros(x5).map(() => zeros(y6));
}
function dot(a2, b3) {
let ret = 0;
for (let i2 = 0; i2 < a2.length; ++i2) {
ret += a2[i2] * b3[i2];
}
return ret;
}
function norm2(a2) {
return Math.sqrt(dot(a2, a2));
}
function scale2(ret, value2, c3) {
for (let i2 = 0; i2 < value2.length; ++i2) {
ret[i2] = value2[i2] * c3;
}
}
function weightedSum(ret, w1, v12, w22, v23) {
for (let j3 = 0; j3 < ret.length; ++j3) {
ret[j3] = w1 * v12[j3] + w22 * v23[j3];
}
}
function nelderMead(f2, x0, parameters) {
parameters = parameters || {};
const maxIterations = parameters.maxIterations || x0.length * 200;
const nonZeroDelta = parameters.nonZeroDelta || 1.05;
const zeroDelta = parameters.zeroDelta || 1e-3;
const minErrorDelta = parameters.minErrorDelta || 1e-6;
const minTolerance = parameters.minErrorDelta || 1e-5;
const rho = parameters.rho !== void 0 ? parameters.rho : 1;
const chi = parameters.chi !== void 0 ? parameters.chi : 2;
const psi = parameters.psi !== void 0 ? parameters.psi : -0.5;
const sigma = parameters.sigma !== void 0 ? parameters.sigma : 0.5;
let maxDiff;
const N3 = x0.length;
const simplex = new Array(N3 + 1);
simplex[0] = x0;
simplex[0].fx = f2(x0);
simplex[0].id = 0;
for (let i2 = 0; i2 < N3; ++i2) {
const point8 = x0.slice();
point8[i2] = point8[i2] ? point8[i2] * nonZeroDelta : zeroDelta;
simplex[i2 + 1] = point8;
simplex[i2 + 1].fx = f2(point8);
simplex[i2 + 1].id = i2 + 1;
}
function updateSimplex(value2) {
for (let i2 = 0; i2 < value2.length; i2++) {
simplex[N3][i2] = value2[i2];
}
simplex[N3].fx = value2.fx;
}
__name(updateSimplex, "updateSimplex");
const sortOrder = /* @__PURE__ */ __name((a2, b3) => a2.fx - b3.fx, "sortOrder");
const centroid = x0.slice();
const reflected = x0.slice();
const contracted = x0.slice();
const expanded = x0.slice();
for (let iteration = 0; iteration < maxIterations; ++iteration) {
simplex.sort(sortOrder);
if (parameters.history) {
const sortedSimplex = simplex.map((x5) => {
const state3 = x5.slice();
state3.fx = x5.fx;
state3.id = x5.id;
return state3;
});
sortedSimplex.sort((a2, b3) => a2.id - b3.id);
parameters.history.push({
x: simplex[0].slice(),
fx: simplex[0].fx,
simplex: sortedSimplex
});
}
maxDiff = 0;
for (let i2 = 0; i2 < N3; ++i2) {
maxDiff = Math.max(maxDiff, Math.abs(simplex[0][i2] - simplex[1][i2]));
}
if (Math.abs(simplex[0].fx - simplex[N3].fx) < minErrorDelta && maxDiff < minTolerance) {
break;
}
for (let i2 = 0; i2 < N3; ++i2) {
centroid[i2] = 0;
for (let j3 = 0; j3 < N3; ++j3) {
centroid[i2] += simplex[j3][i2];
}
centroid[i2] /= N3;
}
const worst = simplex[N3];
weightedSum(reflected, 1 + rho, centroid, -rho, worst);
reflected.fx = f2(reflected);
if (reflected.fx < simplex[0].fx) {
weightedSum(expanded, 1 + chi, centroid, -chi, worst);
expanded.fx = f2(expanded);
if (expanded.fx < reflected.fx) {
updateSimplex(expanded);
} else {
updateSimplex(reflected);
}
} else if (reflected.fx >= simplex[N3 - 1].fx) {
let shouldReduce = false;
if (reflected.fx > worst.fx) {
weightedSum(contracted, 1 + psi, centroid, -psi, worst);
contracted.fx = f2(contracted);
if (contracted.fx < worst.fx) {
updateSimplex(contracted);
} else {
shouldReduce = true;
}
} else {
weightedSum(contracted, 1 - psi * rho, centroid, psi * rho, worst);
contracted.fx = f2(contracted);
if (contracted.fx < reflected.fx) {
updateSimplex(contracted);
} else {
shouldReduce = true;
}
}
if (shouldReduce) {
if (sigma >= 1) break;
for (let i2 = 1; i2 < simplex.length; ++i2) {
weightedSum(simplex[i2], 1 - sigma, simplex[0], sigma, simplex[i2]);
simplex[i2].fx = f2(simplex[i2]);
}
}
} else {
updateSimplex(reflected);
}
}
simplex.sort(sortOrder);
return { fx: simplex[0].fx, x: simplex[0] };
}
function wolfeLineSearch(f2, pk, current, next3, a2, c1, c22) {
const phi0 = current.fx;
const phiPrime0 = dot(current.fxprime, pk);
let phi2 = phi0;
let phi_old = phi0;
let phiPrime = phiPrime0;
let a0 = 0;
a2 = a2 || 1;
c1 = c1 || 1e-6;
c22 = c22 || 0.1;
function zoom2(a_lo, a_high, phi_lo) {
for (let iteration = 0; iteration < 16; ++iteration) {
a2 = (a_lo + a_high) / 2;
weightedSum(next3.x, 1, current.x, a2, pk);
phi2 = next3.fx = f2(next3.x, next3.fxprime);
phiPrime = dot(next3.fxprime, pk);
if (phi2 > phi0 + c1 * a2 * phiPrime0 || phi2 >= phi_lo) {
a_high = a2;
} else {
if (Math.abs(phiPrime) <= -c22 * phiPrime0) {
return a2;
}
if (phiPrime * (a_high - a_lo) >= 0) {
a_high = a_lo;
}
a_lo = a2;
phi_lo = phi2;
}
}
return 0;
}
__name(zoom2, "zoom");
for (let iteration = 0; iteration < 10; ++iteration) {
weightedSum(next3.x, 1, current.x, a2, pk);
phi2 = next3.fx = f2(next3.x, next3.fxprime);
phiPrime = dot(next3.fxprime, pk);
if (phi2 > phi0 + c1 * a2 * phiPrime0 || iteration && phi2 >= phi_old) {
return zoom2(a0, a2, phi_old);
}
if (Math.abs(phiPrime) <= -c22 * phiPrime0) {
return a2;
}
if (phiPrime >= 0) {
return zoom2(a2, a0, phi2);
}
phi_old = phi2;
a0 = a2;
a2 *= 2;
}
return a2;
}
function conjugateGradient(f2, initial, params) {
let current = { x: initial.slice(), fx: 0, fxprime: initial.slice() };
let next3 = { x: initial.slice(), fx: 0, fxprime: initial.slice() };
const yk = initial.slice();
let pk;
let temp;
let a2 = 1;
let maxIterations;
params = params || {};
maxIterations = params.maxIterations || initial.length * 20;
current.fx = f2(current.x, current.fxprime);
pk = current.fxprime.slice();
scale2(pk, current.fxprime, -1);
for (let i2 = 0; i2 < maxIterations; ++i2) {
a2 = wolfeLineSearch(f2, pk, current, next3, a2);
if (params.history) {
params.history.push({
x: current.x.slice(),
fx: current.fx,
fxprime: current.fxprime.slice(),
alpha: a2
});
}
if (!a2) {
scale2(pk, current.fxprime, -1);
} else {
weightedSum(yk, 1, next3.fxprime, -1, current.fxprime);
const delta_k = dot(current.fxprime, current.fxprime);
const beta_k = Math.max(0, dot(yk, next3.fxprime) / delta_k);
weightedSum(pk, beta_k, pk, -1, next3.fxprime);
temp = current;
current = next3;
next3 = temp;
}
if (norm2(current.fxprime) <= 1e-5) {
break;
}
}
if (params.history) {
params.history.push({
x: current.x.slice(),
fx: current.fx,
fxprime: current.fxprime.slice(),
alpha: a2
});
}
return current;
}
function venn(sets, parameters = {}) {
parameters.maxIterations = parameters.maxIterations || 500;
const initialLayout = parameters.initialLayout || bestInitialLayout;
const loss = parameters.lossFunction || lossFunction;
const areas = addMissingAreas(sets, parameters);
const circles = initialLayout(areas, parameters);
const setids = Object.keys(circles);
const initial = [];
for (const setid of setids) {
initial.push(circles[setid].x);
initial.push(circles[setid].y);
}
const solution = nelderMead(
(values2) => {
const current = {};
for (let i2 = 0; i2 < setids.length; ++i2) {
const setid = setids[i2];
current[setid] = {
x: values2[2 * i2],
y: values2[2 * i2 + 1],
radius: circles[setid].radius
// size : circles[setid].size
};
}
return loss(current, areas);
},
initial,
parameters
);
const positions2 = solution.x;
for (let i2 = 0; i2 < setids.length; ++i2) {
const setid = setids[i2];
circles[setid].x = positions2[2 * i2];
circles[setid].y = positions2[2 * i2 + 1];
}
return circles;
}
function distanceFromIntersectArea(r1, r2, overlap) {
if (Math.min(r1, r2) * Math.min(r1, r2) * Math.PI <= overlap + SMALL) {
return Math.abs(r1 - r2);
}
return bisect((distance3) => circleOverlap(r1, r2, distance3) - overlap, 0, r1 + r2);
}
function addMissingAreas(areas, parameters = {}) {
const distinct = parameters.distinct;
const r2 = areas.map((s2) => Object.assign({}, s2));
function toKey2(arr) {
return arr.join(";");
}
__name(toKey2, "toKey");
if (distinct) {
const count2 = /* @__PURE__ */ new Map();
for (const area of r2) {
for (let i2 = 0; i2 < area.sets.length; i2++) {
const si = String(area.sets[i2]);
count2.set(si, area.size + (count2.get(si) || 0));
for (let j3 = i2 + 1; j3 < area.sets.length; j3++) {
const sj = String(area.sets[j3]);
const k1 = `${si};${sj}`;
const k2 = `${sj};${si}`;
count2.set(k1, area.size + (count2.get(k1) || 0));
count2.set(k2, area.size + (count2.get(k2) || 0));
}
}
}
for (const area of r2) {
if (area.sets.length < 3) {
area.size = count2.get(toKey2(area.sets));
}
}
}
const ids = [];
const pairs2 = /* @__PURE__ */ new Set();
for (const area of r2) {
if (area.sets.length === 1) {
ids.push(area.sets[0]);
} else if (area.sets.length === 2) {
const a2 = area.sets[0];
const b3 = area.sets[1];
pairs2.add(toKey2(area.sets));
pairs2.add(toKey2([b3, a2]));
}
}
ids.sort((a2, b3) => a2 === b3 ? 0 : a2 < b3 ? -1 : 1);
for (let i2 = 0; i2 < ids.length; ++i2) {
const a2 = ids[i2];
for (let j3 = i2 + 1; j3 < ids.length; ++j3) {
const b3 = ids[j3];
if (!pairs2.has(toKey2([a2, b3]))) {
r2.push({ sets: [a2, b3], size: 0 });
}
}
}
return r2;
}
function getDistanceMatrices(areas, sets, setids) {
const distances2 = zerosM(sets.length, sets.length);
const constraints = zerosM(sets.length, sets.length);
areas.filter((x5) => x5.sets.length === 2).forEach((current) => {
const left3 = setids[current.sets[0]];
const right3 = setids[current.sets[1]];
const r1 = Math.sqrt(sets[left3].size / Math.PI);
const r2 = Math.sqrt(sets[right3].size / Math.PI);
const distance3 = distanceFromIntersectArea(r1, r2, current.size);
distances2[left3][right3] = distances2[right3][left3] = distance3;
let c3 = 0;
if (current.size + 1e-10 >= Math.min(sets[left3].size, sets[right3].size)) {
c3 = 1;
} else if (current.size <= 1e-10) {
c3 = -1;
}
constraints[left3][right3] = constraints[right3][left3] = c3;
});
return { distances: distances2, constraints };
}
function constrainedMDSGradient(x5, fxprime, distances2, constraints) {
for (let i2 = 0; i2 < fxprime.length; ++i2) {
fxprime[i2] = 0;
}
let loss = 0;
for (let i2 = 0; i2 < distances2.length; ++i2) {
const xi = x5[2 * i2];
const yi = x5[2 * i2 + 1];
for (let j3 = i2 + 1; j3 < distances2.length; ++j3) {
const xj = x5[2 * j3];
const yj = x5[2 * j3 + 1];
const dij = distances2[i2][j3];
const constraint = constraints[i2][j3];
const squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi);
const distance3 = Math.sqrt(squaredDistance);
const delta = squaredDistance - dij * dij;
if (constraint > 0 && distance3 <= dij || constraint < 0 && distance3 >= dij) {
continue;
}
loss += 2 * delta * delta;
fxprime[2 * i2] += 4 * delta * (xi - xj);
fxprime[2 * i2 + 1] += 4 * delta * (yi - yj);
fxprime[2 * j3] += 4 * delta * (xj - xi);
fxprime[2 * j3 + 1] += 4 * delta * (yj - yi);
}
}
return loss;
}
function bestInitialLayout(areas, params = {}) {
let initial = greedyLayout(areas, params);
const loss = params.lossFunction || lossFunction;
if (areas.length >= 8) {
const constrained = constrainedMDSLayout(areas, params);
const constrainedLoss = loss(constrained, areas);
const greedyLoss = loss(initial, areas);
if (constrainedLoss + 1e-8 < greedyLoss) {
initial = constrained;
}
}
return initial;
}
function constrainedMDSLayout(areas, params = {}) {
const restarts = params.restarts || 10;
const sets = [];
const setids = {};
for (const area of areas) {
if (area.sets.length === 1) {
setids[area.sets[0]] = sets.length;
sets.push(area);
}
}
let { distances: distances2, constraints } = getDistanceMatrices(areas, sets, setids);
const norm = norm2(distances2.map(norm2)) / distances2.length;
distances2 = distances2.map((row) => row.map((value2) => value2 / norm));
const obj = /* @__PURE__ */ __name((x5, fxprime) => constrainedMDSGradient(x5, fxprime, distances2, constraints), "obj");
let best = null;
for (let i2 = 0; i2 < restarts; ++i2) {
const initial = zeros(distances2.length * 2).map(Math.random);
const current = conjugateGradient(obj, initial, params);
if (!best || current.fx < best.fx) {
best = current;
}
}
const positions2 = best.x;
const circles = {};
for (let i2 = 0; i2 < sets.length; ++i2) {
const set5 = sets[i2];
circles[set5.sets[0]] = {
x: positions2[2 * i2] * norm,
y: positions2[2 * i2 + 1] * norm,
radius: Math.sqrt(set5.size / Math.PI)
};
}
if (params.history) {
for (const h3 of params.history) {
scale2(h3.x, norm);
}
}
return circles;
}
function greedyLayout(areas, params) {
const loss = params && params.lossFunction ? params.lossFunction : lossFunction;
const circles = {};
const setOverlaps = {};
for (const area of areas) {
if (area.sets.length === 1) {
const set5 = area.sets[0];
circles[set5] = {
x: 1e10,
y: 1e10,
rowid: circles.length,
size: area.size,
radius: Math.sqrt(area.size / Math.PI)
};
setOverlaps[set5] = [];
}
}
areas = areas.filter((a2) => a2.sets.length === 2);
for (const current of areas) {
let weight8 = current.weight != null ? current.weight : 1;
const left3 = current.sets[0];
const right3 = current.sets[1];
if (current.size + SMALL >= Math.min(circles[left3].size, circles[right3].size)) {
weight8 = 0;
}
setOverlaps[left3].push({ set: right3, size: current.size, weight: weight8 });
setOverlaps[right3].push({ set: left3, size: current.size, weight: weight8 });
}
const mostOverlapped = [];
Object.keys(setOverlaps).forEach((set5) => {
let size4 = 0;
for (let i2 = 0; i2 < setOverlaps[set5].length; ++i2) {
size4 += setOverlaps[set5][i2].size * setOverlaps[set5][i2].weight;
}
mostOverlapped.push({ set: set5, size: size4 });
});
function sortOrder(a2, b3) {
return b3.size - a2.size;
}
__name(sortOrder, "sortOrder");
mostOverlapped.sort(sortOrder);
const positioned = {};
function isPositioned(element3) {
return element3.set in positioned;
}
__name(isPositioned, "isPositioned");
function positionSet(point8, index) {
circles[index].x = point8.x;
circles[index].y = point8.y;
positioned[index] = true;
}
__name(positionSet, "positionSet");
positionSet({ x: 0, y: 0 }, mostOverlapped[0].set);
for (let i2 = 1; i2 < mostOverlapped.length; ++i2) {
const setIndex = mostOverlapped[i2].set;
const overlap = setOverlaps[setIndex].filter(isPositioned);
const set5 = circles[setIndex];
overlap.sort(sortOrder);
if (overlap.length === 0) {
throw "ERROR: missing pairwise overlap information";
}
const points = [];
for (var j3 = 0; j3 < overlap.length; ++j3) {
const p1 = circles[overlap[j3].set];
const d1 = distanceFromIntersectArea(set5.radius, p1.radius, overlap[j3].size);
points.push({ x: p1.x + d1, y: p1.y });
points.push({ x: p1.x - d1, y: p1.y });
points.push({ y: p1.y + d1, x: p1.x });
points.push({ y: p1.y - d1, x: p1.x });
for (let k2 = j3 + 1; k2 < overlap.length; ++k2) {
const p22 = circles[overlap[k2].set];
const d22 = distanceFromIntersectArea(set5.radius, p22.radius, overlap[k2].size);
const extraPoints = circleCircleIntersection(
{ x: p1.x, y: p1.y, radius: d1 },
{ x: p22.x, y: p22.y, radius: d22 }
);
points.push(...extraPoints);
}
}
let bestLoss = 1e50;
let bestPoint = points[0];
for (const point8 of points) {
circles[setIndex].x = point8.x;
circles[setIndex].y = point8.y;
const localLoss = loss(circles, areas);
if (localLoss < bestLoss) {
bestLoss = localLoss;
bestPoint = point8;
}
}
positionSet(bestPoint, setIndex);
}
return circles;
}
function lossFunction(circles, overlaps) {
let output2 = 0;
for (const area of overlaps) {
if (area.sets.length === 1) {
continue;
}
let overlap;
if (area.sets.length === 2) {
const left3 = circles[area.sets[0]];
const right3 = circles[area.sets[1]];
overlap = circleOverlap(left3.radius, right3.radius, distance2(left3, right3));
} else {
overlap = intersectionArea(area.sets.map((d3) => circles[d3]));
}
const weight8 = area.weight != null ? area.weight : 1;
output2 += weight8 * (overlap - area.size) * (overlap - area.size);
}
return output2;
}
function logRatioLossFunction(circles, overlaps) {
let output2 = 0;
for (const area of overlaps) {
if (area.sets.length === 1) {
continue;
}
let overlap;
if (area.sets.length === 2) {
const left3 = circles[area.sets[0]];
const right3 = circles[area.sets[1]];
overlap = circleOverlap(left3.radius, right3.radius, distance2(left3, right3));
} else {
overlap = intersectionArea(area.sets.map((d3) => circles[d3]));
}
const weight8 = area.weight != null ? area.weight : 1;
const differenceFromIdeal = Math.log((overlap + 1) / (area.size + 1));
output2 += weight8 * differenceFromIdeal * differenceFromIdeal;
}
return output2;
}
function orientateCircles(circles, orientation, orientationOrder) {
if (orientationOrder == null) {
circles.sort((a2, b3) => b3.radius - a2.radius);
} else {
circles.sort(orientationOrder);
}
if (circles.length > 0) {
const largestX = circles[0].x;
const largestY = circles[0].y;
for (const circle6 of circles) {
circle6.x -= largestX;
circle6.y -= largestY;
}
}
if (circles.length === 2) {
const dist3 = distance2(circles[0], circles[1]);
if (dist3 < Math.abs(circles[1].radius - circles[0].radius)) {
circles[1].x = circles[0].x + circles[0].radius - circles[1].radius - 1e-10;
circles[1].y = circles[0].y;
}
}
if (circles.length > 1) {
const rotation = Math.atan2(circles[1].x, circles[1].y) - orientation;
const c3 = Math.cos(rotation);
const s2 = Math.sin(rotation);
for (const circle6 of circles) {
const x5 = circle6.x;
const y6 = circle6.y;
circle6.x = c3 * x5 - s2 * y6;
circle6.y = s2 * x5 + c3 * y6;
}
}
if (circles.length > 2) {
let angle2 = Math.atan2(circles[2].x, circles[2].y) - orientation;
while (angle2 < 0) {
angle2 += 2 * Math.PI;
}
while (angle2 > 2 * Math.PI) {
angle2 -= 2 * Math.PI;
}
if (angle2 > Math.PI) {
const slope = circles[1].y / (1e-10 + circles[1].x);
for (const circle6 of circles) {
var d3 = (circle6.x + slope * circle6.y) / (1 + slope * slope);
circle6.x = 2 * d3 - circle6.x;
circle6.y = 2 * d3 * slope - circle6.y;
}
}
}
}
function disjointCluster(circles) {
circles.forEach((circle6) => {
circle6.parent = circle6;
});
function find4(circle6) {
if (circle6.parent !== circle6) {
circle6.parent = find4(circle6.parent);
}
return circle6.parent;
}
__name(find4, "find");
function union2(x5, y6) {
const xRoot = find4(x5);
const yRoot = find4(y6);
xRoot.parent = yRoot;
}
__name(union2, "union");
for (let i2 = 0; i2 < circles.length; ++i2) {
for (let j3 = i2 + 1; j3 < circles.length; ++j3) {
const maxDistance = circles[i2].radius + circles[j3].radius;
if (distance2(circles[i2], circles[j3]) + 1e-10 < maxDistance) {
union2(circles[j3], circles[i2]);
}
}
}
const disjointClusters = /* @__PURE__ */ new Map();
for (let i2 = 0; i2 < circles.length; ++i2) {
const setid = find4(circles[i2]).parent.setid;
if (!disjointClusters.has(setid)) {
disjointClusters.set(setid, []);
}
disjointClusters.get(setid).push(circles[i2]);
}
circles.forEach((circle6) => {
delete circle6.parent;
});
return Array.from(disjointClusters.values());
}
function getBoundingBox(circles) {
const minMax = /* @__PURE__ */ __name((d3) => {
const hi = circles.reduce((acc, c3) => Math.max(acc, c3[d3] + c3.radius), Number.NEGATIVE_INFINITY);
const lo = circles.reduce((acc, c3) => Math.min(acc, c3[d3] - c3.radius), Number.POSITIVE_INFINITY);
return { max: hi, min: lo };
}, "minMax");
return { xRange: minMax("x"), yRange: minMax("y") };
}
function normalizeSolution(solution, orientation, orientationOrder) {
if (orientation == null) {
orientation = Math.PI / 2;
}
let circles = fromObjectNotation(solution).map((d3) => Object.assign({}, d3));
const clusters = disjointCluster(circles);
for (const cluster of clusters) {
orientateCircles(cluster, orientation, orientationOrder);
const bounds4 = getBoundingBox(cluster);
cluster.size = (bounds4.xRange.max - bounds4.xRange.min) * (bounds4.yRange.max - bounds4.yRange.min);
cluster.bounds = bounds4;
}
clusters.sort((a2, b3) => b3.size - a2.size);
circles = clusters[0];
let returnBounds = circles.bounds;
const spacing2 = (returnBounds.xRange.max - returnBounds.xRange.min) / 50;
function addCluster(cluster, right3, bottom2) {
if (!cluster) {
return;
}
const bounds4 = cluster.bounds;
let xOffset;
let yOffset;
if (right3) {
xOffset = returnBounds.xRange.max - bounds4.xRange.min + spacing2;
} else {
xOffset = returnBounds.xRange.max - bounds4.xRange.max;
const centreing = (bounds4.xRange.max - bounds4.xRange.min) / 2 - (returnBounds.xRange.max - returnBounds.xRange.min) / 2;
if (centreing < 0) {
xOffset += centreing;
}
}
if (bottom2) {
yOffset = returnBounds.yRange.max - bounds4.yRange.min + spacing2;
} else {
yOffset = returnBounds.yRange.max - bounds4.yRange.max;
const centreing = (bounds4.yRange.max - bounds4.yRange.min) / 2 - (returnBounds.yRange.max - returnBounds.yRange.min) / 2;
if (centreing < 0) {
yOffset += centreing;
}
}
for (const c3 of cluster) {
c3.x += xOffset;
c3.y += yOffset;
circles.push(c3);
}
}
__name(addCluster, "addCluster");
let index = 1;
while (index < clusters.length) {
addCluster(clusters[index], true, false);
addCluster(clusters[index + 1], false, true);
addCluster(clusters[index + 2], true, true);
index += 3;
returnBounds = getBoundingBox(circles);
}
return toObjectNotation(circles);
}
function scaleSolution(solution, width3, height2, padding2, scaleToFit) {
const circles = fromObjectNotation(solution);
width3 -= 2 * padding2;
height2 -= 2 * padding2;
const { xRange, yRange } = getBoundingBox(circles);
if (xRange.max === xRange.min || yRange.max === yRange.min) {
console.log("not scaling solution: zero size detected");
return solution;
}
let xScaling;
let yScaling;
if (scaleToFit) {
const toScaleDiameter = Math.sqrt(scaleToFit / Math.PI) * 2;
xScaling = width3 / toScaleDiameter;
yScaling = height2 / toScaleDiameter;
} else {
xScaling = width3 / (xRange.max - xRange.min);
yScaling = height2 / (yRange.max - yRange.min);
}
const scaling = Math.min(yScaling, xScaling);
const xOffset = (width3 - (xRange.max - xRange.min) * scaling) / 2;
const yOffset = (height2 - (yRange.max - yRange.min) * scaling) / 2;
return toObjectNotation(
circles.map((circle6) => ({
radius: scaling * circle6.radius,
x: padding2 + xOffset + (circle6.x - xRange.min) * scaling,
y: padding2 + yOffset + (circle6.y - yRange.min) * scaling,
setid: circle6.setid
}))
);
}
function toObjectNotation(circles) {
const r2 = {};
for (const circle6 of circles) {
r2[circle6.setid] = circle6;
}
return r2;
}
function fromObjectNotation(solution) {
const setids = Object.keys(solution);
return setids.map((id32) => Object.assign(solution[id32], { setid: id32 }));
}
function VennDiagram(options2 = {}) {
let useViewBox = false, width3 = 600, height2 = 350, padding2 = 15, duration = 1e3, orientation = Math.PI / 2, normalize4 = true, scaleToFit = null, wrap3 = true, styled = true, fontSize = null, orientationOrder = null, distinct = false, round = null, symmetricalTextCentre = options2 && options2.symmetricalTextCentre ? options2.symmetricalTextCentre : false, colourMap = {}, colourScheme = options2 && options2.colourScheme ? options2.colourScheme : options2 && options2.colorScheme ? options2.colorScheme : [
"#1f77b4",
"#ff7f0e",
"#2ca02c",
"#d62728",
"#9467bd",
"#8c564b",
"#e377c2",
"#7f7f7f",
"#bcbd22",
"#17becf"
], colourIndex = 0, colours = /* @__PURE__ */ __name(function(key) {
if (key in colourMap) {
return colourMap[key];
}
var ret = colourMap[key] = colourScheme[colourIndex];
colourIndex += 1;
if (colourIndex >= colourScheme.length) {
colourIndex = 0;
}
return ret;
}, "colours"), layoutFunction = venn, loss = lossFunction;
function chart(selection2) {
let data5 = selection2.datum();
const toRemove = /* @__PURE__ */ new Set();
data5.forEach((datum2) => {
if (datum2.size == 0 && datum2.sets.length == 1) {
toRemove.add(datum2.sets[0]);
}
});
data5 = data5.filter((datum2) => !datum2.sets.some((set5) => toRemove.has(set5)));
let circles = {};
let textCentres = {};
if (data5.length > 0) {
let solution = layoutFunction(data5, { lossFunction: loss, distinct });
if (normalize4) {
solution = normalizeSolution(solution, orientation, orientationOrder);
}
circles = scaleSolution(solution, width3, height2, padding2, scaleToFit);
textCentres = computeTextCentres(circles, data5, symmetricalTextCentre);
}
const labels = {};
data5.forEach((datum2) => {
if (datum2.label) {
labels[datum2.sets] = datum2.label;
}
});
function label(d3) {
if (d3.sets in labels) {
return labels[d3.sets];
}
if (d3.sets.length == 1) {
return "" + d3.sets[0];
}
}
__name(label, "label");
selection2.selectAll("svg").data([circles]).enter().append("svg");
const svg2 = selection2.select("svg");
if (useViewBox) {
svg2.attr("viewBox", `0 0 ${width3} ${height2}`);
} else {
svg2.attr("width", width3).attr("height", height2);
}
const previous = {};
let hasPrevious = false;
svg2.selectAll(".venn-area path").each(function(d3) {
const path4 = this.getAttribute("d");
if (d3.sets.length == 1 && path4 && !distinct) {
hasPrevious = true;
previous[d3.sets[0]] = circleFromPath(path4);
}
});
function pathTween(d3) {
return (t4) => {
const c3 = d3.sets.map((set5) => {
let start3 = previous[set5];
let end2 = circles[set5];
if (!start3) {
start3 = { x: width3 / 2, y: height2 / 2, radius: 1 };
}
if (!end2) {
end2 = { x: width3 / 2, y: height2 / 2, radius: 1 };
}
return {
x: start3.x * (1 - t4) + end2.x * t4,
y: start3.y * (1 - t4) + end2.y * t4,
radius: start3.radius * (1 - t4) + end2.radius * t4
};
});
return intersectionAreaPath(c3, round);
};
}
__name(pathTween, "pathTween");
const nodes5 = svg2.selectAll(".venn-area").data(data5, (d3) => d3.sets);
const enter = nodes5.enter().append("g").attr(
"class",
(d3) => `venn-area venn-${d3.sets.length == 1 ? "circle" : "intersection"}${d3.colour || d3.color ? " venn-coloured" : ""}`
).attr("data-venn-sets", (d3) => d3.sets.join("_"));
const enterPath = enter.append("path");
const enterText = enter.append("text").attr("class", "label").text((d3) => label(d3)).attr("text-anchor", "middle").attr("dy", ".35em").attr("x", width3 / 2).attr("y", height2 / 2);
if (styled) {
enterPath.style("fill-opacity", "0").filter((d3) => d3.sets.length == 1).style("fill", (d3) => d3.colour ? d3.colour : d3.color ? d3.color : colours(d3.sets)).style("fill-opacity", ".25");
enterText.style("fill", (d3) => {
if (d3.colour || d3.color) {
return "#FFF";
}
if (options2.textFill) {
return options2.textFill;
}
return d3.sets.length == 1 ? colours(d3.sets) : "#444";
});
}
function asTransition(s2) {
if (typeof s2.transition === "function") {
return s2.transition("venn").duration(duration);
}
return s2;
}
__name(asTransition, "asTransition");
let update2 = selection2;
if (hasPrevious && typeof update2.transition === "function") {
update2 = asTransition(selection2);
update2.selectAll("path").attrTween("d", pathTween);
} else {
update2.selectAll("path").attr("d", (d3) => intersectionAreaPath(d3.sets.map((set5) => circles[set5])), round);
}
const updateText = update2.selectAll("text").filter((d3) => d3.sets in textCentres).text((d3) => label(d3)).attr("x", (d3) => Math.floor(textCentres[d3.sets].x)).attr("y", (d3) => Math.floor(textCentres[d3.sets].y));
if (wrap3) {
if (hasPrevious) {
if ("on" in updateText) {
updateText.on("end", wrapText2(circles, label));
} else {
updateText.each("end", wrapText2(circles, label));
}
} else {
updateText.each(wrapText2(circles, label));
}
}
const exit = asTransition(nodes5.exit()).remove();
if (typeof nodes5.transition === "function") {
exit.selectAll("path").attrTween("d", pathTween);
}
const exitText = exit.selectAll("text").attr("x", width3 / 2).attr("y", height2 / 2);
if (fontSize !== null) {
enterText.style("font-size", "0px");
updateText.style("font-size", fontSize);
exitText.style("font-size", "0px");
}
return { circles, textCentres, nodes: nodes5, enter, update: update2, exit };
}
__name(chart, "chart");
chart.wrap = function(_3) {
if (!arguments.length) return wrap3;
wrap3 = _3;
return chart;
};
chart.useViewBox = function() {
useViewBox = true;
return chart;
};
chart.width = function(_3) {
if (!arguments.length) return width3;
width3 = _3;
return chart;
};
chart.height = function(_3) {
if (!arguments.length) return height2;
height2 = _3;
return chart;
};
chart.padding = function(_3) {
if (!arguments.length) return padding2;
padding2 = _3;
return chart;
};
chart.distinct = function(_3) {
if (!arguments.length) return distinct;
distinct = _3;
return chart;
};
chart.colours = function(_3) {
if (!arguments.length) return colours;
colours = _3;
return chart;
};
chart.colors = function(_3) {
if (!arguments.length) return colours;
colours = _3;
return chart;
};
chart.fontSize = function(_3) {
if (!arguments.length) return fontSize;
fontSize = _3;
return chart;
};
chart.round = function(_3) {
if (!arguments.length) return round;
round = _3;
return chart;
};
chart.duration = function(_3) {
if (!arguments.length) return duration;
duration = _3;
return chart;
};
chart.layoutFunction = function(_3) {
if (!arguments.length) return layoutFunction;
layoutFunction = _3;
return chart;
};
chart.normalize = function(_3) {
if (!arguments.length) return normalize4;
normalize4 = _3;
return chart;
};
chart.scaleToFit = function(_3) {
if (!arguments.length) return scaleToFit;
scaleToFit = _3;
return chart;
};
chart.styled = function(_3) {
if (!arguments.length) return styled;
styled = _3;
return chart;
};
chart.orientation = function(_3) {
if (!arguments.length) return orientation;
orientation = _3;
return chart;
};
chart.orientationOrder = function(_3) {
if (!arguments.length) return orientationOrder;
orientationOrder = _3;
return chart;
};
chart.lossFunction = function(_3) {
if (!arguments.length) return loss;
loss = _3 === "default" ? lossFunction : _3 === "logRatio" ? logRatioLossFunction : _3;
return chart;
};
return chart;
}
function wrapText2(circles, labeller) {
return function(data5) {
const text4 = this;
const width3 = circles[data5.sets[0]].radius || 50;
const label = labeller(data5) || "";
const words = label.split(/\s+/).reverse();
const maxLines = 3;
const minChars = (label.length + words.length) / maxLines;
let word = words.pop();
let line2 = [word];
let lineNumber = 0;
const lineHeight = 1.1;
text4.textContent = null;
const tspans = [];
function append3(word2) {
const tspan2 = text4.ownerDocument.createElementNS(text4.namespaceURI, "tspan");
tspan2.textContent = word2;
tspans.push(tspan2);
text4.append(tspan2);
return tspan2;
}
__name(append3, "append");
let tspan = append3(word);
while (true) {
word = words.pop();
if (!word) {
break;
}
line2.push(word);
const joined = line2.join(" ");
tspan.textContent = joined;
if (joined.length > minChars && tspan.getComputedTextLength() > width3) {
line2.pop();
tspan.textContent = line2.join(" ");
line2 = [word];
tspan = append3(word);
lineNumber++;
}
}
const initial = 0.35 - lineNumber * lineHeight / 2;
const x5 = text4.getAttribute("x");
const y6 = text4.getAttribute("y");
tspans.forEach((t4, i2) => {
t4.setAttribute("x", x5);
t4.setAttribute("y", y6);
t4.setAttribute("dy", `${initial + i2 * lineHeight}em`);
});
};
}
function circleMargin(current, interior, exterior) {
let margin = interior[0].radius - distance2(interior[0], current);
for (let i2 = 1; i2 < interior.length; ++i2) {
const m3 = interior[i2].radius - distance2(interior[i2], current);
if (m3 <= margin) {
margin = m3;
}
}
for (let i2 = 0; i2 < exterior.length; ++i2) {
const m3 = distance2(exterior[i2], current) - exterior[i2].radius;
if (m3 <= margin) {
margin = m3;
}
}
return margin;
}
function computeTextCentre(interior, exterior, symmetricalTextCentre) {
const points = [];
for (const c3 of interior) {
points.push({ x: c3.x, y: c3.y });
points.push({ x: c3.x + c3.radius / 2, y: c3.y });
points.push({ x: c3.x - c3.radius / 2, y: c3.y });
points.push({ x: c3.x, y: c3.y + c3.radius / 2 });
points.push({ x: c3.x, y: c3.y - c3.radius / 2 });
}
let initial = points[0];
let margin = circleMargin(points[0], interior, exterior);
for (let i2 = 1; i2 < points.length; ++i2) {
const m3 = circleMargin(points[i2], interior, exterior);
if (m3 >= margin) {
initial = points[i2];
margin = m3;
}
}
const solution = nelderMead(
(p3) => -1 * circleMargin({ x: p3[0], y: p3[1] }, interior, exterior),
[initial.x, initial.y],
{ maxIterations: 500, minErrorDelta: 1e-10 }
).x;
const ret = { x: symmetricalTextCentre ? 0 : solution[0], y: solution[1] };
let valid2 = true;
for (const i2 of interior) {
if (distance2(ret, i2) > i2.radius) {
valid2 = false;
break;
}
}
for (const e3 of exterior) {
if (distance2(ret, e3) < e3.radius) {
valid2 = false;
break;
}
}
if (valid2) {
return ret;
}
if (interior.length == 1) {
return { x: interior[0].x, y: interior[0].y };
}
const areaStats = {};
intersectionArea(interior, areaStats);
if (areaStats.arcs.length === 0) {
return { x: 0, y: -1e3, disjoint: true };
}
if (areaStats.arcs.length == 1) {
return { x: areaStats.arcs[0].circle.x, y: areaStats.arcs[0].circle.y };
}
if (exterior.length) {
return computeTextCentre(interior, []);
}
return getCenter(areaStats.arcs.map((a2) => a2.p1));
}
function getOverlappingCircles(circles) {
const ret = {};
const circleids = Object.keys(circles);
for (const circleid of circleids) {
ret[circleid] = [];
}
for (let i2 = 0; i2 < circleids.length; i2++) {
const ci = circleids[i2];
const a2 = circles[ci];
for (let j3 = i2 + 1; j3 < circleids.length; ++j3) {
const cj = circleids[j3];
const b3 = circles[cj];
const d3 = distance2(a2, b3);
if (d3 + b3.radius <= a2.radius + 1e-10) {
ret[cj].push(ci);
} else if (d3 + a2.radius <= b3.radius + 1e-10) {
ret[ci].push(cj);
}
}
}
return ret;
}
function computeTextCentres(circles, areas, symmetricalTextCentre) {
const ret = {};
const overlapped = getOverlappingCircles(circles);
for (let i2 = 0; i2 < areas.length; ++i2) {
const area = areas[i2].sets;
const areaids = {};
const exclude = {};
for (let j3 = 0; j3 < area.length; ++j3) {
areaids[area[j3]] = true;
const overlaps = overlapped[area[j3]];
for (let k2 = 0; k2 < overlaps.length; ++k2) {
exclude[overlaps[k2]] = true;
}
}
const interior = [];
const exterior = [];
for (let setid in circles) {
if (setid in areaids) {
interior.push(circles[setid]);
} else if (!(setid in exclude)) {
exterior.push(circles[setid]);
}
}
const centre = computeTextCentre(interior, exterior, symmetricalTextCentre);
ret[area] = centre;
if (centre.disjoint && areas[i2].size > 0) {
console.log("WARNING: area " + area + " not represented on screen");
}
}
return ret;
}
function circlePath(x5, y6, r2) {
const ret = [];
ret.push("\nM", x5, y6);
ret.push("\nm", -r2, 0);
ret.push("\na", r2, r2, 0, 1, 0, r2 * 2, 0);
ret.push("\na", r2, r2, 0, 1, 0, -r2 * 2, 0);
return ret.join(" ");
}
function circleFromPath(path4) {
const tokens2 = path4.split(" ");
return { x: Number.parseFloat(tokens2[1]), y: Number.parseFloat(tokens2[2]), radius: -Number.parseFloat(tokens2[4]) };
}
function intersectionAreaArcs(circles) {
if (circles.length === 0) {
return [];
}
const stats = {};
intersectionArea(circles, stats);
return stats.arcs;
}
function arcsToPath(arcs, round) {
if (arcs.length === 0) {
return "M 0 0";
}
const rFactor = Math.pow(10, round || 0);
const r2 = round != null ? (v3) => Math.round(v3 * rFactor) / rFactor : (v3) => v3;
if (arcs.length == 1) {
const circle6 = arcs[0].circle;
return circlePath(r2(circle6.x), r2(circle6.y), r2(circle6.radius));
}
const ret = ["\nM", r2(arcs[0].p2.x), r2(arcs[0].p2.y)];
for (const arc of arcs) {
const radius2 = r2(arc.circle.radius);
ret.push("\nA", radius2, radius2, 0, arc.large ? 1 : 0, arc.sweep ? 1 : 0, r2(arc.p1.x), r2(arc.p1.y));
}
return ret.join(" ");
}
function intersectionAreaPath(circles, round) {
return arcsToPath(intersectionAreaArcs(circles), round);
}
function layout6(data5, options2 = {}) {
const {
lossFunction: loss,
layoutFunction: layout7 = venn,
normalize: normalize4 = true,
orientation = Math.PI / 2,
orientationOrder,
width: width3 = 600,
height: height2 = 350,
padding: padding2 = 15,
scaleToFit = false,
symmetricalTextCentre = false,
distinct,
round = 2
} = options2;
let solution = layout7(data5, {
lossFunction: loss === "default" || !loss ? lossFunction : loss === "logRatio" ? logRatioLossFunction : loss,
distinct
});
if (normalize4) {
solution = normalizeSolution(solution, orientation, orientationOrder);
}
const circles = scaleSolution(solution, width3, height2, padding2, scaleToFit);
const textCentres = computeTextCentres(circles, data5, symmetricalTextCentre);
const circleLookup = new Map(
Object.keys(circles).map((set5) => [
set5,
{
set: set5,
x: circles[set5].x,
y: circles[set5].y,
radius: circles[set5].radius
}
])
);
const helpers = data5.map((area) => {
const circles2 = area.sets.map((s2) => circleLookup.get(s2));
const arcs = intersectionAreaArcs(circles2);
const path4 = arcsToPath(arcs, round);
return { circles: circles2, arcs, path: path4, area, has: new Set(area.sets) };
});
function genDistinctPath(sets) {
let r2 = "";
for (const e3 of helpers) {
if (e3.has.size > sets.length && sets.every((s2) => e3.has.has(s2))) {
r2 += " " + e3.path;
}
}
return r2;
}
__name(genDistinctPath, "genDistinctPath");
return helpers.map(({ circles: circles2, arcs, path: path4, area }) => {
return {
data: area,
text: textCentres[area.sets],
circles: circles2,
arcs,
path: path4,
distinctPath: path4 + genDistinctPath(area.sets)
};
});
}
var SMALL$1, SMALL;
var init_venn_esm = __esm({
"../../node_modules/.pnpm/@upsetjs+venn.js@2.0.0/node_modules/@upsetjs/venn.js/build/venn.esm.js"() {
"use strict";
SMALL$1 = 1e-10;
__name(intersectionArea, "intersectionArea");
__name(containedInCircles, "containedInCircles");
__name(getIntersectionPoints, "getIntersectionPoints");
__name(circleArea, "circleArea");
__name(distance2, "distance");
__name(circleOverlap, "circleOverlap");
__name(circleCircleIntersection, "circleCircleIntersection");
__name(getCenter, "getCenter");
__name(bisect, "bisect");
__name(zeros, "zeros");
__name(zerosM, "zerosM");
__name(dot, "dot");
__name(norm2, "norm2");
__name(scale2, "scale");
__name(weightedSum, "weightedSum");
__name(nelderMead, "nelderMead");
__name(wolfeLineSearch, "wolfeLineSearch");
__name(conjugateGradient, "conjugateGradient");
__name(venn, "venn");
SMALL = 1e-10;
__name(distanceFromIntersectArea, "distanceFromIntersectArea");
__name(addMissingAreas, "addMissingAreas");
__name(getDistanceMatrices, "getDistanceMatrices");
__name(constrainedMDSGradient, "constrainedMDSGradient");
__name(bestInitialLayout, "bestInitialLayout");
__name(constrainedMDSLayout, "constrainedMDSLayout");
__name(greedyLayout, "greedyLayout");
__name(lossFunction, "lossFunction");
__name(logRatioLossFunction, "logRatioLossFunction");
__name(orientateCircles, "orientateCircles");
__name(disjointCluster, "disjointCluster");
__name(getBoundingBox, "getBoundingBox");
__name(normalizeSolution, "normalizeSolution");
__name(scaleSolution, "scaleSolution");
__name(toObjectNotation, "toObjectNotation");
__name(fromObjectNotation, "fromObjectNotation");
__name(VennDiagram, "VennDiagram");
__name(wrapText2, "wrapText");
__name(circleMargin, "circleMargin");
__name(computeTextCentre, "computeTextCentre");
__name(getOverlappingCircles, "getOverlappingCircles");
__name(computeTextCentres, "computeTextCentres");
__name(circlePath, "circlePath");
__name(circleFromPath, "circleFromPath");
__name(intersectionAreaArcs, "intersectionAreaArcs");
__name(arcsToPath, "arcsToPath");
__name(intersectionAreaPath, "intersectionAreaPath");
__name(layout6, "layout");
}
});
// src/diagrams/venn/vennRenderer.ts
function buildStyleByKey(styleData) {
const map5 = /* @__PURE__ */ new Map();
for (const entry of styleData) {
const key = entry.targets.join("|");
const existing = map5.get(key);
if (existing) {
Object.assign(existing, entry.styles);
} else {
map5.set(key, { ...entry.styles });
}
}
return map5;
}
function stableSetsKey(setIds) {
return setIds.join("|");
}
function renderTextNodes(config5, layoutByKey, dummyD3root, textNodes2, scale3, styleByKey) {
const useDebugLayout = config5?.useDebugLayout ?? false;
const vennSvg = dummyD3root.select("svg");
const textGroup = vennSvg.append("g").attr("class", "venn-text-nodes");
const nodesByArea = /* @__PURE__ */ new Map();
for (const node2 of textNodes2) {
const key = stableSetsKey(node2.sets);
const existing = nodesByArea.get(key);
if (existing) {
existing.push(node2);
} else {
nodesByArea.set(key, [node2]);
}
}
for (const [key, nodes5] of nodesByArea.entries()) {
const area = layoutByKey.get(key);
if (!area?.text) {
continue;
}
const centerX = area.text.x;
const centerY = area.text.y;
const minCircleRadius = Math.min(...area.circles.map((c3) => c3.radius));
const innerRadiusRaw = Math.min(
...area.circles.map((c3) => c3.radius - Math.hypot(centerX - c3.x, centerY - c3.y))
);
let innerRadius = Number.isFinite(innerRadiusRaw) ? Math.max(0, innerRadiusRaw) : 0;
if (innerRadius === 0 && Number.isFinite(minCircleRadius)) {
innerRadius = minCircleRadius * 0.6;
}
const areaGroup = textGroup.append("g").attr("class", "venn-text-area").attr("font-size", `${40 * scale3}px`);
if (useDebugLayout) {
areaGroup.append("circle").attr("class", "venn-text-debug-circle").attr("cx", centerX).attr("cy", centerY).attr("r", innerRadius).attr("fill", "none").attr("stroke", "purple").attr("stroke-width", 1.5 * scale3).attr("stroke-dasharray", `${6 * scale3} ${4 * scale3}`);
}
const innerWidth = Math.max(80 * scale3, innerRadius * 2 * 0.95);
const innerHeight = Math.max(60 * scale3, innerRadius * 2 * 0.95);
const hasLabel = area.data.label && area.data.label.length > 0;
const labelOffsetBase = hasLabel ? Math.min(32 * scale3, innerRadius * 0.25) : 0;
const labelOffset = labelOffsetBase + (nodes5.length <= 2 ? 30 * scale3 : 0);
const startX2 = centerX - innerWidth / 2;
const startY2 = centerY - innerHeight / 2 + labelOffset;
const cols = Math.max(1, Math.ceil(Math.sqrt(nodes5.length)));
const rows = Math.max(1, Math.ceil(nodes5.length / cols));
const cellWidth = innerWidth / cols;
const cellHeight = innerHeight / rows;
for (const [i2, node2] of nodes5.entries()) {
const col = i2 % cols;
const row = Math.floor(i2 / cols);
const x5 = startX2 + cellWidth * (col + 0.5);
const y6 = startY2 + cellHeight * (row + 0.5);
if (useDebugLayout) {
areaGroup.append("rect").attr("class", "venn-text-debug-cell").attr("x", startX2 + cellWidth * col).attr("y", startY2 + cellHeight * row).attr("width", cellWidth).attr("height", cellHeight).attr("fill", "none").attr("stroke", "teal").attr("stroke-width", 1 * scale3).attr("stroke-dasharray", `${4 * scale3} ${3 * scale3}`);
}
const boxWidth = cellWidth * 0.9;
const boxHeight = cellHeight * 0.9;
const container2 = areaGroup.append("foreignObject").attr("class", "venn-text-node-fo").attr("width", boxWidth).attr("height", boxHeight).attr("x", x5 - boxWidth / 2).attr("y", y6 - boxHeight / 2).attr("overflow", "visible");
const textColor = styleByKey.get(node2.id)?.color;
const text4 = container2.append("xhtml:span").attr("class", "venn-text-node").style("display", "flex").style("width", "100%").style("height", "100%").style("white-space", "normal").style("align-items", "center").style("justify-content", "center").style("text-align", "center").style("overflow-wrap", "normal").style("word-break", "normal").text(node2.label ?? node2.id);
if (textColor) {
text4.style("color", textColor);
}
}
}
}
var draw26, renderer10;
var init_vennRenderer = __esm({
"src/diagrams/venn/vennRenderer.ts"() {
"use strict";
init_src32();
init_dist();
init_config();
init_selectSvgElement();
init_venn_esm();
init_setupGraphViewbox();
init_rough_esm();
__name(buildStyleByKey, "buildStyleByKey");
draw26 = /* @__PURE__ */ __name((_text, id32, _version, diagObj) => {
const db8 = diagObj.db;
const config5 = db8.getConfig?.();
const { themeVariables, look, handDrawnSeed } = getConfig();
const isHandDrawn = look === "handDrawn";
const themeColors = [
themeVariables.venn1,
themeVariables.venn2,
themeVariables.venn3,
themeVariables.venn4,
themeVariables.venn5,
themeVariables.venn6,
themeVariables.venn7,
themeVariables.venn8
].filter(Boolean);
const title2 = db8.getDiagramTitle?.();
const sets = db8.getSubsetData();
const textNodes2 = db8.getTextData();
const styleByKey = buildStyleByKey(db8.getStyleData());
const svgWidth = config5?.width ?? 800;
const svgHeight = config5?.height ?? 450;
const REFERENCE_WIDTH = 1600;
const scale3 = svgWidth / REFERENCE_WIDTH;
const titleHeight = title2 ? 48 * scale3 : 0;
const defaultTextColor = themeVariables.primaryTextColor ?? themeVariables.textColor;
const svg2 = selectSvgElement(id32);
svg2.attr("viewBox", `0 0 ${svgWidth} ${svgHeight}`);
if (title2) {
svg2.append("text").text(title2).attr("class", "venn-title").attr("font-size", `${32 * scale3}px`).attr("text-anchor", "middle").attr("dominant-baseline", "middle").attr("x", "50%").attr("y", 32 * scale3).style("fill", themeVariables.vennTitleTextColor || themeVariables.titleColor);
}
const dummyD3root = select_default2(document.createElement("div"));
const vennDiagram = VennDiagram().width(svgWidth).height(svgHeight - titleHeight);
dummyD3root.datum(sets).call(vennDiagram);
const roughSvg = isHandDrawn ? at.svg(dummyD3root.select("svg").node()) : void 0;
const layoutAreas = layout6(sets, {
width: svgWidth,
height: svgHeight - titleHeight,
padding: config5?.padding ?? 15
});
const layoutByKey = /* @__PURE__ */ new Map();
for (const area of layoutAreas) {
const key = stableSetsKey([...area.data.sets].sort());
layoutByKey.set(key, area);
}
if (textNodes2.length > 0) {
renderTextNodes(config5, layoutByKey, dummyD3root, textNodes2, scale3, styleByKey);
}
const themeDark = is_dark_default(themeVariables.background || "#f4f4f4");
dummyD3root.selectAll(".venn-circle").each(function(d3, i2) {
const group2 = select_default2(this);
const data5 = d3;
const setsKey = stableSetsKey([...data5.sets].sort());
const customStyle = styleByKey.get(setsKey);
const baseColor = customStyle?.fill || themeColors[i2 % themeColors.length] || themeVariables.primaryColor;
group2.classed(`venn-set-${i2 % 8}`, true);
const fillOpacity = customStyle?.["fill-opacity"] ?? 0.1;
const strokeColor = customStyle?.stroke || baseColor;
const strokeWidthVal = customStyle?.["stroke-width"] || `${5 * scale3}`;
if (isHandDrawn && roughSvg) {
const layoutArea = layoutByKey.get(setsKey);
if (layoutArea && layoutArea.circles.length > 0) {
const c3 = layoutArea.circles[0];
const roughNode = roughSvg.circle(c3.x, c3.y, c3.radius * 2, {
roughness: 0.7,
seed: handDrawnSeed,
fill: transparentize_default(baseColor, 0.7),
fillStyle: "hachure",
fillWeight: 2,
hachureGap: 8,
hachureAngle: -41 + i2 * 60,
stroke: strokeColor,
strokeWidth: parseFloat(String(strokeWidthVal))
});
group2.select("path").remove();
group2.node()?.insertBefore(roughNode, group2.select("text").node());
}
} else {
group2.select("path").style("fill", baseColor).style("fill-opacity", fillOpacity).style("stroke", strokeColor).style("stroke-width", strokeWidthVal).style("stroke-opacity", 0.95);
}
const textColor = customStyle?.color || (themeDark ? lighten_default(baseColor, 30) : darken_default(baseColor, 30));
group2.select("text").style("font-size", `${48 * scale3}px`).style("fill", textColor);
});
if (isHandDrawn && roughSvg) {
dummyD3root.selectAll(".venn-intersection").each(function(d3) {
const group2 = select_default2(this);
const data5 = d3;
const setsKey = stableSetsKey([...data5.sets].sort());
const customStyle = styleByKey.get(setsKey);
const customFill = customStyle?.fill;
if (customFill) {
const pathEl = group2.select("path");
const pathD = pathEl.attr("d");
if (pathD) {
const roughNode = roughSvg.path(pathD, {
roughness: 0.7,
seed: handDrawnSeed,
fill: transparentize_default(customFill, 0.3),
fillStyle: "cross-hatch",
fillWeight: 2,
hachureGap: 6,
hachureAngle: 60,
stroke: "none"
});
const existingPath = pathEl.node();
existingPath?.parentNode?.insertBefore(roughNode, existingPath);
pathEl.remove();
}
} else {
group2.select("path").style("fill-opacity", 0);
}
group2.select("text").style("font-size", `${48 * scale3}px`).style("fill", customStyle?.color ?? themeVariables.vennSetTextColor ?? defaultTextColor);
});
} else {
dummyD3root.selectAll(".venn-intersection text").style("font-size", `${48 * scale3}px`).style("fill", (e3) => {
const data5 = e3;
const setsKey = stableSetsKey([...data5.sets].sort());
return styleByKey.get(setsKey)?.color ?? themeVariables.vennSetTextColor ?? defaultTextColor;
});
dummyD3root.selectAll(".venn-intersection path").style("fill-opacity", (e3) => {
const data5 = e3;
const setsKey = stableSetsKey([...data5.sets].sort());
return styleByKey.get(setsKey)?.fill ? 1 : 0;
}).style("fill", (e3) => {
const data5 = e3;
const setsKey = stableSetsKey([...data5.sets].sort());
return styleByKey.get(setsKey)?.fill ?? "transparent";
});
}
const vennGroup = svg2.append("g").attr("transform", `translate(0, ${titleHeight})`);
const dummySvg = dummyD3root.select("svg").node();
if (dummySvg && "childNodes" in dummySvg) {
for (const child of [...dummySvg.childNodes]) {
vennGroup.node()?.appendChild(child);
}
}
configureSvgSize(svg2, svgHeight, svgWidth, config5?.useMaxWidth ?? true);
}, "draw");
__name(stableSetsKey, "stableSetsKey");
__name(renderTextNodes, "renderTextNodes");
renderer10 = { draw: draw26 };
}
});
// src/diagrams/venn/vennDiagram.ts
var vennDiagram_exports = {};
__export(vennDiagram_exports, {
diagram: () => diagram27
});
var diagram27;
var init_vennDiagram = __esm({
"src/diagrams/venn/vennDiagram.ts"() {
"use strict";
init_venn();
init_vennDB();
init_styles19();
init_vennRenderer();
diagram27 = {
parser: venn_default,
db: db7,
renderer: renderer10,
styles: styles_default17
};
}
});
// src/diagrams/treemap/db.ts
var TreeMapDB;
var init_db3 = __esm({
"src/diagrams/treemap/db.ts"() {
"use strict";
init_defaultConfig();
init_config();
init_utils2();
init_handDrawnShapeStyles();
init_commonDb();
TreeMapDB = class {
constructor() {
this.nodes = [];
this.levels = /* @__PURE__ */ new Map();
this.outerNodes = [];
this.classes = /* @__PURE__ */ new Map();
this.setAccTitle = setAccTitle;
this.getAccTitle = getAccTitle;
this.setDiagramTitle = setDiagramTitle;
this.getDiagramTitle = getDiagramTitle;
this.getAccDescription = getAccDescription;
this.setAccDescription = setAccDescription;
}
static {
__name(this, "TreeMapDB");
}
getNodes() {
return this.nodes;
}
getConfig() {
const defaultConfig4 = defaultConfig_default;
const userConfig = getConfig();
return cleanAndMerge({
...defaultConfig4.treemap,
...userConfig.treemap ?? {}
});
}
addNode(node2, level) {
this.nodes.push(node2);
this.levels.set(node2, level);
if (level === 0) {
this.outerNodes.push(node2);
this.root ??= node2;
}
}
getRoot() {
return { name: "", children: this.outerNodes };
}
addClass(id32, _style) {
const styleClass = this.classes.get(id32) ?? { id: id32, styles: [], textStyles: [] };
const styles4 = _style.replace(/\\,/g, "\xA7\xA7\xA7").replace(/,/g, ";").replace(/§§§/g, ",").split(";");
if (styles4) {
styles4.forEach((s2) => {
if (isLabelStyle(s2)) {
if (styleClass?.textStyles) {
styleClass.textStyles.push(s2);
} else {
styleClass.textStyles = [s2];
}
}
if (styleClass?.styles) {
styleClass.styles.push(s2);
} else {
styleClass.styles = [s2];
}
});
}
this.classes.set(id32, styleClass);
}
getClasses() {
return this.classes;
}
getStylesForClass(classSelector) {
return this.classes.get(classSelector)?.styles ?? [];
}
clear() {
clear();
this.nodes = [];
this.levels = /* @__PURE__ */ new Map();
this.outerNodes = [];
this.classes = /* @__PURE__ */ new Map();
this.root = void 0;
}
};
}
});
// src/diagrams/treemap/utils.ts
function buildHierarchy(items) {
if (!items.length) {
return [];
}
const root3 = [];
const stack = [];
items.forEach((item) => {
const node2 = {
name: item.name,
children: item.type === "Leaf" ? void 0 : []
};
node2.classSelector = item?.classSelector;
if (item?.cssCompiledStyles) {
node2.cssCompiledStyles = item.cssCompiledStyles;
}
if (item.type === "Leaf" && item.value !== void 0) {
node2.value = item.value;
}
while (stack.length > 0 && stack[stack.length - 1].level >= item.level) {
stack.pop();
}
if (stack.length === 0) {
root3.push(node2);
} else {
const parent4 = stack[stack.length - 1].node;
if (parent4.children) {
parent4.children.push(node2);
} else {
parent4.children = [node2];
}
}
if (item.type !== "Leaf") {
stack.push({ node: node2, level: item.level });
}
});
return root3;
}
var init_utils6 = __esm({
"src/diagrams/treemap/utils.ts"() {
"use strict";
__name(buildHierarchy, "buildHierarchy");
}
});
// src/diagrams/treemap/parser.ts
var populate18, getItemName, parser25;
var init_parser5 = __esm({
"src/diagrams/treemap/parser.ts"() {
"use strict";
init_mermaid_parser_core();
init_logger();
init_populateCommonDb();
init_utils6();
init_db3();
populate18 = /* @__PURE__ */ __name((ast, db8) => {
populateCommonDb(ast, db8);
const items = [];
for (const row of ast.TreemapRows ?? []) {
if (row.$type === "ClassDefStatement") {
db8.addClass(row.className ?? "", row.styleText ?? "");
}
}
for (const row of ast.TreemapRows ?? []) {
const item = row.item;
if (!item) {
continue;
}
const level = row.indent ? parseInt(row.indent) : 0;
const name = getItemName(item);
const styles4 = item.classSelector ? db8.getStylesForClass(item.classSelector) : [];
const cssCompiledStyles = styles4.length > 0 ? styles4 : void 0;
const itemData = {
level,
name,
type: item.$type,
value: item.value,
classSelector: item.classSelector,
cssCompiledStyles
};
items.push(itemData);
}
const hierarchyNodes = buildHierarchy(items);
const addNodesRecursively = /* @__PURE__ */ __name((nodes5, level) => {
for (const node2 of nodes5) {
db8.addNode(node2, level);
if (node2.children && node2.children.length > 0) {
addNodesRecursively(node2.children, level + 1);
}
}
}, "addNodesRecursively");
addNodesRecursively(hierarchyNodes, 0);
}, "populate");
getItemName = /* @__PURE__ */ __name((item) => {
return item.name ? String(item.name) : "";
}, "getItemName");
parser25 = {
// @ts-expect-error - TreeMapDB is not assignable to DiagramDB
parser: { yy: void 0 },
parse: /* @__PURE__ */ __name(async (text4) => {
try {
const parseFunc = parse3;
const ast = await parseFunc("treemap", text4);
log.debug("Treemap AST:", ast);
const db8 = parser25.parser?.yy;
if (!(db8 instanceof TreeMapDB)) {
throw new Error(
"parser.parser?.yy was not a TreemapDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues."
);
}
populate18(ast, db8);
} catch (error3) {
log.error("Error parsing treemap:", error3);
throw error3;
}
}, "parse")
};
}
});
// src/diagrams/treemap/renderer.ts
var DEFAULT_INNER_PADDING, SECTION_INNER_PADDING, SECTION_HEADER_HEIGHT, draw27, getClasses6, renderer11;
var init_renderer3 = __esm({
"src/diagrams/treemap/renderer.ts"() {
"use strict";
init_selectSvgElement();
init_setupViewPortForSVG();
init_setupGraphViewbox();
init_src32();
init_handDrawnShapeStyles();
init_config();
init_logger();
DEFAULT_INNER_PADDING = 10;
SECTION_INNER_PADDING = 10;
SECTION_HEADER_HEIGHT = 25;
draw27 = /* @__PURE__ */ __name((_text, id32, _version, diagram29) => {
const treemapDb = diagram29.db;
const config5 = treemapDb.getConfig();
const treemapInnerPadding = config5.padding ?? DEFAULT_INNER_PADDING;
const title2 = treemapDb.getDiagramTitle();
const root3 = treemapDb.getRoot();
const { themeVariables } = getConfig();
if (!root3) {
return;
}
const titleHeight = title2 ? 30 : 0;
const svg2 = selectSvgElement(id32);
const width3 = config5.nodeWidth ? config5.nodeWidth * SECTION_INNER_PADDING : 960;
const height2 = config5.nodeHeight ? config5.nodeHeight * SECTION_INNER_PADDING : 500;
const svgWidth = width3;
const svgHeight = height2 + titleHeight;
svg2.attr("viewBox", `0 0 ${svgWidth} ${svgHeight}`);
configureSvgSize(svg2, svgHeight, svgWidth, config5.useMaxWidth);
let valueFormat;
try {
const formatStr = config5.valueFormat || ",";
if (formatStr === "$0,0") {
valueFormat = /* @__PURE__ */ __name((value2) => "$" + format2(",")(value2), "valueFormat");
} else if (formatStr.startsWith("$") && formatStr.includes(",")) {
const precision = /\.\d+/.exec(formatStr);
const precisionStr = precision ? precision[0] : "";
valueFormat = /* @__PURE__ */ __name((value2) => "$" + format2("," + precisionStr)(value2), "valueFormat");
} else if (formatStr.startsWith("$")) {
const restOfFormat = formatStr.substring(1);
valueFormat = /* @__PURE__ */ __name((value2) => "$" + format2(restOfFormat || "")(value2), "valueFormat");
} else {
valueFormat = format2(formatStr);
}
} catch (error3) {
log.error("Error creating format function:", error3);
valueFormat = format2(",");
}
const colorScale = ordinal().range([
"transparent",
themeVariables.cScale0,
themeVariables.cScale1,
themeVariables.cScale2,
themeVariables.cScale3,
themeVariables.cScale4,
themeVariables.cScale5,
themeVariables.cScale6,
themeVariables.cScale7,
themeVariables.cScale8,
themeVariables.cScale9,
themeVariables.cScale10,
themeVariables.cScale11
]);
const colorScalePeer = ordinal().range([
"transparent",
themeVariables.cScalePeer0,
themeVariables.cScalePeer1,
themeVariables.cScalePeer2,
themeVariables.cScalePeer3,
themeVariables.cScalePeer4,
themeVariables.cScalePeer5,
themeVariables.cScalePeer6,
themeVariables.cScalePeer7,
themeVariables.cScalePeer8,
themeVariables.cScalePeer9,
themeVariables.cScalePeer10,
themeVariables.cScalePeer11
]);
const colorScaleLabel = ordinal().range([
themeVariables.cScaleLabel0,
themeVariables.cScaleLabel1,
themeVariables.cScaleLabel2,
themeVariables.cScaleLabel3,
themeVariables.cScaleLabel4,
themeVariables.cScaleLabel5,
themeVariables.cScaleLabel6,
themeVariables.cScaleLabel7,
themeVariables.cScaleLabel8,
themeVariables.cScaleLabel9,
themeVariables.cScaleLabel10,
themeVariables.cScaleLabel11
]);
if (title2) {
svg2.append("text").attr("x", svgWidth / 2).attr("y", titleHeight / 2).attr("class", "treemapTitle").attr("text-anchor", "middle").attr("dominant-baseline", "middle").text(title2);
}
const g2 = svg2.append("g").attr("transform", `translate(0, ${titleHeight})`).attr("class", "treemapContainer");
const hierarchyRoot = hierarchy(root3).sum((d3) => d3.value ?? 0).sort((a2, b3) => (b3.value ?? 0) - (a2.value ?? 0));
const treemapLayout = treemap_default().size([width3, height2]).paddingTop(
(d3) => d3.children && d3.children.length > 0 ? SECTION_HEADER_HEIGHT + SECTION_INNER_PADDING : 0
).paddingInner(treemapInnerPadding).paddingLeft((d3) => d3.children && d3.children.length > 0 ? SECTION_INNER_PADDING : 0).paddingRight((d3) => d3.children && d3.children.length > 0 ? SECTION_INNER_PADDING : 0).paddingBottom((d3) => d3.children && d3.children.length > 0 ? SECTION_INNER_PADDING : 0).round(true);
const treemapData = treemapLayout(hierarchyRoot);
const branchNodes = treemapData.descendants().filter((d3) => d3.children && d3.children.length > 0);
const sections6 = g2.selectAll(".treemapSection").data(branchNodes).enter().append("g").attr("class", "treemapSection").attr("transform", (d3) => `translate(${d3.x0},${d3.y0})`);
sections6.append("rect").attr("width", (d3) => d3.x1 - d3.x0).attr("height", SECTION_HEADER_HEIGHT).attr("class", "treemapSectionHeader").attr("fill", "none").attr("fill-opacity", 0.6).attr("stroke-width", 0.6).attr("style", (d3) => {
if (d3.depth === 0) {
return "display: none;";
}
return "";
});
sections6.append("clipPath").attr("id", (_d, i2) => `clip-section-${id32}-${i2}`).append("rect").attr("width", (d3) => Math.max(0, d3.x1 - d3.x0 - 12)).attr("height", SECTION_HEADER_HEIGHT);
sections6.append("rect").attr("width", (d3) => d3.x1 - d3.x0).attr("height", (d3) => d3.y1 - d3.y0).attr("class", (_d, i2) => {
return `treemapSection section${i2}`;
}).attr("fill", (d3) => colorScale(d3.data.name)).attr("fill-opacity", 0.6).attr("stroke", (d3) => colorScalePeer(d3.data.name)).attr("stroke-width", 2).attr("stroke-opacity", 0.4).attr("style", (d3) => {
if (d3.depth === 0) {
return "display: none;";
}
const styles4 = styles2String({ cssCompiledStyles: d3.data.cssCompiledStyles });
return styles4.nodeStyles + ";" + styles4.borderStyles.join(";");
});
sections6.append("text").attr("class", "treemapSectionLabel").attr("x", 6).attr("y", SECTION_HEADER_HEIGHT / 2).attr("dominant-baseline", "middle").text((d3) => d3.depth === 0 ? "" : d3.data.name).attr("font-weight", "bold").attr("style", (d3) => {
if (d3.depth === 0) {
return "display: none;";
}
const labelStyles = "dominant-baseline: middle; font-size: 12px; fill:" + colorScaleLabel(d3.data.name) + "; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;";
const styles4 = styles2String({ cssCompiledStyles: d3.data.cssCompiledStyles });
return labelStyles + styles4.labelStyles.replace("color:", "fill:");
}).each(function(d3) {
if (d3.depth === 0) {
return;
}
const self2 = select_default2(this);
const originalText = d3.data.name;
self2.text(originalText);
const totalHeaderWidth = d3.x1 - d3.x0;
const labelXPosition = 6;
let spaceForTextContent;
if (config5.showValues !== false && d3.value) {
const valueEndsAtXRelative = totalHeaderWidth - 10;
const estimatedValueTextActualWidth = 30;
const gapBetweenLabelAndValue = 10;
const labelMustEndBeforeX = valueEndsAtXRelative - estimatedValueTextActualWidth - gapBetweenLabelAndValue;
spaceForTextContent = labelMustEndBeforeX - labelXPosition;
} else {
const labelOwnRightPadding = 6;
spaceForTextContent = totalHeaderWidth - labelXPosition - labelOwnRightPadding;
}
const minimumWidthToDisplay = 15;
const actualAvailableWidth = Math.max(minimumWidthToDisplay, spaceForTextContent);
const textNode = self2.node();
const currentTextContentLength = textNode.getComputedTextLength();
if (currentTextContentLength > actualAvailableWidth) {
const ellipsis = "...";
let currentTruncatedText = originalText;
while (currentTruncatedText.length > 0) {
currentTruncatedText = originalText.substring(0, currentTruncatedText.length - 1);
if (currentTruncatedText.length === 0) {
self2.text(ellipsis);
if (textNode.getComputedTextLength() > actualAvailableWidth) {
self2.text("");
}
break;
}
self2.text(currentTruncatedText + ellipsis);
if (textNode.getComputedTextLength() <= actualAvailableWidth) {
break;
}
}
}
});
if (config5.showValues !== false) {
sections6.append("text").attr("class", "treemapSectionValue").attr("x", (d3) => d3.x1 - d3.x0 - 10).attr("y", SECTION_HEADER_HEIGHT / 2).attr("text-anchor", "end").attr("dominant-baseline", "middle").text((d3) => d3.value ? valueFormat(d3.value) : "").attr("font-style", "italic").attr("style", (d3) => {
if (d3.depth === 0) {
return "display: none;";
}
const labelStyles = "text-anchor: end; dominant-baseline: middle; font-size: 10px; fill:" + colorScaleLabel(d3.data.name) + "; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;";
const styles4 = styles2String({ cssCompiledStyles: d3.data.cssCompiledStyles });
return labelStyles + styles4.labelStyles.replace("color:", "fill:");
});
}
const leafNodes = treemapData.leaves();
const cell = g2.selectAll(".treemapLeafGroup").data(leafNodes).enter().append("g").attr("class", (d3, i2) => {
return `treemapNode treemapLeafGroup leaf${i2}${d3.data.classSelector ? ` ${d3.data.classSelector}` : ""}x`;
}).attr("transform", (d3) => `translate(${d3.x0},${d3.y0})`);
cell.append("rect").attr("width", (d3) => d3.x1 - d3.x0).attr("height", (d3) => d3.y1 - d3.y0).attr("class", "treemapLeaf").attr("fill", (d3) => {
return d3.parent ? colorScale(d3.parent.data.name) : colorScale(d3.data.name);
}).attr("style", (d3) => {
const styles4 = styles2String({ cssCompiledStyles: d3.data.cssCompiledStyles });
return styles4.nodeStyles;
}).attr("fill-opacity", 0.3).attr("stroke", (d3) => {
return d3.parent ? colorScale(d3.parent.data.name) : colorScale(d3.data.name);
}).attr("stroke-width", 3);
cell.append("clipPath").attr("id", (_d, i2) => `clip-${id32}-${i2}`).append("rect").attr("width", (d3) => Math.max(0, d3.x1 - d3.x0 - 4)).attr("height", (d3) => Math.max(0, d3.y1 - d3.y0 - 4));
const leafLabels = cell.append("text").attr("class", "treemapLabel").attr("x", (d3) => (d3.x1 - d3.x0) / 2).attr("y", (d3) => (d3.y1 - d3.y0) / 2).attr("style", (d3) => {
const labelStyles = "text-anchor: middle; dominant-baseline: middle; font-size: 38px;fill:" + colorScaleLabel(d3.data.name) + ";";
const styles4 = styles2String({ cssCompiledStyles: d3.data.cssCompiledStyles });
return labelStyles + styles4.labelStyles.replace("color:", "fill:");
}).attr("clip-path", (_d, i2) => `url(#clip-${id32}-${i2})`).text((d3) => d3.data.name);
leafLabels.each(function(d3) {
const self2 = select_default2(this);
const nodeWidth = d3.x1 - d3.x0;
const nodeHeight = d3.y1 - d3.y0;
const textNode = self2.node();
const padding2 = 4;
const availableWidth = nodeWidth - 2 * padding2;
const availableHeight = nodeHeight - 2 * padding2;
if (availableWidth < 10 || availableHeight < 10) {
self2.style("display", "none");
return;
}
let currentLabelFontSize = parseInt(self2.style("font-size"), 10);
const minLabelFontSize = 8;
const originalValueRelFontSize = 28;
const valueScaleFactor = 0.6;
const minValueFontSize = 6;
const spacingBetweenLabelAndValue = 2;
while (textNode.getComputedTextLength() > availableWidth && currentLabelFontSize > minLabelFontSize) {
currentLabelFontSize--;
self2.style("font-size", `${currentLabelFontSize}px`);
}
let prospectiveValueFontSize = Math.max(
minValueFontSize,
Math.min(originalValueRelFontSize, Math.round(currentLabelFontSize * valueScaleFactor))
);
let combinedHeight = currentLabelFontSize + spacingBetweenLabelAndValue + prospectiveValueFontSize;
while (combinedHeight > availableHeight && currentLabelFontSize > minLabelFontSize) {
currentLabelFontSize--;
prospectiveValueFontSize = Math.max(
minValueFontSize,
Math.min(originalValueRelFontSize, Math.round(currentLabelFontSize * valueScaleFactor))
);
if (prospectiveValueFontSize < minValueFontSize && currentLabelFontSize === minLabelFontSize) {
break;
}
self2.style("font-size", `${currentLabelFontSize}px`);
combinedHeight = currentLabelFontSize + spacingBetweenLabelAndValue + prospectiveValueFontSize;
if (prospectiveValueFontSize <= minValueFontSize && combinedHeight > availableHeight) {
}
}
self2.style("font-size", `${currentLabelFontSize}px`);
if (textNode.getComputedTextLength() > availableWidth || currentLabelFontSize < minLabelFontSize || availableHeight < currentLabelFontSize) {
self2.style("display", "none");
}
});
if (config5.showValues !== false) {
const leafValues = cell.append("text").attr("class", "treemapValue").attr("x", (d3) => (d3.x1 - d3.x0) / 2).attr("y", function(d3) {
return (d3.y1 - d3.y0) / 2;
}).attr("style", (d3) => {
const labelStyles = "text-anchor: middle; dominant-baseline: hanging; font-size: 28px;fill:" + colorScaleLabel(d3.data.name) + ";";
const styles4 = styles2String({ cssCompiledStyles: d3.data.cssCompiledStyles });
return labelStyles + styles4.labelStyles.replace("color:", "fill:");
}).attr("clip-path", (_d, i2) => `url(#clip-${id32}-${i2})`).text((d3) => d3.value ? valueFormat(d3.value) : "");
leafValues.each(function(d3) {
const valueTextElement = select_default2(this);
const parentCellNode = this.parentNode;
if (!parentCellNode) {
valueTextElement.style("display", "none");
return;
}
const labelElement = select_default2(parentCellNode).select(".treemapLabel");
if (labelElement.empty() || labelElement.style("display") === "none") {
valueTextElement.style("display", "none");
return;
}
const finalLabelFontSize = parseFloat(labelElement.style("font-size"));
const originalValueFontSize = 28;
const valueScaleFactor = 0.6;
const minValueFontSize = 6;
const spacingBetweenLabelAndValue = 2;
const actualValueFontSize = Math.max(
minValueFontSize,
Math.min(originalValueFontSize, Math.round(finalLabelFontSize * valueScaleFactor))
);
valueTextElement.style("font-size", `${actualValueFontSize}px`);
const labelCenterY = (d3.y1 - d3.y0) / 2;
const valueTopActualY = labelCenterY + finalLabelFontSize / 2 + spacingBetweenLabelAndValue;
valueTextElement.attr("y", valueTopActualY);
const nodeWidth = d3.x1 - d3.x0;
const nodeTotalHeight = d3.y1 - d3.y0;
const cellBottomPadding = 4;
const maxValueBottomY = nodeTotalHeight - cellBottomPadding;
const availableWidthForValue = nodeWidth - 2 * 4;
if (valueTextElement.node().getComputedTextLength() > availableWidthForValue || valueTopActualY + actualValueFontSize > maxValueBottomY || actualValueFontSize < minValueFontSize) {
valueTextElement.style("display", "none");
} else {
valueTextElement.style("display", null);
}
});
}
const diagramPadding = config5.diagramPadding ?? 8;
setupViewPortForSVG(svg2, diagramPadding, "flowchart", config5?.useMaxWidth || false);
}, "draw");
getClasses6 = /* @__PURE__ */ __name(function(_text, diagramObj) {
return diagramObj.db.getClasses();
}, "getClasses");
renderer11 = { draw: draw27, getClasses: getClasses6 };
}
});
// src/diagrams/treemap/styles.ts
var defaultTreemapStyleOptions, getStyles21, styles_default18;
var init_styles20 = __esm({
"src/diagrams/treemap/styles.ts"() {
"use strict";
init_utils2();
defaultTreemapStyleOptions = {
sectionStrokeColor: "black",
sectionStrokeWidth: "1",
sectionFillColor: "#efefef",
leafStrokeColor: "black",
leafStrokeWidth: "1",
leafFillColor: "#efefef",
labelColor: "black",
labelFontSize: "12px",
valueFontSize: "10px",
valueColor: "black",
titleColor: "black",
titleFontSize: "14px"
};
getStyles21 = /* @__PURE__ */ __name(({
treemap: treemap2
} = {}) => {
const options2 = cleanAndMerge(defaultTreemapStyleOptions, treemap2);
return `
.treemapNode.section {
stroke: ${options2.sectionStrokeColor};
stroke-width: ${options2.sectionStrokeWidth};
fill: ${options2.sectionFillColor};
}
.treemapNode.leaf {
stroke: ${options2.leafStrokeColor};
stroke-width: ${options2.leafStrokeWidth};
fill: ${options2.leafFillColor};
}
.treemapLabel {
fill: ${options2.labelColor};
font-size: ${options2.labelFontSize};
}
.treemapValue {
fill: ${options2.valueColor};
font-size: ${options2.valueFontSize};
}
.treemapTitle {
fill: ${options2.titleColor};
font-size: ${options2.titleFontSize};
}
`;
}, "getStyles");
styles_default18 = getStyles21;
}
});
// src/diagrams/treemap/diagram.ts
var diagram_exports3 = {};
__export(diagram_exports3, {
diagram: () => diagram28
});
var diagram28;
var init_diagram3 = __esm({
"src/diagrams/treemap/diagram.ts"() {
"use strict";
init_db3();
init_parser5();
init_renderer3();
init_styles20();
diagram28 = {
parser: parser25,
get db() {
return new TreeMapDB();
},
renderer: renderer11,
styles: styles_default18
};
}
});
// src/mermaid.ts
var mermaid_exports = {};
__export(mermaid_exports, {
default: () => mermaid_default
});
init_icons();
init_esm();
init_detectType();
// src/diagrams/c4/c4Detector.ts
var id2 = "c4";
var detector = /* @__PURE__ */ __name((txt) => {
return /^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/.test(txt);
}, "detector");
var loader = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_c4Diagram2(), c4Diagram_exports));
return { id: id2, diagram: diagram29 };
}, "loader");
var plugin = {
id: id2,
detector,
loader
};
var c4Detector_default = plugin;
// src/diagrams/flowchart/flowDetector.ts
var id4 = "flowchart";
var detector2 = /* @__PURE__ */ __name((txt, config5) => {
if (config5?.flowchart?.defaultRenderer === "dagre-wrapper" || config5?.flowchart?.defaultRenderer === "elk") {
return false;
}
return /^\s*graph/.test(txt);
}, "detector");
var loader3 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_flowDiagram(), flowDiagram_exports));
return { id: id4, diagram: diagram29 };
}, "loader");
var plugin2 = {
id: id4,
detector: detector2,
loader: loader3
};
var flowDetector_default = plugin2;
// src/diagrams/flowchart/flowDetector-v2.ts
var id5 = "flowchart-v2";
var detector3 = /* @__PURE__ */ __name((txt, config5) => {
if (config5?.flowchart?.defaultRenderer === "dagre-d3") {
return false;
}
if (config5?.flowchart?.defaultRenderer === "elk") {
config5.layout = "elk";
}
if (/^\s*graph/.test(txt) && config5?.flowchart?.defaultRenderer === "dagre-wrapper") {
return true;
}
return /^\s*flowchart/.test(txt);
}, "detector");
var loader4 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_flowDiagram(), flowDiagram_exports));
return { id: id5, diagram: diagram29 };
}, "loader");
var plugin3 = {
id: id5,
detector: detector3,
loader: loader4
};
var flowDetector_v2_default = plugin3;
// src/diagrams/er/erDetector.ts
var id6 = "er";
var detector4 = /* @__PURE__ */ __name((txt) => {
return /^\s*erDiagram/.test(txt);
}, "detector");
var loader5 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_erDiagram2(), erDiagram_exports));
return { id: id6, diagram: diagram29 };
}, "loader");
var plugin4 = {
id: id6,
detector: detector4,
loader: loader5
};
var erDetector_default = plugin4;
// src/diagrams/git/gitGraphDetector.ts
var id7 = "gitGraph";
var detector5 = /* @__PURE__ */ __name((txt) => {
return /^\s*gitGraph/.test(txt);
}, "detector");
var loader6 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_gitGraphDiagram(), gitGraphDiagram_exports));
return { id: id7, diagram: diagram29 };
}, "loader");
var plugin5 = {
id: id7,
detector: detector5,
loader: loader6
};
var gitGraphDetector_default = plugin5;
// src/diagrams/gantt/ganttDetector.ts
var id8 = "gantt";
var detector6 = /* @__PURE__ */ __name((txt) => {
return /^\s*gantt/.test(txt);
}, "detector");
var loader7 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_ganttDiagram(), ganttDiagram_exports));
return { id: id8, diagram: diagram29 };
}, "loader");
var plugin6 = {
id: id8,
detector: detector6,
loader: loader7
};
var ganttDetector_default = plugin6;
// src/diagrams/info/infoDetector.ts
var id9 = "info";
var detector7 = /* @__PURE__ */ __name((txt) => {
return /^\s*info/.test(txt);
}, "detector");
var loader8 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_infoDiagram(), infoDiagram_exports));
return { id: id9, diagram: diagram29 };
}, "loader");
var info = {
id: id9,
detector: detector7,
loader: loader8
};
// src/diagrams/pie/pieDetector.ts
var id10 = "pie";
var detector8 = /* @__PURE__ */ __name((txt) => {
return /^\s*pie/.test(txt);
}, "detector");
var loader9 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_pieDiagram(), pieDiagram_exports));
return { id: id10, diagram: diagram29 };
}, "loader");
var pie = {
id: id10,
detector: detector8,
loader: loader9
};
// src/diagrams/quadrant-chart/quadrantDetector.ts
var id11 = "quadrantChart";
var detector9 = /* @__PURE__ */ __name((txt) => {
return /^\s*quadrantChart/.test(txt);
}, "detector");
var loader10 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_quadrantDiagram(), quadrantDiagram_exports));
return { id: id11, diagram: diagram29 };
}, "loader");
var plugin7 = {
id: id11,
detector: detector9,
loader: loader10
};
var quadrantDetector_default = plugin7;
// src/diagrams/xychart/xychartDetector.ts
var id12 = "xychart";
var detector10 = /* @__PURE__ */ __name((txt) => {
return /^\s*xychart(-beta)?/.test(txt);
}, "detector");
var loader11 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_xychartDiagram(), xychartDiagram_exports));
return { id: id12, diagram: diagram29 };
}, "loader");
var plugin8 = {
id: id12,
detector: detector10,
loader: loader11
};
var xychartDetector_default = plugin8;
// src/diagrams/requirement/requirementDetector.ts
var id13 = "requirement";
var detector11 = /* @__PURE__ */ __name((txt) => {
return /^\s*requirement(Diagram)?/.test(txt);
}, "detector");
var loader12 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_requirementDiagram2(), requirementDiagram_exports));
return { id: id13, diagram: diagram29 };
}, "loader");
var plugin9 = {
id: id13,
detector: detector11,
loader: loader12
};
var requirementDetector_default = plugin9;
// src/diagrams/sequence/sequenceDetector.ts
var id14 = "sequence";
var detector12 = /* @__PURE__ */ __name((txt) => {
return /^\s*sequenceDiagram/.test(txt);
}, "detector");
var loader13 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_sequenceDiagram2(), sequenceDiagram_exports));
return { id: id14, diagram: diagram29 };
}, "loader");
var plugin10 = {
id: id14,
detector: detector12,
loader: loader13
};
var sequenceDetector_default = plugin10;
// src/diagrams/class/classDetector.ts
var id15 = "class";
var detector13 = /* @__PURE__ */ __name((txt, config5) => {
if (config5?.class?.defaultRenderer === "dagre-wrapper") {
return false;
}
return /^\s*classDiagram/.test(txt);
}, "detector");
var loader14 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_classDiagram2(), classDiagram_exports));
return { id: id15, diagram: diagram29 };
}, "loader");
var plugin11 = {
id: id15,
detector: detector13,
loader: loader14
};
var classDetector_default = plugin11;
// src/diagrams/class/classDetector-V2.ts
var id16 = "classDiagram";
var detector14 = /* @__PURE__ */ __name((txt, config5) => {
if (/^\s*classDiagram/.test(txt) && config5?.class?.defaultRenderer === "dagre-wrapper") {
return true;
}
return /^\s*classDiagram-v2/.test(txt);
}, "detector");
var loader15 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_classDiagram_v2(), classDiagram_v2_exports));
return { id: id16, diagram: diagram29 };
}, "loader");
var plugin12 = {
id: id16,
detector: detector14,
loader: loader15
};
var classDetector_V2_default = plugin12;
// src/diagrams/state/stateDetector.ts
var id17 = "state";
var detector15 = /* @__PURE__ */ __name((txt, config5) => {
if (config5?.state?.defaultRenderer === "dagre-wrapper") {
return false;
}
return /^\s*stateDiagram/.test(txt);
}, "detector");
var loader16 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_stateDiagram2(), stateDiagram_exports));
return { id: id17, diagram: diagram29 };
}, "loader");
var plugin13 = {
id: id17,
detector: detector15,
loader: loader16
};
var stateDetector_default = plugin13;
// src/diagrams/state/stateDetector-V2.ts
var id18 = "stateDiagram";
var detector16 = /* @__PURE__ */ __name((txt, config5) => {
if (/^\s*stateDiagram-v2/.test(txt)) {
return true;
}
if (/^\s*stateDiagram/.test(txt) && config5?.state?.defaultRenderer === "dagre-wrapper") {
return true;
}
return false;
}, "detector");
var loader17 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_stateDiagram_v2(), stateDiagram_v2_exports));
return { id: id18, diagram: diagram29 };
}, "loader");
var plugin14 = {
id: id18,
detector: detector16,
loader: loader17
};
var stateDetector_V2_default = plugin14;
// src/diagrams/user-journey/journeyDetector.ts
var id19 = "journey";
var detector17 = /* @__PURE__ */ __name((txt) => {
return /^\s*journey/.test(txt);
}, "detector");
var loader18 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_journeyDiagram(), journeyDiagram_exports));
return { id: id19, diagram: diagram29 };
}, "loader");
var plugin15 = {
id: id19,
detector: detector17,
loader: loader18
};
var journeyDetector_default = plugin15;
// src/diagrams/error/errorRenderer.ts
init_logger();
init_selectSvgElement();
init_setupGraphViewbox();
var draw16 = /* @__PURE__ */ __name((_text, id32, version3) => {
log.debug("rendering svg for syntax error\n");
const svg2 = selectSvgElement(id32);
const g2 = svg2.append("g");
svg2.attr("viewBox", "0 0 2412 512");
configureSvgSize(svg2, 100, 512, true);
g2.append("path").attr("class", "error-icon").attr(
"d",
"m411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z"
);
g2.append("path").attr("class", "error-icon").attr(
"d",
"m459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z"
);
g2.append("path").attr("class", "error-icon").attr(
"d",
"m340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z"
);
g2.append("path").attr("class", "error-icon").attr(
"d",
"m400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z"
);
g2.append("path").attr("class", "error-icon").attr(
"d",
"m496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z"
);
g2.append("path").attr("class", "error-icon").attr(
"d",
"m436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z"
);
g2.append("text").attr("class", "error-text").attr("x", 1440).attr("y", 250).attr("font-size", "150px").style("text-anchor", "middle").text("Syntax error in text");
g2.append("text").attr("class", "error-text").attr("x", 1250).attr("y", 400).attr("font-size", "100px").style("text-anchor", "middle").text(`mermaid version ${version3}`);
}, "draw");
var renderer5 = { draw: draw16 };
var errorRenderer_default = renderer5;
// src/diagrams/error/errorDiagram.ts
var diagram17 = {
db: {},
renderer: renderer5,
parser: {
parse: /* @__PURE__ */ __name(() => {
return;
}, "parse")
}
};
var errorDiagram_default = diagram17;
// src/diagrams/flowchart/elk/detector.ts
var id20 = "flowchart-elk";
var detector18 = /* @__PURE__ */ __name((txt, config5 = {}) => {
if (
// If diagram explicitly states flowchart-elk
/^\s*flowchart-elk/.test(txt) || // If a flowchart/graph diagram has their default renderer set to elk
/^\s*(flowchart|graph)/.test(txt) && config5?.flowchart?.defaultRenderer === "elk"
) {
config5.layout = "elk";
return true;
}
return false;
}, "detector");
var loader19 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_flowDiagram(), flowDiagram_exports));
return { id: id20, diagram: diagram29 };
}, "loader");
var plugin16 = {
id: id20,
detector: detector18,
loader: loader19
};
var detector_default = plugin16;
// src/diagrams/timeline/detector.ts
var id21 = "timeline";
var detector19 = /* @__PURE__ */ __name((txt) => {
return /^\s*timeline/.test(txt);
}, "detector");
var loader20 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_timeline_definition(), timeline_definition_exports));
return { id: id21, diagram: diagram29 };
}, "loader");
var plugin17 = {
id: id21,
detector: detector19,
loader: loader20
};
var detector_default2 = plugin17;
// src/diagrams/mindmap/detector.ts
var id22 = "mindmap";
var detector20 = /* @__PURE__ */ __name((txt) => {
return /^\s*mindmap/.test(txt);
}, "detector");
var loader21 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_mindmap_definition(), mindmap_definition_exports));
return { id: id22, diagram: diagram29 };
}, "loader");
var plugin18 = {
id: id22,
detector: detector20,
loader: loader21
};
var detector_default3 = plugin18;
// src/diagrams/kanban/detector.ts
var id23 = "kanban";
var detector21 = /* @__PURE__ */ __name((txt) => {
return /^\s*kanban/.test(txt);
}, "detector");
var loader22 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_kanban_definition(), kanban_definition_exports));
return { id: id23, diagram: diagram29 };
}, "loader");
var plugin19 = {
id: id23,
detector: detector21,
loader: loader22
};
var detector_default4 = plugin19;
// src/diagrams/sankey/sankeyDetector.ts
var id24 = "sankey";
var detector22 = /* @__PURE__ */ __name((txt) => {
return /^\s*sankey(-beta)?/.test(txt);
}, "detector");
var loader23 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_sankeyDiagram(), sankeyDiagram_exports));
return { id: id24, diagram: diagram29 };
}, "loader");
var plugin20 = {
id: id24,
detector: detector22,
loader: loader23
};
var sankeyDetector_default = plugin20;
// src/diagrams/packet/detector.ts
var id25 = "packet";
var detector23 = /* @__PURE__ */ __name((txt) => {
return /^\s*packet(-beta)?/.test(txt);
}, "detector");
var loader24 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_diagram(), diagram_exports));
return { id: id25, diagram: diagram29 };
}, "loader");
var packet = {
id: id25,
detector: detector23,
loader: loader24
};
// src/diagrams/radar/detector.ts
var id26 = "radar";
var detector24 = /* @__PURE__ */ __name((txt) => {
return /^\s*radar-beta/.test(txt);
}, "detector");
var loader25 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_diagram2(), diagram_exports2));
return { id: id26, diagram: diagram29 };
}, "loader");
var radar = {
id: id26,
detector: detector24,
loader: loader25
};
// src/diagrams/block/blockDetector.ts
var id27 = "block";
var detector25 = /* @__PURE__ */ __name((txt) => {
return /^\s*block(-beta)?/.test(txt);
}, "detector");
var loader26 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_blockDiagram(), blockDiagram_exports));
return { id: id27, diagram: diagram29 };
}, "loader");
var plugin21 = {
id: id27,
detector: detector25,
loader: loader26
};
var blockDetector_default = plugin21;
// src/diagrams/architecture/architectureDetector.ts
var id28 = "architecture";
var detector26 = /* @__PURE__ */ __name((txt) => {
return /^\s*architecture/.test(txt);
}, "detector");
var loader27 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_architectureDiagram(), architectureDiagram_exports));
return { id: id28, diagram: diagram29 };
}, "loader");
var architecture = {
id: id28,
detector: detector26,
loader: loader27
};
var architectureDetector_default = architecture;
// src/diagrams/ishikawa/ishikawaDetector.ts
var id29 = "ishikawa";
var detector27 = /* @__PURE__ */ __name((txt) => {
return /^\s*ishikawa(-beta)?\b/i.test(txt);
}, "detector");
var loader28 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_ishikawaDiagram(), ishikawaDiagram_exports));
return { id: id29, diagram: diagram29 };
}, "loader");
var ishikawa = {
id: id29,
detector: detector27,
loader: loader28
};
// src/diagrams/venn/vennDetector.ts
var id30 = "venn";
var detector28 = /* @__PURE__ */ __name((txt) => {
return /^\s*venn-beta/.test(txt);
}, "detector");
var loader29 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_vennDiagram(), vennDiagram_exports));
return { id: id30, diagram: diagram29 };
}, "loader");
var plugin22 = {
id: id30,
detector: detector28,
loader: loader29
};
var vennDetector_default = plugin22;
// src/diagram-api/diagram-orchestration.ts
init_detectType();
init_diagramAPI();
// src/diagrams/treemap/detector.ts
var id31 = "treemap";
var detector29 = /* @__PURE__ */ __name((txt) => {
return /^\s*treemap/.test(txt);
}, "detector");
var loader30 = /* @__PURE__ */ __name(async () => {
const { diagram: diagram29 } = await Promise.resolve().then(() => (init_diagram3(), diagram_exports3));
return { id: id31, diagram: diagram29 };
}, "loader");
var treemap = {
id: id31,
detector: detector29,
loader: loader30
};
// src/diagram-api/diagram-orchestration.ts
var hasLoadedDiagrams = false;
var addDiagrams = /* @__PURE__ */ __name(() => {
if (hasLoadedDiagrams) {
return;
}
hasLoadedDiagrams = true;
registerDiagram("error", errorDiagram_default, (text4) => {
return text4.toLowerCase().trim() === "error";
});
registerDiagram(
"---",
// --- diagram type may appear if YAML front-matter is not parsed correctly
{
db: {
clear: /* @__PURE__ */ __name(() => {
}, "clear")
},
styles: {},
// should never be used
renderer: {
draw: /* @__PURE__ */ __name(() => {
}, "draw")
},
parser: {
parse: /* @__PURE__ */ __name(() => {
throw new Error(
"Diagrams beginning with --- are not valid. If you were trying to use a YAML front-matter, please ensure that you've correctly opened and closed the YAML front-matter with un-indented `---` blocks"
);
}, "parse")
},
init: /* @__PURE__ */ __name(() => null, "init")
// no op
},
(text4) => {
return text4.toLowerCase().trimStart().startsWith("---");
}
);
if (true) {
registerLazyLoadedDiagrams(detector_default, detector_default3, architectureDetector_default);
}
registerLazyLoadedDiagrams(
c4Detector_default,
detector_default4,
classDetector_V2_default,
classDetector_default,
erDetector_default,
ganttDetector_default,
info,
pie,
requirementDetector_default,
sequenceDetector_default,
flowDetector_v2_default,
flowDetector_default,
detector_default2,
gitGraphDetector_default,
stateDetector_V2_default,
stateDetector_default,
journeyDetector_default,
quadrantDetector_default,
sankeyDetector_default,
packet,
xychartDetector_default,
blockDetector_default,
radar,
ishikawa,
treemap,
vennDetector_default
);
}, "addDiagrams");
// src/diagram-api/loadDiagram.ts
init_logger();
init_detectType();
init_diagramAPI();
var loadRegisteredDiagrams = /* @__PURE__ */ __name(async () => {
log.debug(`Loading registered diagrams`);
const results = await Promise.allSettled(
Object.entries(detectors).map(async ([key, { detector: detector30, loader: loader31 }]) => {
if (!loader31) {
return;
}
try {
getDiagram(key);
} catch {
try {
const { diagram: diagram29, id: id32 } = await loader31();
registerDiagram(id32, diagram29, detector30);
} catch (err) {
log.error(`Failed to load external diagram with key ${key}. Removing from detectors.`);
delete detectors[key];
throw err;
}
}
})
);
const failed = results.filter((result) => result.status === "rejected");
if (failed.length > 0) {
log.error(`Failed to load ${failed.length} external diagrams`);
for (const res of failed) {
log.error(res);
}
throw new Error(`Failed to load ${failed.length} external diagrams`);
}
}, "loadRegisteredDiagrams");
// src/mermaid.ts
init_logger();
// src/mermaidAPI.ts
init_src32();
// ../../node_modules/.pnpm/stylis@4.3.6/node_modules/stylis/src/Enum.js
var COMMENT = "comm";
var RULESET = "rule";
var DECLARATION = "decl";
var IMPORT = "@import";
var NAMESPACE = "@namespace";
var KEYFRAMES = "@keyframes";
var LAYER = "@layer";
// ../../node_modules/.pnpm/stylis@4.3.6/node_modules/stylis/src/Utility.js
var abs3 = Math.abs;
var from = String.fromCharCode;
function trim(value2) {
return value2.trim();
}
__name(trim, "trim");
function replace(value2, pattern, replacement) {
return value2.replace(pattern, replacement);
}
__name(replace, "replace");
function indexof(value2, search, position5) {
return value2.indexOf(search, position5);
}
__name(indexof, "indexof");
function charat(value2, index) {
return value2.charCodeAt(index) | 0;
}
__name(charat, "charat");
function substr(value2, begin, end2) {
return value2.slice(begin, end2);
}
__name(substr, "substr");
function strlen(value2) {
return value2.length;
}
__name(strlen, "strlen");
function sizeof(value2) {
return value2.length;
}
__name(sizeof, "sizeof");
function append2(value2, array4) {
return array4.push(value2), value2;
}
__name(append2, "append");
// ../../node_modules/.pnpm/stylis@4.3.6/node_modules/stylis/src/Tokenizer.js
var line = 1;
var column = 1;
var length = 0;
var position4 = 0;
var character = 0;
var characters = "";
function node(value2, root3, parent4, type3, props, children2, length2, siblings2) {
return { value: value2, root: root3, parent: parent4, type: type3, props, children: children2, line, column, length: length2, return: "", siblings: siblings2 };
}
__name(node, "node");
function char() {
return character;
}
__name(char, "char");
function prev() {
character = position4 > 0 ? charat(characters, --position4) : 0;
if (column--, character === 10)
column = 1, line--;
return character;
}
__name(prev, "prev");
function next2() {
character = position4 < length ? charat(characters, position4++) : 0;
if (column++, character === 10)
column = 1, line++;
return character;
}
__name(next2, "next");
function peek() {
return charat(characters, position4);
}
__name(peek, "peek");
function caret() {
return position4;
}
__name(caret, "caret");
function slice4(begin, end2) {
return substr(characters, begin, end2);
}
__name(slice4, "slice");
function token(type3) {
switch (type3) {
// \0 \t \n \r \s whitespace token
case 0:
case 9:
case 10:
case 13:
case 32:
return 5;
// ! + , / > @ ~ isolate token
case 33:
case 43:
case 44:
case 47:
case 62:
case 64:
case 126:
// ; { } breakpoint token
case 59:
case 123:
case 125:
return 4;
// : accompanied token
case 58:
return 3;
// " ' ( [ opening delimit token
case 34:
case 39:
case 40:
case 91:
return 2;
// ) ] closing delimit token
case 41:
case 93:
return 1;
}
return 0;
}
__name(token, "token");
function alloc(value2) {
return line = column = 1, length = strlen(characters = value2), position4 = 0, [];
}
__name(alloc, "alloc");
function dealloc(value2) {
return characters = "", value2;
}
__name(dealloc, "dealloc");
function delimit(type3) {
return trim(slice4(position4 - 1, delimiter2(type3 === 91 ? type3 + 2 : type3 === 40 ? type3 + 1 : type3)));
}
__name(delimit, "delimit");
function whitespace(type3) {
while (character = peek())
if (character < 33)
next2();
else
break;
return token(type3) > 2 || token(character) > 3 ? "" : " ";
}
__name(whitespace, "whitespace");
function escaping(index, count2) {
while (--count2 && next2())
if (character < 48 || character > 102 || character > 57 && character < 65 || character > 70 && character < 97)
break;
return slice4(index, caret() + (count2 < 6 && peek() == 32 && next2() == 32));
}
__name(escaping, "escaping");
function delimiter2(type3) {
while (next2())
switch (character) {
// ] ) " '
case type3:
return position4;
// " '
case 34:
case 39:
if (type3 !== 34 && type3 !== 39)
delimiter2(character);
break;
// (
case 40:
if (type3 === 41)
delimiter2(type3);
break;
// \
case 92:
next2();
break;
}
return position4;
}
__name(delimiter2, "delimiter");
function commenter(type3, index) {
while (next2())
if (type3 + character === 47 + 10)
break;
else if (type3 + character === 42 + 42 && peek() === 47)
break;
return "/*" + slice4(index, position4 - 1) + "*" + from(type3 === 47 ? type3 : next2());
}
__name(commenter, "commenter");
function identifier(index) {
while (!token(peek()))
next2();
return slice4(index, position4);
}
__name(identifier, "identifier");
// ../../node_modules/.pnpm/stylis@4.3.6/node_modules/stylis/src/Parser.js
function compile(value2) {
return dealloc(parse4("", null, null, null, [""], value2 = alloc(value2), 0, [0], value2));
}
__name(compile, "compile");
function parse4(value2, root3, parent4, rule, rules, rulesets, pseudo, points, declarations) {
var index = 0;
var offset = 0;
var length2 = pseudo;
var atrule = 0;
var property2 = 0;
var previous = 0;
var variable = 1;
var scanning = 1;
var ampersand = 1;
var character2 = 0;
var type3 = "";
var props = rules;
var children2 = rulesets;
var reference = rule;
var characters2 = type3;
while (scanning)
switch (previous = character2, character2 = next2()) {
// (
case 40:
if (previous != 108 && charat(characters2, length2 - 1) == 58) {
if (indexof(characters2 += replace(delimit(character2), "&", "&\f"), "&\f", abs3(index ? points[index - 1] : 0)) != -1)
ampersand = -1;
break;
}
// " ' [
case 34:
case 39:
case 91:
characters2 += delimit(character2);
break;
// \t \n \r \s
case 9:
case 10:
case 13:
case 32:
characters2 += whitespace(previous);
break;
// \
case 92:
characters2 += escaping(caret() - 1, 7);
continue;
// /
case 47:
switch (peek()) {
case 42:
case 47:
append2(comment(commenter(next2(), caret()), root3, parent4, declarations), declarations);
if ((token(previous || 1) == 5 || token(peek() || 1) == 5) && strlen(characters2) && substr(characters2, -1, void 0) !== " ") characters2 += " ";
break;
default:
characters2 += "/";
}
break;
// {
case 123 * variable:
points[index++] = strlen(characters2) * ampersand;
// } ; \0
case 125 * variable:
case 59:
case 0:
switch (character2) {
// \0 }
case 0:
case 125:
scanning = 0;
// ;
case 59 + offset:
if (ampersand == -1) characters2 = replace(characters2, /\f/g, "");
if (property2 > 0 && (strlen(characters2) - length2 || variable === 0 && previous === 47))
append2(property2 > 32 ? declaration(characters2 + ";", rule, parent4, length2 - 1, declarations) : declaration(replace(characters2, " ", "") + ";", rule, parent4, length2 - 2, declarations), declarations);
break;
// @ ;
case 59:
characters2 += ";";
// { rule/at-rule
default:
append2(reference = ruleset(characters2, root3, parent4, index, offset, rules, points, type3, props = [], children2 = [], length2, rulesets), rulesets);
if (character2 === 123)
if (offset === 0)
parse4(characters2, root3, reference, reference, props, rulesets, length2, points, children2);
else {
switch (atrule) {
// c(ontainer)
case 99:
if (charat(characters2, 3) === 110) break;
// l(ayer)
case 108:
if (charat(characters2, 2) === 97) break;
default:
offset = 0;
// d(ocument) m(edia) s(upports)
case 100:
case 109:
case 115:
}
if (offset) parse4(value2, reference, reference, rule && append2(ruleset(value2, reference, reference, 0, 0, rules, points, type3, rules, props = [], length2, children2), children2), rules, children2, length2, points, rule ? props : children2);
else parse4(characters2, reference, reference, reference, [""], children2, 0, points, children2);
}
}
index = offset = property2 = 0, variable = ampersand = 1, type3 = characters2 = "", length2 = pseudo;
break;
// :
case 58:
length2 = 1 + strlen(characters2), property2 = previous;
default:
if (variable < 1) {
if (character2 == 123)
--variable;
else if (character2 == 125 && variable++ == 0 && prev() == 125)
continue;
}
switch (characters2 += from(character2), character2 * variable) {
// &
case 38:
ampersand = offset > 0 ? 1 : (characters2 += "\f", -1);
break;
// ,
case 44:
points[index++] = (strlen(characters2) - 1) * ampersand, ampersand = 1;
break;
// @
case 64:
if (peek() === 45)
characters2 += delimit(next2());
atrule = peek(), offset = length2 = strlen(type3 = characters2 += identifier(caret())), character2++;
break;
// -
case 45:
if (previous === 45 && strlen(characters2) == 2)
variable = 0;
}
}
return rulesets;
}
__name(parse4, "parse");
function ruleset(value2, root3, parent4, index, offset, rules, points, type3, props, children2, length2, siblings2) {
var post = offset - 1;
var rule = offset === 0 ? rules : [""];
var size4 = sizeof(rule);
for (var i2 = 0, j3 = 0, k2 = 0; i2 < index; ++i2)
for (var x5 = 0, y6 = substr(value2, post + 1, post = abs3(j3 = points[i2])), z3 = value2; x5 < size4; ++x5)
if (z3 = trim(j3 > 0 ? rule[x5] + " " + y6 : replace(y6, /&\f/g, rule[x5])))
props[k2++] = z3;
return node(value2, root3, parent4, offset === 0 ? RULESET : type3, props, children2, length2, siblings2);
}
__name(ruleset, "ruleset");
function comment(value2, root3, parent4, siblings2) {
return node(value2, root3, parent4, COMMENT, from(char()), substr(value2, 2, -2), 0, siblings2);
}
__name(comment, "comment");
function declaration(value2, root3, parent4, length2, siblings2) {
return node(value2, root3, parent4, DECLARATION, substr(value2, 0, length2), substr(value2, length2 + 1, -1), length2, siblings2);
}
__name(declaration, "declaration");
// ../../node_modules/.pnpm/stylis@4.3.6/node_modules/stylis/src/Serializer.js
function serialize(children2, callback) {
var output2 = "";
for (var i2 = 0; i2 < children2.length; i2++)
output2 += callback(children2[i2], i2, children2, callback) || "";
return output2;
}
__name(serialize, "serialize");
function stringify(element3, index, children2, callback) {
switch (element3.type) {
case LAYER:
if (element3.children.length) break;
case IMPORT:
case NAMESPACE:
case DECLARATION:
return element3.return = element3.return || element3.value;
case COMMENT:
return "";
case KEYFRAMES:
return element3.return = element3.value + "{" + serialize(element3.children, callback) + "}";
case RULESET:
if (!strlen(element3.value = element3.props.join(","))) return "";
}
return strlen(children2 = serialize(element3.children, callback)) ? element3.return = element3.value + "{" + children2 + "}" : "";
}
__name(stringify, "stringify");
// src/mermaidAPI.ts
init_purify_es();
init_isEmpty();
// src/accessibility.ts
var SVG_ROLE = "graphics-document document";
function setA11yDiagramInfo(svg2, diagramType) {
svg2.attr("role", SVG_ROLE);
if (diagramType !== "") {
svg2.attr("aria-roledescription", diagramType);
}
}
__name(setA11yDiagramInfo, "setA11yDiagramInfo");
function addSVGa11yTitleDescription(svg2, a11yTitle, a11yDesc, baseId) {
if (svg2.insert === void 0) {
return;
}
if (a11yDesc) {
const descId = `chart-desc-${baseId}`;
svg2.attr("aria-describedby", descId);
svg2.insert("desc", ":first-child").attr("id", descId).text(a11yDesc);
}
if (a11yTitle) {
const titleId = `chart-title-${baseId}`;
svg2.attr("aria-labelledby", titleId);
svg2.insert("title", ":first-child").attr("id", titleId).text(a11yTitle);
}
}
__name(addSVGa11yTitleDescription, "addSVGa11yTitleDescription");
// src/mermaidAPI.ts
init_assignWithDepth();
init_config();
init_config();
// src/Diagram.ts
init_config();
init_diagramAPI();
init_detectType();
init_errors();
init_utils2();
var Diagram = class _Diagram {
constructor(type3, text4, db8, parser26, renderer12) {
this.type = type3;
this.text = text4;
this.db = db8;
this.parser = parser26;
this.renderer = renderer12;
}
static {
__name(this, "Diagram");
}
static async fromText(text4, metadata = {}) {
const config5 = getConfig();
const type3 = detectType(text4, config5);
text4 = encodeEntities(text4) + "\n";
try {
getDiagram(type3);
} catch {
const loader31 = getDiagramLoader(type3);
if (!loader31) {
throw new UnknownDiagramError(`Diagram ${type3} not found.`);
}
const { id: id32, diagram: diagram29 } = await loader31();
registerDiagram(id32, diagram29);
}
const { db: db8, parser: parser26, renderer: renderer12, init: init3 } = getDiagram(type3);
if (parser26.parser) {
parser26.parser.yy = db8;
}
db8.clear?.();
init3?.(config5);
if (metadata.title) {
db8.setDiagramTitle?.(metadata.title);
}
await parser26.parse(text4);
return new _Diagram(type3, text4, db8, parser26, renderer12);
}
async render(id32, version3) {
await this.renderer.draw(this.text, id32, version3, this);
}
getParser() {
return this.parser;
}
getType() {
return this.type;
}
};
// src/mermaidAPI.ts
init_common();
// src/interactionDb.ts
var interactionFunctions = [];
var attachFunctions = /* @__PURE__ */ __name(() => {
interactionFunctions.forEach((f2) => {
f2();
});
interactionFunctions = [];
}, "attachFunctions");
// src/mermaidAPI.ts
init_logger();
// src/diagram-api/comments.ts
var cleanupComments = /* @__PURE__ */ __name((text4) => {
return text4.replace(/^\s*%%(?!{)[^\n]+\n?/gm, "").trimStart();
}, "cleanupComments");
// src/diagram-api/frontmatter.ts
init_regexes();
init_js_yaml();
function extractFrontMatter(text4) {
const matches33 = text4.match(frontMatterRegex);
if (!matches33) {
return {
text: text4,
metadata: {}
};
}
let parsed = load(matches33[1], {
// To support config, we need JSON schema.
// https://www.yaml.org/spec/1.2/spec.html#id2803231
schema: JSON_SCHEMA
}) ?? {};
parsed = typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
const metadata = {};
if (parsed.displayMode) {
metadata.displayMode = parsed.displayMode.toString();
}
if (parsed.title) {
metadata.title = parsed.title.toString();
}
if (parsed.config) {
metadata.config = parsed.config;
}
return {
text: text4.slice(matches33[0].length),
metadata
};
}
__name(extractFrontMatter, "extractFrontMatter");
// src/preprocess.ts
init_utils2();
var cleanupText = /* @__PURE__ */ __name((code) => {
return code.replace(/\r\n?/g, "\n").replace(
/<(\w+)([^>]*)>/g,
(match2, tag, attributes) => "<" + tag + attributes.replace(/="([^"]*)"/g, "='$1'") + ">"
);
}, "cleanupText");
var processFrontmatter = /* @__PURE__ */ __name((code) => {
const { text: text4, metadata } = extractFrontMatter(code);
const { displayMode: displayMode2, title: title2, config: config5 = {} } = metadata;
if (displayMode2) {
if (!config5.gantt) {
config5.gantt = {};
}
config5.gantt.displayMode = displayMode2;
}
return { title: title2, config: config5, text: text4 };
}, "processFrontmatter");
var processDirectives = /* @__PURE__ */ __name((code) => {
const initDirective = utils_default2.detectInit(code) ?? {};
const wrapDirectives = utils_default2.detectDirective(code, "wrap");
if (Array.isArray(wrapDirectives)) {
initDirective.wrap = wrapDirectives.some(({ type: type3 }) => type3 === "wrap");
} else if (wrapDirectives?.type === "wrap") {
initDirective.wrap = true;
}
return {
text: removeDirectives(code),
directive: initDirective
};
}, "processDirectives");
function preprocessDiagram(code) {
const cleanedCode = cleanupText(code);
const frontMatterResult = processFrontmatter(cleanedCode);
const directiveResult = processDirectives(frontMatterResult.text);
const config5 = cleanAndMerge(frontMatterResult.config, directiveResult.directive);
code = cleanupComments(directiveResult.text);
return {
code,
title: frontMatterResult.title,
config: config5
};
}
__name(preprocessDiagram, "preprocessDiagram");
// src/mermaidAPI.ts
init_styles();
init_themes();
init_utils2();
// src/utils/base64.ts
function toBase64(str2) {
const utf8Bytes = new TextEncoder().encode(str2);
const utf8Str = Array.from(utf8Bytes, (byte) => String.fromCodePoint(byte)).join("");
return btoa(utf8Str);
}
__name(toBase64, "toBase64");
// src/mermaidAPI.ts
var MAX_TEXTLENGTH = 5e4;
var MAX_TEXTLENGTH_EXCEEDED_MSG = "graph TB;a[Maximum text size in diagram exceeded];style a fill:#faa";
var SECURITY_LVL_SANDBOX = "sandbox";
var SECURITY_LVL_LOOSE = "loose";
var XMLNS_SVG_STD = "http://www.w3.org/2000/svg";
var XMLNS_XLINK_STD = "http://www.w3.org/1999/xlink";
var XMLNS_XHTML_STD = "http://www.w3.org/1999/xhtml";
var IFRAME_WIDTH = "100%";
var IFRAME_HEIGHT = "100%";
var IFRAME_STYLES = "border:0;margin:0;";
var IFRAME_BODY_STYLE = "margin:0";
var IFRAME_SANDBOX_OPTS = "allow-top-navigation-by-user-activation allow-popups";
var IFRAME_NOT_SUPPORTED_MSG = 'The "iframe" tag is not supported by your browser.';
var DOMPURIFY_TAGS = ["foreignobject"];
var DOMPURIFY_ATTR = ["dominant-baseline"];
function processAndSetConfigs(text4) {
const processed2 = preprocessDiagram(text4);
reset();
addDirective(processed2.config ?? {});
return processed2;
}
__name(processAndSetConfigs, "processAndSetConfigs");
async function parse5(text4, parseOptions) {
addDiagrams();
try {
const { code, config: config5 } = processAndSetConfigs(text4);
const diagram29 = await getDiagramFromText(code);
return { diagramType: diagram29.type, config: config5 };
} catch (error3) {
if (parseOptions?.suppressErrors) {
return false;
}
throw error3;
}
}
__name(parse5, "parse");
var cssImportantStyles = /* @__PURE__ */ __name((cssClass, element3, cssClasses = []) => {
return `
.${cssClass} ${element3} { ${cssClasses.join(" !important; ")} !important; }`;
}, "cssImportantStyles");
var createCssStyles = /* @__PURE__ */ __name((config5, classDefs = /* @__PURE__ */ new Map()) => {
let cssStyles = "";
if (config5.themeCSS !== void 0) {
cssStyles += `
${config5.themeCSS}`;
}
if (config5.fontFamily !== void 0) {
cssStyles += `
:root { --mermaid-font-family: ${config5.fontFamily}}`;
}
if (config5.altFontFamily !== void 0) {
cssStyles += `
:root { --mermaid-alt-font-family: ${config5.altFontFamily}}`;
}
if (classDefs instanceof Map) {
const htmlLabels = getEffectiveHtmlLabels(config5);
const cssHtmlElements = ["> *", "span"];
const cssShapeElements = ["rect", "polygon", "ellipse", "circle", "path"];
const cssElements = htmlLabels ? cssHtmlElements : cssShapeElements;
classDefs.forEach((styleClassDef) => {
if (!isEmpty_default(styleClassDef.styles)) {
cssElements.forEach((cssElement) => {
cssStyles += cssImportantStyles(styleClassDef.id, cssElement, styleClassDef.styles);
});
}
if (!isEmpty_default(styleClassDef.textStyles)) {
cssStyles += cssImportantStyles(
styleClassDef.id,
"tspan",
(styleClassDef?.textStyles || []).map((s2) => s2.replace("color", "fill"))
);
}
});
}
return cssStyles;
}, "createCssStyles");
var createUserStyles = /* @__PURE__ */ __name((config5, graphType, classDefs, svgId) => {
const userCSSstyles = createCssStyles(config5, classDefs);
const allStyles = styles_default(graphType, userCSSstyles, config5.themeVariables);
return serialize(compile(`${svgId}{${allStyles}}`), stringify);
}, "createUserStyles");
var cleanUpSvgCode = /* @__PURE__ */ __name((svgCode = "", inSandboxMode, useArrowMarkerUrls) => {
let cleanedUpSvg = svgCode;
if (!useArrowMarkerUrls && !inSandboxMode) {
cleanedUpSvg = cleanedUpSvg.replace(
/marker-end="url\([\d+./:=?A-Za-z-]*?#/g,
'marker-end="url(#'
);
}
cleanedUpSvg = decodeEntities(cleanedUpSvg);
cleanedUpSvg = cleanedUpSvg.replace(/
/g, "
");
return cleanedUpSvg;
}, "cleanUpSvgCode");
var putIntoIFrame = /* @__PURE__ */ __name((svgCode = "", svgElement) => {
const height2 = svgElement?.viewBox?.baseVal?.height ? svgElement.viewBox.baseVal.height + "px" : IFRAME_HEIGHT;
const base64encodedSrc = toBase64(`