Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introducing TypeScript #3336

Merged
merged 38 commits into from
Sep 1, 2022
Merged
Show file tree
Hide file tree
Changes from 31 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
88e17bf
Typescript init
sidharthv96 Aug 20, 2022
95dbbb3
tsConversion: DetectType
sidharthv96 Aug 20, 2022
c9cd569
tsConversion: errorRenderer
sidharthv96 Aug 20, 2022
896154d
tsConversion: logger
sidharthv96 Aug 20, 2022
fab9688
tsConversion: flowchartStyles
sidharthv96 Aug 20, 2022
d9bace0
Add `trace` logLevel
sidharthv96 Aug 21, 2022
238cbd1
tsConversion: styles
sidharthv96 Aug 21, 2022
6de66ea
Add `trace` logLevel
sidharthv96 Aug 21, 2022
f14f0d9
tsConversion: config & common
sidharthv96 Aug 21, 2022
4710f67
fix: sanitization bug
sidharthv96 Aug 21, 2022
cd4b1ea
fix: codeScanning vuln
sidharthv96 Aug 21, 2022
c68ec54
tsConversion: mermaid main
sidharthv96 Aug 21, 2022
a51d8e8
Merge branch 'develop' into sidv/typescript
sidharthv96 Aug 21, 2022
d97b380
fix: startOnLoad
sidharthv96 Aug 21, 2022
39aaf2f
tsConversion: fix paths, add d.ts to output
sidharthv96 Aug 21, 2022
d365dac
tsConversion: mermaidAPI
sidharthv96 Aug 22, 2022
c245a2d
tsConversion: rename DiagramAPI
sidharthv96 Aug 22, 2022
1549eb2
tsConversion: fix DiagramAPI
sidharthv96 Aug 22, 2022
a2469b6
Merge branch 'develop' into sidv/typescript
sidharthv96 Aug 22, 2022
4885e7b
fix detectType
sidharthv96 Aug 22, 2022
9f49259
fix detectType
sidharthv96 Aug 22, 2022
6291e4d
fix detectType
sidharthv96 Aug 22, 2022
9a0d5e3
fix: review comments
sidharthv96 Aug 22, 2022
0e0802a
Update src/config.ts
knsv Aug 22, 2022
32ba2d5
Remove console.logs
sidharthv96 Aug 23, 2022
a8042f6
Merge branch 'sidv/typescript' of https://github.com/mermaid-js/merma…
sidharthv96 Aug 23, 2022
1efd5c7
Cleanup
sidharthv96 Aug 24, 2022
60651fd
Merge branch 'develop' into sidv/typescript
sidharthv96 Aug 24, 2022
84148d4
Remove failing test
sidharthv96 Aug 24, 2022
a3dfc4c
Remove `@ts-ignore`s.
sidharthv96 Aug 25, 2022
9b319a5
Merge branch 'develop' into sidv/typescript
sidharthv96 Aug 31, 2022
8c85c10
Fix TODO Qs
sidharthv96 Sep 1, 2022
4619ff2
Merge branch 'develop' into sidv/typescript
sidharthv96 Sep 1, 2022
36be811
Revert flowchart change
sidharthv96 Sep 1, 2022
4fa0d36
Revert flowchart change
sidharthv96 Sep 1, 2022
2272eb6
Fix repo URL
sidharthv96 Sep 1, 2022
e46d9c1
Merge branch 'develop' into sidv/typescript
sidharthv96 Sep 1, 2022
1ced01c
Typo fix
sidharthv96 Sep 1, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
demos/*.html
10 changes: 7 additions & 3 deletions .webpack/webpack.config.base.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import path from 'path';

export const resolveRoot = (...relativePath) => path.resolve(__dirname, '..', ...relativePath);

export default {
amd: false, // https://github.com/lodash/lodash/issues/3052
target: 'web',
entry: {
mermaid: './src/mermaid.js',
mermaid: './src/mermaid',
},
resolve: {
extensions: ['.wasm', '.mjs', '.js', '.json', '.jison'],
extensions: ['.wasm', '.mjs', '.js', '.ts', '.json', '.jison'],
fallback: {
fs: false, // jison generated code requires 'fs'
path: require.resolve('path-browserify'),
Expand All @@ -27,6 +26,11 @@ export default {
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.js$/,
include: [resolveRoot('./src'), resolveRoot('./node_modules/dagre-d3-renderer/lib')],
Expand Down
2 changes: 1 addition & 1 deletion .webpack/webpack.config.e2e.babel.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { merge } from 'webpack-merge';
export default merge(baseConfig, {
mode: 'development',
entry: {
mermaid: './src/mermaid.js',
mermaid: './src/mermaid',
e2e: './cypress/platform/viewer.js',
'bundle-test': './cypress/platform/bundle-test.js',
},
Expand Down
1,237 changes: 640 additions & 597 deletions CHANGELOG.md

Large diffs are not rendered by default.

86 changes: 41 additions & 45 deletions docs/Setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,13 @@ Theme , the CSS style sheet

## logLevel

| 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
Expand Down Expand Up @@ -1404,15 +1405,6 @@ This sets the auto-wrap padding for the diagram (sides only)

**Notes:** Default value: 0.

## parse

### Parameters

- `text`
- `dia`

Returns **any**

## setSiteConfig

## setSiteConfig
Expand All @@ -1428,7 +1420,7 @@ function _Default value: At default, will mirror Global Config_

### Parameters

- `conf` The base currentConfig to use as siteConfig
- `conf` **MermaidConfig** The base currentConfig to use as siteConfig

Returns **[object][5]** The siteConfig

Expand Down Expand Up @@ -1462,6 +1454,34 @@ corresponding siteConfig value.

Returns **any** The currentConfig merged with the sanitized conf

## render

Function that renders an svg with a graph from a chart definition. Usage example below.

```javascript
mermaidAPI.initialize({
startOnLoad: true,
});
$(function () {
const graphDefinition = 'graph TB\na-->b';
const cb = function (svgGraph) {
console.log(svgGraph);
};
mermaidAPI.render('id1', graphDefinition, cb);
});
```

### Parameters

- `id` **[string][6]** The id of the element to be rendered
- `text` **[string][6]** The graph definition
- `cb` **function (svgCode: [string][6], bindFunctions: function (element: [Element][7]): void): void**
- `container` **[Element][7]** Selector to element in which a div with the graph temporarily will be
inserted. If one is provided a hidden div will be inserted in the body of the page instead. The
element will be removed when rendering is completed.

Returns **void**

## getConfig

## getConfig
Expand Down Expand Up @@ -1489,34 +1509,6 @@ options in-place

- `options` **any** The potential setConfig parameter

## render

Function that renders an svg with a graph from a chart definition. Usage example below.

```javascript
mermaidAPI.initialize({
startOnLoad: true,
});
$(function () {
const graphDefinition = 'graph TB\na-->b';
const cb = function (svgGraph) {
console.log(svgGraph);
};
mermaidAPI.render('id1', graphDefinition, cb);
});
```

### Parameters

- `id` **any** The id of the element to be rendered
- `_txt` **any** The graph definition
- `cb` **any** Callback which is called after rendering is finished with the svg code as inparam.
- `container` **any** Selector to element in which a div with the graph temporarily will be
inserted. If one is provided a hidden div will be inserted in the body of the page instead. The
element will be removed when rendering is completed.

Returns **any**

## addDirective

Pushes in a directive to the configuration
Expand All @@ -1541,17 +1533,17 @@ Pushes in a directive to the configuration

**Notes**: (default: current siteConfig ) (optional, default `getSiteConfig()`)

## updateRendererConfigs

### Parameters

- `conf` **any**
- `config` (optional, default `siteConfig`)

Returns **void**

## initialize

### Parameters

- `options` **any**
- `options` **MermaidConfig**

##

Expand Down Expand Up @@ -1626,3 +1618,7 @@ Pushes in a directive to the configuration
[4]: #mermaidapi-configuration-defaults

[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object

[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

[7]: https://developer.mozilla.org/docs/Web/API/Element
4 changes: 3 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const path = require('path');

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
testEnvironment: 'jsdom',
preset: 'ts-jest',
transform: {
'^.+\\.jsx?$': ['babel-jest', { rootMode: 'upward' }],
'^.+\\.jison$': [
Expand All @@ -10,7 +12,7 @@ module.exports = {
],
},
transformIgnorePatterns: ['/node_modules/(?!dagre-d3-renderer/lib|khroma).*\\.js'],
testPathIgnorePatterns: ['/node_modules/', '.cache'],
testPathIgnorePatterns: ['/node_modules/', '.cache', './cypress'],
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy',
},
Expand Down
24 changes: 17 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"main": "dist/mermaid.min.js",
"module": "dist/mermaid.esm.min.mjs",
"types": "dist/mermaid.d.ts",
"exports": {
".": {
"require": "./dist/mermaid.min.js",
"import": "./dist/mermaid.esm.min.mjs"
"import": "./dist/mermaid.esm.min.mjs",
"types": "./dist/mermaid.d.ts"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wonder if this line isn't causing troubles, see #3747

},
"./*": "./*"
},
Expand All @@ -21,24 +23,25 @@
"git graph"
],
"scripts": {
"build:development": "webpack --mode development --progress --color",
"build:production": "webpack --mode production --progress --color",
"build": "concurrently \"yarn build:development\" \"yarn build:production\"",
"postbuild": "documentation build src/mermaidAPI.js src/config.js src/defaultConfig.js --shallow -f md --markdown-toc false > docs/Setup.md",
"build:watch": "yarn build:development --watch",
"build:dev": "webpack --mode development --progress --color",
"build:prod": "webpack --mode production --progress --color",
"build": "concurrently \"yarn build:dev\" \"yarn build:prod\"",
"postbuild": "documentation build src/mermaidAPI.ts src/config.ts src/defaultConfig.ts --shallow -f md --markdown-toc false > docs/Setup.md",
"build:watch": "yarn build:dev --watch",
"release": "yarn build",
"lint": "eslint --cache ./ --ext .js,.json,.html,.md",
"lint:fix": "yarn lint --fix",
"e2e:depr": "yarn lint && jest e2e --config e2e/jest.config.js",
"cypress": "cypress run",
"cypress:open": "cypress open",
"e2e": "start-server-and-test dev http://localhost:9000/ cypress",
"e2e-upd": "yarn lint && jest e2e -u --config e2e/jest.config.js",
"dev": "webpack serve --config ./.webpack/webpack.config.e2e.babel.js",
"ci": "jest src/.*",
"test": "yarn lint && jest src/.*",
"test:watch": "jest --watch src",
"prepublishOnly": "yarn build && yarn test",
"prepare": "husky install && yarn build",
"prepare": "husky install",
"pre-commit": "lint-staged"
},
"repository": {
Expand Down Expand Up @@ -76,6 +79,10 @@
"@babel/register": "^7.14.5",
"@commitlint/cli": "^17.0.0",
"@commitlint/config-conventional": "^17.0.0",
"@types/d3": "^7.4.0",
"@types/dompurify": "^2.3.3",
"@types/jest": "^28.1.7",
"@types/stylis": "^4.0.2",
"babel-jest": "^29.0.1",
"babel-loader": "^8.2.2",
"concurrently": "^7.0.0",
Expand Down Expand Up @@ -106,6 +113,9 @@
"prettier-plugin-jsdoc": "^0.3.30",
"start-server-and-test": "^1.12.6",
"terser-webpack-plugin": "^5.2.4",
"ts-jest": "^28.0.8",
"ts-loader": "^9.3.1",
"typescript": "^4.7.4",
"webpack": "^5.53.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^4.3.0",
Expand Down
51 changes: 24 additions & 27 deletions src/Diagram.js → src/Diagram.ts
Original file line number Diff line number Diff line change
@@ -1,71 +1,68 @@
import utils from './utils';
import * as configApi from './config';
import { log } from './logger';
import { getDiagrams } from './diagram-api/diagramAPI';
import detectType from './diagram-api/detectType';
class Diagram {
import { getDiagram } from './diagram-api/diagramAPI';
import { detectType } from './diagram-api/detectType';
import { isDetailedError } from './utils';
export class Diagram {
type = 'graph';
parser;
renderer;
db;
constructor(txt) {
const diagrams = getDiagrams();
constructor(public txt: string, parseError?: Function) {
const cnf = configApi.getConfig();
this.txt = txt;
this.type = detectType(txt, cnf);
const diagram = getDiagram(this.type);
log.debug('Type ' + this.type);

// console.log('this.type', this.type, diagrams[this.type]);
// Setup diagram
this.db = diagrams[this.type].db;
this.db = diagram.db;
this.db.clear?.();

this.renderer = diagrams[this.type].renderer;
this.parser = diagrams[this.type].parser;
this.renderer = diagram.renderer;
this.parser = diagram.parser;
this.parser.parser.yy = this.db;
if (typeof diagrams[this.type].init === 'function') {
diagrams[this.type].init(cnf);
if (diagram.init) {
diagram.init(cnf);
log.debug('Initialized diagram ' + this.type, cnf);
}
this.txt = this.txt + '\n';

this.txt += '\n';
this.parser.parser.yy.graphType = this.type;
this.parser.parser.yy.parseError = (str, hash) => {
this.parser.parser.yy.parseError = (str: string, hash: string) => {
const error = { str, hash };
throw error;
};
this.parser.parse(this.txt);
this.parse(this.txt, parseError);
}
parse(text) {
var parseEncounteredException = false;

parse(text: string, parseError?: Function): boolean {
try {
text = text + '\n';
this.db.clear();

this.parser.parse(text);
return true;
} catch (error) {
parseEncounteredException = true;
// Is this the correct way to access mermiad's parseError()
// method ? (or global.mermaid.parseError()) ?
if (global.mermaid.parseError) {
if (error.str != undefined) {
if (parseError) {
if (isDetailedError(error)) {
// handle case where error string and hash were
// wrapped in object like`const error = { str, hash };`
global.mermaid.parseError(error.str, error.hash);
parseError(error.str, error.hash);
} else {
// assume it is just error string and pass it on
global.mermaid.parseError(error);
parseError(error);
}
} else {
// No mermaid.parseError() handler defined, so re-throw it
throw error;
}
}
return !parseEncounteredException;
return false;
}

getParser() {
return this.parser;
}

getType() {
return this.type;
}
Expand Down
Loading