Refactor code

This commit is contained in:
Tyler Long
2017-04-16 23:24:47 +08:00
parent 110e4ee586
commit 87c7f73245
6 changed files with 124 additions and 159 deletions

View File

@@ -4,7 +4,6 @@
*/ */
var Logger = require('./logger') var Logger = require('./logger')
// Logger.setLogLevel(1)
var log = Logger.Log var log = Logger.Log
var mermaidAPI = require('./mermaidAPI') var mermaidAPI = require('./mermaidAPI')
var nextId = 0 var nextId = 0

View File

@@ -36,11 +36,6 @@ var gitGraphRenderer = require('./diagrams/gitGraph/gitGraphRenderer')
var gitGraphAst = require('./diagrams/gitGraph/gitGraphAst') var gitGraphAst = require('./diagrams/gitGraph/gitGraphAst')
var d3 = require('./d3') var d3 = require('./d3')
// https://github.com/cpettitt/dagre-d3/issues/202
// window.SVGElement.prototype.getTransformToElement = window.SVGElement.prototype.getTransformToElement || function (toElement) {
// return toElement.getScreenCTM().inverse().multiply(this.getScreenCTM())
// }
/** /**
* ## Configuration * ## Configuration
* These are the default options which can be overridden with the initialization call as in the example below: * These are the default options which can be overridden with the initialization call as in the example below:
@@ -53,62 +48,62 @@ var d3 = require('./d3')
* ``` * ```
*/ */
var config = { var config = {
/** /**
* logLevel , decides the amount of logging to be used. * logLevel , decides the amount of logging to be used.
* * debug: 1 * * debug: 1
* * info: 2 * * info: 2
* * warn: 3 * * warn: 3
* * error: 4 * * error: 4
* * fatal: 5 * * fatal: 5
*/ */
logLevel: 5, logLevel: 5,
/** /**
* **cloneCssStyles** - This options controls whether or not the css rules should be copied into the generated svg * **cloneCssStyles** - This options controls whether or not the css rules should be copied into the generated svg
*/ */
cloneCssStyles: true, cloneCssStyles: true,
/** /**
* **startOnLoad** - This options controls whether or mermaid starts when the page loads * **startOnLoad** - This options controls whether or mermaid starts when the page loads
*/ */
startOnLoad: true, startOnLoad: true,
/** /**
* **arrowMarkerAbsolute** - This options controls whether or arrow markers in html code will be absolute paths or * **arrowMarkerAbsolute** - This options controls whether or arrow markers in html code will be absolute paths or
* an anchor, #. This matters if you are using base tag settings. * an anchor, #. This matters if you are using base tag settings.
*/ */
arrowMarkerAbsolute: false, arrowMarkerAbsolute: false,
/** /**
* ### flowchart * ### flowchart
* *The object containing configurations specific for flowcharts* * *The object containing configurations specific for flowcharts*
*/ */
flowchart: { flowchart: {
/** /**
* **htmlLabels** - Flag for setting whether or not a html tag should be used for rendering labels * **htmlLabels** - Flag for setting whether or not a html tag should be used for rendering labels
* on the edges * on the edges
*/ */
htmlLabels: true, htmlLabels: true,
/** /**
* **useMaxWidth** - Flag for setting whether or not a all available width should be used for * **useMaxWidth** - Flag for setting whether or not a all available width should be used for
* the diagram. * the diagram.
*/ */
useMaxWidth: true useMaxWidth: true
}, },
/** /**
* ### sequenceDiagram * ### sequenceDiagram
* The object containing configurations specific for sequence diagrams * The object containing configurations specific for sequence diagrams
*/ */
sequenceDiagram: { sequenceDiagram: {
/** /**
* **diagramMarginX** - margin to the right and left of the sequence diagram * **diagramMarginX** - margin to the right and left of the sequence diagram
*/ */
diagramMarginX: 50, diagramMarginX: 50,
/** /**
* **diagramMarginY** - margin to the over and under the sequence diagram * **diagramMarginY** - margin to the over and under the sequence diagram
*/ */
diagramMarginY: 10, diagramMarginY: 10,
/** /**
@@ -131,19 +126,19 @@ var config = {
*/ */
boxMargin: 10, boxMargin: 10,
/** /**
* **boxTextMargin** - margin around the text in loop/alt/opt boxes * **boxTextMargin** - margin around the text in loop/alt/opt boxes
*/ */
boxTextMargin: 5, boxTextMargin: 5,
/** /**
* **noteMargin** - margin around notes * **noteMargin** - margin around notes
*/ */
noteMargin: 10, noteMargin: 10,
/** /**
* **messageMargin** - Space between messages * **messageMargin** - Space between messages
*/ */
messageMargin: 35, messageMargin: 35,
/** /**
@@ -164,77 +159,77 @@ var config = {
useMaxWidth: true useMaxWidth: true
}, },
/** ### gantt /** ### gantt
* The object containing configurations specific for gantt diagrams* * The object containing configurations specific for gantt diagrams*
*/ */
gantt: { gantt: {
/** /**
* **titleTopMargin** - margin top for the text over the gantt diagram * **titleTopMargin** - margin top for the text over the gantt diagram
*/ */
titleTopMargin: 25, titleTopMargin: 25,
/** /**
* **barHeight** - the height of the bars in the graph * **barHeight** - the height of the bars in the graph
*/ */
barHeight: 20, barHeight: 20,
/** /**
* **barGap** - the margin between the different activities in the gantt diagram * **barGap** - the margin between the different activities in the gantt diagram
*/ */
barGap: 4, barGap: 4,
/** /**
* **topPadding** - margin between title and gantt diagram and between axis and gantt diagram. * **topPadding** - margin between title and gantt diagram and between axis and gantt diagram.
*/ */
topPadding: 50, topPadding: 50,
/** /**
* **leftPadding** - the space allocated for the section name to the left of the activities. * **leftPadding** - the space allocated for the section name to the left of the activities.
*/ */
leftPadding: 75, leftPadding: 75,
/** /**
* **gridLineStartPadding** - Vertical starting position of the grid lines * **gridLineStartPadding** - Vertical starting position of the grid lines
*/ */
gridLineStartPadding: 35, gridLineStartPadding: 35,
/** /**
* **fontSize** - font size ... * **fontSize** - font size ...
*/ */
fontSize: 11, fontSize: 11,
/** /**
* **fontFamily** - font family ... * **fontFamily** - font family ...
*/ */
fontFamily: '"Open-Sans", "sans-serif"', fontFamily: '"Open-Sans", "sans-serif"',
/** /**
* **numberSectionStyles** - the number of alternating section styles * **numberSectionStyles** - the number of alternating section styles
*/ */
numberSectionStyles: 3, numberSectionStyles: 3,
/** /**
* **axisFormatter** - formatting of the axis, this might need adjustment to match your locale and preferences * **axisFormatter** - formatting of the axis, this might need adjustment to match your locale and preferences
*/ */
axisFormatter: [ axisFormatter: [
// Within a day // Within a day
['%I:%M', function (d) { ['%I:%M', function (d) {
return d.getHours() return d.getHours()
}], }],
// Monday a week // Monday a week
['w. %U', function (d) { ['w. %U', function (d) {
return d.getDay() === 1 return d.getDay() === 1
}], }],
// Day within a week (not monday) // Day within a week (not monday)
['%a %d', function (d) { ['%a %d', function (d) {
return d.getDay() && d.getDate() !== 1 return d.getDay() && d.getDate() !== 1
}], }],
// within a month // within a month
['%b %d', function (d) { ['%b %d', function (d) {
return d.getDate() !== 1 return d.getDate() !== 1
}], }],
// Month // Month
['%m-%y', function (d) { ['%m-%y', function (d) {
return d.getMonth() return d.getMonth()
}] }]
@@ -375,12 +370,12 @@ var render = function (id, txt, cb, container) {
container.innerHTML = '' container.innerHTML = ''
d3.select(container).append('div') d3.select(container).append('div')
.attr('id', 'd' + id) .attr('id', 'd' + id)
.append('svg') .append('svg')
.attr('id', id) .attr('id', id)
.attr('width', '100%') .attr('width', '100%')
.attr('xmlns', 'http://www.w3.org/2000/svg') .attr('xmlns', 'http://www.w3.org/2000/svg')
.append('g') .append('g')
} else { } else {
const element = document.querySelector('#' + 'd' + id) const element = document.querySelector('#' + 'd' + id)
if (element) { if (element) {
@@ -388,18 +383,16 @@ var render = function (id, txt, cb, container) {
} }
d3.select('body').append('div') d3.select('body').append('div')
.attr('id', 'd' + id) .attr('id', 'd' + id)
.append('svg') .append('svg')
.attr('id', id) .attr('id', id)
.attr('width', '100%') .attr('width', '100%')
.attr('xmlns', 'http://www.w3.org/2000/svg') .attr('xmlns', 'http://www.w3.org/2000/svg')
.append('g') .append('g')
} }
window.txt = txt window.txt = txt
txt = exports.encodeEntities(txt) txt = exports.encodeEntities(txt)
// console.warn('mermaid encode: ');
// console.warn(txt);
var element = d3.select('#d' + id).node() var element = d3.select('#d' + id).node()
var graphType = utils.detectType(txt) var graphType = utils.detectType(txt)
@@ -409,10 +402,6 @@ var render = function (id, txt, cb, container) {
config.flowchart.arrowMarkerAbsolute = config.arrowMarkerAbsolute config.flowchart.arrowMarkerAbsolute = config.arrowMarkerAbsolute
gitGraphRenderer.setConf(config.gitGraph) gitGraphRenderer.setConf(config.gitGraph)
gitGraphRenderer.draw(txt, id, false) gitGraphRenderer.draw(txt, id, false)
// if(config.cloneCssStyles){
// classes = gitGraphRenderer.getClasses(txt, false);
// utils.cloneCssStyles(element.firstChild, classes);
// }
break break
case 'graph': case 'graph':
config.flowchart.arrowMarkerAbsolute = config.arrowMarkerAbsolute config.flowchart.arrowMarkerAbsolute = config.arrowMarkerAbsolute
@@ -474,15 +463,11 @@ var render = function (id, txt, cb, container) {
url = url.replace(/\)/g, '\\)') url = url.replace(/\)/g, '\\)')
} }
// Fix for when the base tag is used // Fix for when the base tag is used
var svgCode = d3.select('#d' + id).node().innerHTML.replace(/url\(#arrowhead/g, 'url(' + url + '#arrowhead', 'g') var svgCode = d3.select('#d' + id).node().innerHTML.replace(/url\(#arrowhead/g, 'url(' + url + '#arrowhead', 'g')
svgCode = exports.decodeEntities(svgCode) svgCode = exports.decodeEntities(svgCode)
// console.warn('mermaid decode: ');
// console.warn(svgCode);
// var he = require('he');
// svgCode = he.decode(svgCode);
if (typeof cb !== 'undefined') { if (typeof cb !== 'undefined') {
cb(svgCode, graph.bindFunctions) cb(svgCode, graph.bindFunctions)
} else { } else {
@@ -505,9 +490,9 @@ exports.render = function (id, text, cb, containerElement) {
} }
if (typeof document === 'undefined') { if (typeof document === 'undefined') {
// Todo handle rendering serverside using phantomjs // Todo handle rendering serverside using phantomjs
} else { } else {
// In browser // In browser
return render(id, text, cb, containerElement) return render(id, text, cb, containerElement)
} }
} catch (e) { } catch (e) {
@@ -516,7 +501,7 @@ exports.render = function (id, text, cb, containerElement) {
} }
var setConf = function (cnf) { var setConf = function (cnf) {
// Top level initially mermaid, gflow, sequenceDiagram and gantt // Top level initially mermaid, gflow, sequenceDiagram and gantt
var lvl1Keys = Object.keys(cnf) var lvl1Keys = Object.keys(cnf)
var i var i
for (i = 0; i < lvl1Keys.length; i++) { for (i = 0; i < lvl1Keys.length; i++) {
@@ -540,7 +525,7 @@ var setConf = function (cnf) {
exports.initialize = function (options) { exports.initialize = function (options) {
log.debug('Initializing mermaidAPI') log.debug('Initializing mermaidAPI')
// Update default config with options supplied at initialization // Update default config with options supplied at initialization
if (typeof options === 'object') { if (typeof options === 'object') {
setConf(options) setConf(options)
} }

View File

@@ -6,22 +6,11 @@
* Created by knut on 14-11-23. * Created by knut on 14-11-23.
*/ */
var api = require('./mermaidAPI.js') var api = require('./mermaidAPI.js')
// var log = require('./logger').create();
describe('when using mermaidAPI and ', function () { describe('when using mermaidAPI and ', function () {
describe('doing initialize ', function () { describe('doing initialize ', function () {
// var main;
// var document;
// var window;
beforeEach(function () { beforeEach(function () {
// var MockBrowser = require('mock-browser').mocks.MockBrowser;
// var mock = new MockBrowser();
delete global.mermaid_config delete global.mermaid_config
// and in the run-code inside some object
// global.document = mock.getDocument();
// global.window = mock.getWindow();
document.body.innerHTML = '' document.body.innerHTML = ''
}) })
@@ -29,7 +18,7 @@ describe('when using mermaidAPI and ', function () {
var orgConfig = api.getConfig() var orgConfig = api.getConfig()
expect(orgConfig.testLiteral).toBe(undefined) expect(orgConfig.testLiteral).toBe(undefined)
api.initialize({'testLiteral': true}) api.initialize({ 'testLiteral': true })
var config = api.getConfig() var config = api.getConfig()
expect(config.testLiteral).toBe(true) expect(config.testLiteral).toBe(true)
@@ -43,8 +32,8 @@ describe('when using mermaidAPI and ', function () {
test2: false test2: false
} }
api.initialize({'testObject': object}) api.initialize({ 'testObject': object })
api.initialize({'testObject': {'test3': true}}) api.initialize({ 'testObject': { 'test3': true } })
var config = api.getConfig() var config = api.getConfig()
expect(config.testObject.test1).toBe(1) expect(config.testObject.test1).toBe(1)
@@ -55,7 +44,7 @@ describe('when using mermaidAPI and ', function () {
}) })
describe('checking validity of input ', function () { describe('checking validity of input ', function () {
it('it should return false for an invalid definiton', function () { it('it should return false for an invalid definiton', function () {
global.mermaidAPI.parseError = function () {} global.mermaidAPI.parseError = function () { }
spyOn(global.mermaidAPI, 'parseError') spyOn(global.mermaidAPI, 'parseError')
var res = api.parse('this is not a mermaid diagram definition') var res = api.parse('this is not a mermaid diagram definition')

View File

@@ -28,17 +28,14 @@ var detectType = function (text) {
} }
if (text.match(/^\s*digraph/)) { if (text.match(/^\s*digraph/)) {
// log.debug('Detected dot syntax');
return 'dotGraph' return 'dotGraph'
} }
if (text.match(/^\s*info/)) { if (text.match(/^\s*info/)) {
// log.debug('Detected info syntax');
return 'info' return 'info'
} }
if (text.match(/^\s*gantt/)) { if (text.match(/^\s*gantt/)) {
// log.debug('Detected info syntax');
return 'gantt' return 'gantt'
} }
@@ -66,7 +63,7 @@ var cloneCssStyles = function (svg, classes) {
var sheets = document.styleSheets var sheets = document.styleSheets
var rule var rule
for (var i = 0; i < sheets.length; i++) { for (var i = 0; i < sheets.length; i++) {
// Avoid multiple inclusion on pages with multiple graphs // Avoid multiple inclusion on pages with multiple graphs
if (sheets[i].title !== 'mermaid-svg-internal-css') { if (sheets[i].title !== 'mermaid-svg-internal-css') {
try { try {
var rules = sheets[i].cssRules var rules = sheets[i].cssRules
@@ -121,7 +118,7 @@ var cloneCssStyles = function (svg, classes) {
s.setAttribute('type', 'text/css') s.setAttribute('type', 'text/css')
s.setAttribute('title', 'mermaid-svg-internal-css') s.setAttribute('title', 'mermaid-svg-internal-css')
s.innerHTML = '/* <![CDATA[ */\n' s.innerHTML = '/* <![CDATA[ */\n'
// Make this CSS local to this SVG // Make this CSS local to this SVG
if (defaultStyles !== '') { if (defaultStyles !== '') {
s.innerHTML += defaultStyles s.innerHTML += defaultStyles
} }

View File

@@ -4,13 +4,8 @@
*/ */
var utils = require('./utils') var utils = require('./utils')
// var log = require('./logger').create();
describe('when detecting chart type ', function () { describe('when detecting chart type ', function () {
var str var str
beforeEach(function () {
})
it('should handle a graph defintion', function () { it('should handle a graph defintion', function () {
str = 'graph TB\nbfs1:queue' str = 'graph TB\nbfs1:queue'
@@ -40,11 +35,6 @@ describe('when detecting chart type ', function () {
describe('when cloning CSS ', function () { describe('when cloning CSS ', function () {
beforeEach(function () { beforeEach(function () {
// var MockBrowser = require('mock-browser').mocks.MockBrowser;
// var mock = new MockBrowser();
// and in the run-code inside some object
// global.document = mock.getDocument();
document.body.innerHTML = '' document.body.innerHTML = ''
}) })
@@ -56,11 +46,11 @@ describe('when cloning CSS ', function () {
var innerStyle = styleSheet.innerHTML var innerStyle = styleSheet.innerHTML
var styleArr = innerStyle.split('\n') var styleArr = innerStyle.split('\n')
// Remove first and last two lines to remove the CDATA // Remove first and last two lines to remove the CDATA
expect(styleArr.length).toBeGreaterThan(2) expect(styleArr.length).toBeGreaterThan(2)
var styleArrTrim = styleArr.slice(1, -2) var styleArrTrim = styleArr.slice(1, -2)
// Remove all empty lines // Remove all empty lines
for (var i = 0; i < styleArrTrim.length; i++) { for (var i = 0; i < styleArrTrim.length; i++) {
if (styleArrTrim[i].trim() === '') { if (styleArrTrim[i].trim() === '') {
styleArrTrim.splice(i, 1) styleArrTrim.splice(i, 1)
@@ -113,7 +103,7 @@ describe('when cloning CSS ', function () {
var svg = document.createElement('svg') var svg = document.createElement('svg')
svg.setAttribute('id', 'mermaid-01') svg.setAttribute('id', 'mermaid-01')
// Firefox throws a SecurityError when trying to access cssRules // Firefox throws a SecurityError when trying to access cssRules
document.styleSheets[document.styleSheets.length++] = { document.styleSheets[document.styleSheets.length++] = {
get cssRules () { throw new Error('SecurityError') } get cssRules () { throw new Error('SecurityError') }
} }
@@ -128,7 +118,7 @@ describe('when cloning CSS ', function () {
svg.setAttribute('id', 'mermaid-01') svg.setAttribute('id', 'mermaid-01')
utils.cloneCssStyles(svg, {}) utils.cloneCssStyles(svg, {})
// Should not create style element if not needed // Should not create style element if not needed
expect(svg.innerHTML).toBe('') expect(svg.innerHTML).toBe('')
}) })
@@ -136,9 +126,9 @@ describe('when cloning CSS ', function () {
var svg = document.createElement('svg') var svg = document.createElement('svg')
svg.setAttribute('id', 'mermaid-01') svg.setAttribute('id', 'mermaid-01')
utils.cloneCssStyles(svg, {'default': {'styles': ['stroke:#fff', 'stroke-width:1.5px']}}) utils.cloneCssStyles(svg, { 'default': { 'styles': ['stroke:#fff', 'stroke-width:1.5px'] } })
expect(stylesToArray(svg)).toEqual(['#mermaid-01 .node>rect { stroke:#fff; stroke-width:1.5px; }']) expect(stylesToArray(svg)).toEqual(['#mermaid-01 .node>rect { stroke:#fff; stroke-width:1.5px; }'])
// Also verify the elements around the styling // Also verify the elements around the styling
expect(svg.innerHTML).toBe('<style type="text/css" title="mermaid-svg-internal-css">/* <![CDATA[ */\n#mermaid-01 .node>rect { stroke:#fff; stroke-width:1.5px; }\n/* ]]> */\n</style>') expect(svg.innerHTML).toBe('<style type="text/css" title="mermaid-svg-internal-css">/* <![CDATA[ */\n#mermaid-01 .node>rect { stroke:#fff; stroke-width:1.5px; }\n/* ]]> */\n</style>')
}) })
@@ -148,7 +138,7 @@ describe('when cloning CSS ', function () {
addStyleToDocument('mermaid') addStyleToDocument('mermaid')
utils.cloneCssStyles(svg, {}) utils.cloneCssStyles(svg, {})
// Should not create style element if not needed // Should not create style element if not needed
expect(svg.innerHTML).toBe('') expect(svg.innerHTML).toBe('')
}) })
@@ -179,7 +169,7 @@ describe('when cloning CSS ', function () {
it('should handle a default class together with stylesheet in document with classes in SVG', function () { it('should handle a default class together with stylesheet in document with classes in SVG', function () {
var svg = generateSVG() var svg = generateSVG()
addStyleToDocument() addStyleToDocument()
utils.cloneCssStyles(svg, {'default': {'styles': ['stroke:#ffffff', 'stroke-width:1.5px']}}) utils.cloneCssStyles(svg, { 'default': { 'styles': ['stroke:#ffffff', 'stroke-width:1.5px'] } })
expect(stylesToArray(svg)).toEqual(['#mermaid-01 .node>rect { stroke:#ffffff; stroke-width:1.5px; }', '.node { stroke: #eeeeee;}', '.node-square { stroke: #bbbbbb;}']) expect(stylesToArray(svg)).toEqual(['#mermaid-01 .node>rect { stroke:#ffffff; stroke-width:1.5px; }', '.node { stroke: #eeeeee;}', '.node-square { stroke: #bbbbbb;}'])
}) })
@@ -187,9 +177,9 @@ describe('when cloning CSS ', function () {
var svg = generateSVG() var svg = generateSVG()
addStyleToDocument() addStyleToDocument()
utils.cloneCssStyles(svg, { utils.cloneCssStyles(svg, {
'default': {'styles': ['stroke:#ffffff', 'stroke-width:1.5px']}, 'default': { 'styles': ['stroke:#ffffff', 'stroke-width:1.5px'] },
'node-square': {'styles': ['fill:#eeeeee', 'stroke:#aaaaaa']}, 'node-square': { 'styles': ['fill:#eeeeee', 'stroke:#aaaaaa'] },
'node-circle': {'styles': ['fill:#444444', 'stroke:#111111']} 'node-circle': { 'styles': ['fill:#444444', 'stroke:#111111'] }
}) })
expect(stylesToArray(svg)).toEqual(['#mermaid-01 .node>rect { stroke:#ffffff; stroke-width:1.5px; }', expect(stylesToArray(svg)).toEqual(['#mermaid-01 .node>rect { stroke:#ffffff; stroke-width:1.5px; }',
'.node { stroke: #eeeeee;}', '.node { stroke: #eeeeee;}',

View File

@@ -5,3 +5,8 @@
- default theme doesn't work for class diagram - default theme doesn't work for class diagram
- mermaidAPI.js cannot be required directly - mermaidAPI.js cannot be required directly
- compile less to css - compile less to css
- don't version control generated content, move them to outside project
- editor
- dist
- docs
- what's the correct way to change logLevel as an end user?