tsConversion: config & common

This commit is contained in:
Sidharth Vinod
2022-08-21 11:00:22 +05:30
parent 6de66eaba3
commit f14f0d9857
14 changed files with 605 additions and 109 deletions

342
src/@types/config.d.ts vendored Normal file
View File

@@ -0,0 +1,342 @@
// TODO: This was auto generated from defaultConfig. Needs to be verified.
import DOMPurify from 'dompurify';
export interface MermaidConfig {
theme?: string;
themeVariables?: any;
themeCSS?: string;
maxTextSize?: number;
darkMode?: boolean;
fontFamily?: string;
logLevel?: number;
securityLevel?: string;
startOnLoad?: boolean;
arrowMarkerAbsolute?: boolean;
secure?: string[];
deterministicIds?: boolean;
deterministicIDSeed?: string;
flowchart?: FlowchartDiagramConfig;
sequence?: SequenceDiagramConfig;
gantt?: GanttDiagramConfig;
journey?: JourneyDiagramConfig;
class?: ClassDiagramConfig;
state?: StateDiagramConfig;
er?: ErDiagramConfig;
pie?: PieDiagramConfig;
requirement?: RequirementDiagramConfig;
gitGraph?: GitGraphDiagramConfig;
c4?: C4DiagramConfig;
dompurifyConfig?: DOMPurify.Config;
}
// TODO: More configs needs to be moved in here
export interface BaseDiagramConfig extends BaseDiagramConfig {
useWidth?: number;
useMaxWidth?: boolean;
}
export interface C4DiagramConfig extends BaseDiagramConfig {
diagramMarginX?: number;
diagramMarginY?: number;
c4ShapeMargin?: number;
c4ShapePadding?: number;
width?: number;
height?: number;
boxMargin?: number;
c4ShapeInRow?: number;
nextLinePaddingX?: number;
c4BoundaryInRow?: number;
personFontSize?: string | number;
personFontFamily?: string;
personFontWeight?: string | number;
external_personFontSize?: string | number;
external_personFontFamily?: string;
external_personFontWeight?: string | number;
systemFontSize?: string | number;
systemFontFamily?: string;
systemFontWeight?: string | number;
external_systemFontSize?: string | number;
external_systemFontFamily?: string;
external_systemFontWeight?: string | number;
system_dbFontSize?: string | number;
system_dbFontFamily?: string;
system_dbFontWeight?: string | number;
external_system_dbFontSize?: string | number;
external_system_dbFontFamily?: string;
external_system_dbFontWeight?: string | number;
system_queueFontSize?: string | number;
system_queueFontFamily?: string;
system_queueFontWeight?: string | number;
external_system_queueFontSize?: string | number;
external_system_queueFontFamily?: string;
external_system_queueFontWeight?: string | number;
boundaryFontSize?: string | number;
boundaryFontFamily?: string;
boundaryFontWeight?: string | number;
messageFontSize?: string | number;
messageFontFamily?: string;
messageFontWeight?: string | number;
containerFontSize?: string | number;
containerFontFamily?: string;
containerFontWeight?: string | number;
external_containerFontSize?: string | number;
external_containerFontFamily?: string;
external_containerFontWeight?: string | number;
container_dbFontSize?: string | number;
container_dbFontFamily?: string;
container_dbFontWeight?: string | number;
external_container_dbFontSize?: string | number;
external_container_dbFontFamily?: string;
external_container_dbFontWeight?: string | number;
container_queueFontSize?: string | number;
container_queueFontFamily?: string;
container_queueFontWeight?: string | number;
external_container_queueFontSize?: string | number;
external_container_queueFontFamily?: string;
external_container_queueFontWeight?: string | number;
componentFontSize?: string | number;
componentFontFamily?: string;
componentFontWeight?: string | number;
external_componentFontSize?: string | number;
external_componentFontFamily?: string;
external_componentFontWeight?: string | number;
component_dbFontSize?: string | number;
component_dbFontFamily?: string;
component_dbFontWeight?: string | number;
external_component_dbFontSize?: string | number;
external_component_dbFontFamily?: string;
external_component_dbFontWeight?: string | number;
component_queueFontSize?: string | number;
component_queueFontFamily?: string;
component_queueFontWeight?: string | number;
external_component_queueFontSize?: string | number;
external_component_queueFontFamily?: string;
external_component_queueFontWeight?: string | number;
wrap?: boolean;
wrapPadding?: number;
person_bg_color?: string;
person_border_color?: string;
external_person_bg_color?: string;
external_person_border_color?: string;
system_bg_color?: string;
system_border_color?: string;
system_db_bg_color?: string;
system_db_border_color?: string;
system_queue_bg_color?: string;
system_queue_border_color?: string;
external_system_bg_color?: string;
external_system_border_color?: string;
external_system_db_bg_color?: string;
external_system_db_border_color?: string;
external_system_queue_bg_color?: string;
external_system_queue_border_color?: string;
container_bg_color?: string;
container_border_color?: string;
container_db_bg_color?: string;
container_db_border_color?: string;
container_queue_bg_color?: string;
container_queue_border_color?: string;
external_container_bg_color?: string;
external_container_border_color?: string;
external_container_db_bg_color?: string;
external_container_db_border_color?: string;
external_container_queue_bg_color?: string;
external_container_queue_border_color?: string;
component_bg_color?: string;
component_border_color?: string;
component_db_bg_color?: string;
component_db_border_color?: string;
component_queue_bg_color?: string;
component_queue_border_color?: string;
external_component_bg_color?: string;
external_component_border_color?: string;
external_component_db_bg_color?: string;
external_component_db_border_color?: string;
external_component_queue_bg_color?: string;
external_component_queue_border_color?: string;
personFont?: FontCalculator;
external_personFont?: FontCalculator;
systemFont?: FontCalculator;
external_systemFont?: FontCalculator;
system_dbFont?: FontCalculator;
external_system_dbFont?: FontCalculator;
system_queueFont?: FontCalculator;
external_system_queueFont?: FontCalculator;
containerFont?: FontCalculator;
external_containerFont?: FontCalculator;
container_dbFont?: FontCalculator;
external_container_dbFont?: FontCalculator;
container_queueFont?: FontCalculator;
external_container_queueFont?: FontCalculator;
componentFont?: FontCalculator;
external_componentFont?: FontCalculator;
component_dbFont?: FontCalculator;
external_component_dbFont?: FontCalculator;
component_queueFont?: FontCalculator;
external_component_queueFont?: FontCalculator;
boundaryFont?: FontCalculator;
messageFont?: FontCalculator;
}
export interface GitGraphDiagramConfig extends BaseDiagramConfig {
diagramPadding?: number;
nodeLabel?: NodeLabel;
mainBranchName?: string;
mainBranchOrder?: number;
showCommitLabel?: boolean;
showBranches?: boolean;
rotateCommitLabel?: boolean;
arrowMarkerAbsolute?: boolean;
}
export interface NodeLabel {
width?: number;
height?: number;
x?: number;
y?: number;
}
export interface RequirementDiagramConfig extends BaseDiagramConfig {
rect_fill?: string;
text_color?: string;
rect_border_size?: string;
rect_border_color?: string;
rect_min_width?: number;
rect_min_height?: number;
fontSize?: number;
rect_padding?: number;
line_height?: number;
}
export interface PieDiagramConfig extends BaseDiagramConfig {}
export interface ErDiagramConfig extends BaseDiagramConfig {
diagramPadding?: number;
layoutDirection?: string;
minEntityWidth?: number;
minEntityHeight?: number;
entityPadding?: number;
stroke?: string;
fill?: string;
fontSize?: number;
}
export interface StateDiagramConfig extends BaseDiagramConfig {
dividerMargin?: number;
sizeUnit?: number;
padding?: number;
textHeight?: number;
titleShift?: number;
noteMargin?: number;
forkWidth?: number;
forkHeight?: number;
miniPadding?: number;
fontSizeFactor?: number;
fontSize?: number;
labelHeight?: number;
edgeLengthFactor?: string;
compositTitleSize?: number;
radius?: number;
defaultRenderer?: string;
}
export interface ClassDiagramConfig extends BaseDiagramConfig {
arrowMarkerAbsolute?: boolean;
dividerMargin?: number;
padding?: number;
textHeight?: number;
defaultRenderer?: string;
}
export interface JourneyDiagramConfig extends BaseDiagramConfig {
diagramMarginX?: number;
diagramMarginY?: number;
leftMargin?: number;
width?: number;
height?: number;
boxMargin?: number;
boxTextMargin?: number;
noteMargin?: number;
messageMargin?: number;
messageAlign?: string;
bottomMarginAdj?: number;
rightAngles?: boolean;
taskFontSize?: string | number;
taskFontFamily?: string;
taskMargin?: number;
activationWidth?: number;
textPlacement?: string;
actorColours?: string[];
sectionFills?: string[];
sectionColours?: string[];
}
export interface GanttDiagramConfig extends BaseDiagramConfig {
titleTopMargin?: number;
barHeight?: number;
barGap?: number;
topPadding?: number;
rightPadding?: number;
leftPadding?: number;
gridLineStartPadding?: number;
fontSize?: number;
sectionFontSize?: string | number;
numberSectionStyles?: number;
axisFormat?: string;
topAxis?: boolean;
}
export interface SequenceDiagramConfig extends BaseDiagramConfig {
hideUnusedParticipants?: boolean;
activationWidth?: number;
diagramMarginX?: number;
diagramMarginY?: number;
actorMargin?: number;
width?: number;
height?: number;
boxMargin?: number;
boxTextMargin?: number;
noteMargin?: number;
messageMargin?: number;
messageAlign?: string;
mirrorActors?: boolean;
forceMenus?: boolean;
bottomMarginAdj?: number;
rightAngles?: boolean;
showSequenceNumbers?: boolean;
actorFontSize?: string | number;
actorFontFamily?: string;
actorFontWeight?: string | number;
noteFontSize?: string | number;
noteFontFamily?: string;
noteFontWeight?: string | number;
noteAlign?: string;
messageFontSize?: string | number;
messageFontFamily?: string;
messageFontWeight?: string | number;
wrap?: boolean;
wrapPadding?: number;
labelBoxWidth?: number;
labelBoxHeight?: number;
messageFont?: FontCalculator;
noteFont?: FontCalculator;
actorFont?: FontCalculator;
}
export interface FlowchartDiagramConfig extends BaseDiagramConfig {
diagramPadding?: number;
htmlLabels?: boolean;
nodeSpacing?: number;
rankSpacing?: number;
curve?: string;
padding?: number;
defaultRenderer?: string;
}
export interface FontConfig {
fontSize?: string | number;
fontFamily?: string;
fontWeight?: string | number;
}
export type FontCalculator = () => Partial<FontConfig>;

1
src/@types/types.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
type DiagramDetector = (text: string) => boolean;

View File

@@ -3,35 +3,35 @@ import { getConfig } from './config';
let title = '';
let diagramTitle = '';
let description = '';
const sanitizeText = (txt) => _sanitizeText(txt, getConfig());
const sanitizeText = (txt: string): string => _sanitizeText(txt, getConfig());
export const clear = function () {
export const clear = function (): void {
title = '';
description = '';
diagramTitle = '';
};
export const setAccTitle = function (txt) {
export const setAccTitle = function (txt: string): void {
title = sanitizeText(txt).replace(/^\s+/g, '');
};
export const getAccTitle = function () {
export const getAccTitle = function (): string {
return title || diagramTitle;
};
export const setAccDescription = function (txt) {
export const setAccDescription = function (txt: string): void {
description = sanitizeText(txt).replace(/\n\s+/g, '\n');
};
export const getAccDescription = function () {
export const getAccDescription = function (): string {
return description;
};
export const setDiagramTitle = function (txt) {
export const setDiagramTitle = function (txt: string): void {
diagramTitle = sanitizeText(txt);
};
export const getDiagramTitle = function () {
export const getDiagramTitle = function (): string {
return diagramTitle;
};

View File

@@ -1,4 +1,5 @@
import theme from './themes';
import { MermaidConfig } from 'types/config';
/**
* **Configuration methods in Mermaid version 8.6.0 have been updated, to learn more[[click
* here](8.6.0_docs.md)].**
@@ -21,7 +22,7 @@ import theme from './themes';
*
* @name Configuration
*/
const config = {
const config: Partial<MermaidConfig> = {
/**
* Theme , the CSS style sheet
*
@@ -49,12 +50,13 @@ const config = {
fontFamily: '"trebuchet ms", verdana, arial, sans-serif;',
/**
* | Parameter | Description | Type | Required | Values |
* | --------- | ----------------------------------------------------- | ---------------- | -------- | ------------- |
* | logLevel | This option decides the amount of logging to be used. | string \| number | Required | 1, 2, 3, 4, 5 |
* | Parameter | Description | Type | Required | Values |
* | --------- | ----------------------------------------------------- | ---------------- | -------- | --------------------------------------------- |
* | logLevel | This option decides the amount of logging to be used. | string \| number | Required | 'trace','debug','info','warn','error','fatal' |
*
* **Notes:**
*
* - Trace: 0
* - Debug: 1
* - Info: 2
* - Warn: 3
@@ -1820,11 +1822,12 @@ const config = {
},
};
config.class.arrowMarkerAbsolute = config.arrowMarkerAbsolute;
config.gitGraph.arrowMarkerAbsolute = config.arrowMarkerAbsolute;
console.log(JSON.stringify(config));
if (config.class) config.class.arrowMarkerAbsolute = config.arrowMarkerAbsolute;
if (config.gitGraph) config.gitGraph.arrowMarkerAbsolute = config.arrowMarkerAbsolute;
const keyify = (obj, prefix = '') =>
Object.keys(obj).reduce((res, el) => {
const keyify = (obj: any, prefix = ''): string[] =>
Object.keys(obj).reduce((res: string[], el): string[] => {
if (Array.isArray(obj[el])) {
return res;
} else if (typeof obj[el] === 'object' && obj[el] !== null) {
@@ -1833,5 +1836,5 @@ const keyify = (obj, prefix = '') =>
return [...res, prefix + el];
}, []);
export const configKeys = keyify(config, '');
export const configKeys: string[] = keyify(config, '');
export default config;

View File

@@ -1,3 +1,5 @@
import type { MermaidConfig } from 'types/config';
const directive =
/[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi;
const anyComment = /\s*%%.*\n/gm;
@@ -41,7 +43,7 @@ const diagramMatchers: Record<string, RegExp> = {
* }} [cnf]
* @returns {string} A graph definition key
*/
export const detectType = function (text: string, cnf: ConfigType): string {
export const detectType = function (text: string, cnf: MermaidConfig): string {
text = text.replace(directive, '').replace(anyComment, '\n');
for (const [diagram, matcher] of Object.entries(diagramMatchers)) {
if (text.match(matcher)) {

View File

@@ -1,19 +1,19 @@
import DOMPurify from 'dompurify';
import { MermaidConfig } from 'types/config';
/**
* Gets the number of lines in a string
* Gets the rows of lines in a string
*
* @param {string | undefined} s The string to check the lines for
* @returns {number} The number of lines in that string
* @returns {string[]} The rows in that string
*/
export const getRows = (s) => {
if (!s) return 1;
let str = breakToPlaceholder(s);
str = str.replace(/\\n/g, '#br#');
export const getRows = (s?: string): string[] => {
if (!s) return [''];
const str = breakToPlaceholder(s).replace(/\\n/g, '#br#');
return str.split('#br#');
};
export const removeEscapes = (text) => {
export const removeEscapes = (text: string): string => {
let newStr = text.replace(/\\u[\dA-F]{4}/gi, function (match) {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
});
@@ -35,7 +35,7 @@ export const removeEscapes = (text) => {
* @param {string} txt The text to sanitize
* @returns {string} The safer text
*/
export const removeScript = (txt) => {
export const removeScript = (txt: string): string => {
var rs = '';
var idx = 0;
@@ -65,49 +65,39 @@ export const removeScript = (txt) => {
return decodedText;
};
const sanitizeMore = (text, config) => {
let txt = text;
let htmlLabels = true;
if (
config.flowchart &&
(config.flowchart.htmlLabels === false || config.flowchart.htmlLabels === 'false')
) {
htmlLabels = false;
}
if (htmlLabels) {
const sanitizeMore = (text: string, config: MermaidConfig) => {
// TODO Q: Should this check really be here? Feels like we should be sanitizing it regardless.
if (config.flowchart?.htmlLabels !== false) {
const level = config.securityLevel;
if (level === 'antiscript' || level === 'strict') {
txt = removeScript(txt);
text = removeScript(text);
} else if (level !== 'loose') {
// eslint-disable-line
txt = breakToPlaceholder(txt);
txt = txt.replace(/</g, '&lt;').replace(/>/g, '&gt;');
txt = txt.replace(/=/g, '&equals;');
txt = placeholderToBreak(txt);
text = breakToPlaceholder(text);
text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
text = text.replace(/=/g, '&equals;');
text = placeholderToBreak(text);
}
}
return txt;
return text;
};
export const sanitizeText = (text, config) => {
export const sanitizeText = (text: string, config: MermaidConfig): string => {
if (!text) return text;
let txt = '';
if (config['dompurifyConfig']) {
txt = DOMPurify.sanitize(sanitizeMore(text, config), config['dompurifyConfig']);
if (config.dompurifyConfig) {
text = DOMPurify.sanitize(sanitizeMore(text, config), config.dompurifyConfig).toString();
} else {
txt = DOMPurify.sanitize(sanitizeMore(text, config));
text = DOMPurify.sanitize(sanitizeMore(text, config));
}
return txt;
return text;
};
export const sanitizeTextOrArray = (a, config) => {
export const sanitizeTextOrArray = (
a: string | string[] | string[][],
config: MermaidConfig
): string | string[] => {
if (typeof a === 'string') return sanitizeText(a, config);
const f = (x) => sanitizeText(x, config);
return a.flat().map(f);
// TODO Q: Do we need flat?
return a.flat().map((x: string) => sanitizeText(x, config));
};
export const lineBreakRegex = /<br\s*\/?>/gi;
@@ -118,7 +108,7 @@ export const lineBreakRegex = /<br\s*\/?>/gi;
* @param {string} text The text to test
* @returns {boolean} Whether or not the text has breaks
*/
export const hasBreaks = (text) => {
export const hasBreaks = (text: string): boolean => {
return lineBreakRegex.test(text);
};
@@ -128,7 +118,7 @@ export const hasBreaks = (text) => {
* @param {string} text Text to split
* @returns {string[]} List of lines as strings
*/
export const splitBreaks = (text) => {
export const splitBreaks = (text: string): string[] => {
return text.split(lineBreakRegex);
};
@@ -138,7 +128,7 @@ export const splitBreaks = (text) => {
* @param {string} s HTML with placeholders
* @returns {string} HTML with breaks instead of placeholders
*/
const placeholderToBreak = (s) => {
const placeholderToBreak = (s: string): string => {
return s.replace(/#br#/g, '<br/>');
};
@@ -148,7 +138,7 @@ const placeholderToBreak = (s) => {
* @param {string} s HTML string
* @returns {string} String with placeholders
*/
const breakToPlaceholder = (s) => {
const breakToPlaceholder = (s: string): string => {
return s.replace(lineBreakRegex, '#br#');
};
@@ -158,8 +148,9 @@ const breakToPlaceholder = (s) => {
* @param {boolean} useAbsolute Whether to return the absolute URL or not
* @returns {string} The current URL
*/
const getUrl = (useAbsolute) => {
const getUrl = (useAbsolute: boolean): string => {
let url = '';
// TODO Q: If useAbsolute if false, empty string is returned. Bug?
if (useAbsolute) {
url =
window.location.protocol +
@@ -180,7 +171,9 @@ const getUrl = (useAbsolute) => {
* @param {string | boolean} val String or boolean to convert
* @returns {boolean} The result from the input
*/
export const evaluate = (val) => (val === 'false' || val === false ? false : true);
// TODO Q: Should we make this check more specific? 'False', '0', 'null' all will evaluate to true.
export const evaluate = (val: string | boolean): boolean =>
val === 'false' || val === false ? false : true;
export default {
getRows,

View File

@@ -1,3 +1,5 @@
// TODO: Remove
// @ts-nocheck
/**
* Web page integration module for the mermaid framework. It uses the mermaidAPI for mermaid
* functionality and to render the diagrams to svg code.
@@ -29,9 +31,9 @@ import utils from './utils';
*
* Renders the mermaid diagrams
*/
const init = function () {
const init = function (config: any, ...nodes: any[]) {
try {
initThrowsErrors(...arguments);
initThrowsErrors(config, nodes);
} catch (e) {
log.warn('Syntax Error rendering');
log.warn(e.str);
@@ -41,25 +43,17 @@ const init = function () {
}
};
const initThrowsErrors = function () {
const initThrowsErrors = function (config: any, nodes: any[]) {
const conf = mermaidAPI.getConfig();
// console.log('Starting rendering diagrams (init) - mermaid.init', conf);
let nodes;
if (arguments.length >= 2) {
/*! sequence config was passed as #1 */
if (typeof arguments[0] !== 'undefined') {
mermaid.sequenceConfig = arguments[0];
}
nodes = arguments[1];
} else {
nodes = arguments[0];
if (config) {
mermaid.sequenceConfig = config;
}
// if last argument is a function this is the callback function
let callback;
if (typeof arguments[arguments.length - 1] === 'function') {
callback = arguments[arguments.length - 1];
let callback: (id: string) => void;
if (typeof nodes[nodes.length - 1] === 'function') {
callback = nodes[nodes.length - 1];
log.debug('Callback function found');
} else {
if (typeof conf.mermaid !== 'undefined') {
@@ -140,7 +134,7 @@ const initThrowsErrors = function () {
}
};
const initialize = function (config) {
const initialize = function (config: any) {
// mermaidAPI.reset();
if (typeof config.mermaid !== 'undefined') {
if (typeof config.mermaid.startOnLoad !== 'undefined') {

7
src/types.d.ts vendored
View File

@@ -1,7 +0,0 @@
interface ConfigType {
class?: { defaultRenderer: string };
state?: { defaultRenderer: string };
flowchart?: { defaultRenderer: string };
}
type DiagramDetector = (text: string) => boolean;

View File

@@ -814,6 +814,7 @@ export const setupGraphViewbox = function (graph, svgElem, padding, useMaxWidth)
export const initIdGenerator = class iterator {
constructor(deterministic, seed) {
this.deterministic = deterministic;
// TODO: Seed is only used for length?
this.seed = seed;
this.count = seed ? seed.length : 0;