Fix code style issues

This commit is contained in:
Tyler Long 2017-04-13 20:50:22 +08:00
parent a2ce9e6a54
commit ab398c64a8
7 changed files with 269 additions and 268 deletions

View File

@ -1,21 +1,21 @@
var fs = require('fs'), var fs = require('fs')
exec = require('child_process').exec, var exec = require('child_process').exec
chalk = require('chalk'), var chalk = require('chalk')
which = require('which'), var which = require('which')
parseArgs = require('minimist'), var parseArgs = require('minimist')
semver = require('semver'), var semver = require('semver')
path = require('path') var path = require('path')
var PHANTOM_VERSION = '^2.1.0' var PHANTOM_VERSION = '^2.1.0'
var info = chalk.blue.bold, var info = chalk.blue.bold
note = chalk.green.bold // var note = chalk.green.bold
module.exports = (function () { module.exports = (function () {
return new cli() return new Cli()
}()) }())
function cli (options) { function Cli (options) {
this.options = { this.options = {
alias: { alias: {
help: 'h', help: 'h',
@ -37,7 +37,7 @@ function cli (options) {
this.errors = [] this.errors = []
this.message = null this.message = null
this.helpMessage = [, this.helpMessage = [
info('Usage: mermaid [options] <file>...'), info('Usage: mermaid [options] <file>...'),
'', '',
'file The mermaid description file to be rendered', 'file The mermaid description file to be rendered',
@ -60,10 +60,10 @@ function cli (options) {
return this return this
} }
cli.prototype.parse = function (argv, next) { Cli.prototype.parse = function (argv, next) {
this.errors = [] // clear errors this.errors = [] // clear errors
var options = parseArgs(argv, this.options), var options = parseArgs(argv, this.options)
phantom // var phantom
if (options.version) { if (options.version) {
var pkg = require('../package.json') var pkg = require('../package.json')
@ -138,7 +138,7 @@ cli.prototype.parse = function (argv, next) {
} }
options.phantomPath = path options.phantomPath = path
next( next(
this.errors.length > 0 ? this.errors : null this.errors.length > 0 ? this.errors : null
, this.message , this.message
, options , options
) )
@ -147,12 +147,12 @@ cli.prototype.parse = function (argv, next) {
} }
function createCheckPhantom (_phantomPath) { function createCheckPhantom (_phantomPath) {
var phantomPath = _phantomPath, var phantomPath = _phantomPath
phantomVersion // var phantomVersion
return function checkPhantom (_next) { return function checkPhantom (_next) {
var next = _next || function () {}, var next = _next || function () { }
err var err
if (typeof phantomPath === 'undefined') { if (typeof phantomPath === 'undefined') {
try { try {
@ -186,7 +186,7 @@ function createCheckPhantom (_phantomPath) {
next(new Error('Could not find phantomjs at the specified path.')) next(new Error('Could not find phantomjs at the specified path.'))
} else if (!semver.satisfies(stdout, PHANTOM_VERSION)) { } else if (!semver.satisfies(stdout, PHANTOM_VERSION)) {
next(new Error( next(new Error(
'mermaid requires phantomjs ' + 'mermaid requires phantomjs ' +
PHANTOM_VERSION + PHANTOM_VERSION +
' to be installed, found version ' + ' to be installed, found version ' +
stdout stdout

View File

@ -1,7 +1,7 @@
var os = require('os'), // var os = require('os')
fs = require('fs'), // var fs = require('fs')
path = require('path'), var path = require('path')
spawn = require('child_process').spawn var spawn = require('child_process').spawn
var mkdirp = require('mkdirp') var mkdirp = require('mkdirp')
@ -10,22 +10,22 @@ var phantomscript = path.join(__dirname, 'phantomscript.js')
module.exports = { process: processMermaid } module.exports = { process: processMermaid }
function processMermaid (files, _options, _next) { function processMermaid (files, _options, _next) {
var options = _options || {}, var options = _options || {}
outputDir = options.outputDir || process.cwd(), var outputDir = options.outputDir || process.cwd()
outputSuffix = options.outputSuffix || '', var outputSuffix = options.outputSuffix || ''
next = _next || function () {}, var next = _next || function () { }
phantomArgs = [ var phantomArgs = [
phantomscript, phantomscript,
outputDir, outputDir,
options.png, options.png,
options.svg, options.svg,
options.css, options.css,
options.sequenceConfig, options.sequenceConfig,
options.ganttConfig, options.ganttConfig,
options.verbose, options.verbose,
options.width, options.width,
outputSuffix outputSuffix
] ]
files.forEach(function (file) { files.forEach(function (file) {
phantomArgs.push(file) phantomArgs.push(file)
@ -35,7 +35,7 @@ function processMermaid (files, _options, _next) {
if (err) { if (err) {
throw err throw err
} }
phantom = spawn(options.phantomPath, phantomArgs) var phantom = spawn(options.phantomPath, phantomArgs)
phantom.on('exit', next) phantom.on('exit', next)

View File

@ -6,13 +6,13 @@
* https://github.com/filamentgroup/grunticon * https://github.com/filamentgroup/grunticon
*/ */
phantom.onError = function (msg, trace) { window.phantom.onError = function (msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg] var msgStack = ['PHANTOM ERROR: ' + msg]
if (trace && trace.length) { if (trace && trace.length) {
msgStack.push('TRACE:') msgStack.push('TRACE:')
trace.forEach(function (t) { trace.forEach(function (t) {
msgStack.push( msgStack.push(
' -> ' + ' -> ' +
(t.file || t.sourceURL) + (t.file || t.sourceURL) +
': ' + ': ' +
t.line + t.line +
@ -21,32 +21,32 @@ phantom.onError = function (msg, trace) {
}) })
} }
system.stderr.write(msgStack.join('\n')) system.stderr.write(msgStack.join('\n'))
phantom.exit(1) window.phantom.exit(1)
} }
var system = require('system'), var system = require('system')
fs = require('fs'), var fs = require('fs')
webpage = require('webpage') var webpage = require('webpage')
var page = webpage.create(), var page = webpage.create()
files = system.args.slice(10, system.args.length), var files = system.args.slice(10, system.args.length)
width = system.args[8] var width = system.args[8]
if (typeof width === 'undefined' || width === 'undefined') { if (typeof width === 'undefined' || width === 'undefined') {
width = 1200 width = 1200
} }
var options = { var options = {
outputDir: system.args[1], outputDir: system.args[1],
png: system.args[2] === 'true', png: system.args[2] === 'true',
svg: system.args[3] === 'true', svg: system.args[3] === 'true',
css: fs.read(system.args[4]), css: fs.read(system.args[4]),
sequenceConfig: system.args[5] !== 'null' ? JSON.parse(fs.read(system.args[5])) : {}, sequenceConfig: system.args[5] !== 'null' ? JSON.parse(fs.read(system.args[5])) : {},
ganttConfig: system.args[6] !== 'null' ? JSON.parse(fs.read(system.args[6])) : {}, ganttConfig: system.args[6] !== 'null' ? JSON.parse(fs.read(system.args[6])) : {},
verbose: system.args[7] === 'true', verbose: system.args[7] === 'true',
width: width, width: width,
outputSuffix: system.args[9] outputSuffix: system.args[9]
}, }
log = logger(options.verbose) var log = logger(options.verbose)
options.sequenceConfig.useMaxWidth = false options.sequenceConfig.useMaxWidth = false
page.content = [ page.content = [
@ -69,12 +69,12 @@ page.onConsoleMessage = function (msg, lineNum, sourceId) {
console.log('Num files to execute : ' + files.length) console.log('Num files to execute : ' + files.length)
files.forEach(function (file) { files.forEach(function (file) {
var contents = fs.read(file), var contents = fs.read(file)
filename = file.split(fs.separator).slice(-1), var filename = file.split(fs.separator).slice(-1)
oParser = new DOMParser(), var oParser = new window.DOMParser()
oDOM, var oDOM
svgContent, var svgContent
allElements var allElements
console.log('ready to execute png: ' + filename + '.png ') console.log('ready to execute png: ' + filename + '.png ')
@ -112,7 +112,7 @@ files.forEach(function (file) {
} }
if (options.svg) { if (options.svg) {
var serialize = new XMLSerializer() var serialize = new window.XMLSerializer()
fs.write(outputPath + '.svg' fs.write(outputPath + '.svg'
, serialize.serializeToString(oDOM) + '\n' , serialize.serializeToString(oDOM) + '\n'
, 'w' , 'w'
@ -121,15 +121,15 @@ files.forEach(function (file) {
} }
}) })
phantom.exit() window.phantom.exit()
function logger (_verbose) { function logger (_verbose) {
var verbose = _verbose var verbose = _verbose
return function (_message, _level) { return function (_message, _level) {
var level = level, var level = _level
message = _message, var message = _message
log var log
log = level === 'error' ? system.stderr : system.stdout log = level === 'error' ? system.stderr : system.stdout
@ -149,7 +149,7 @@ function traverse (obj) {
if (node && node.hasChildNodes()) { if (node && node.hasChildNodes()) {
var child = node.firstChild var child = node.firstChild
while (child) { while (child) {
if (child.nodeType === 1 && child.nodeName != 'SCRIPT') { if (child.nodeType === 1 && child.nodeName !== 'SCRIPT') {
tree.push(child) tree.push(child)
visit(child) visit(child)
} }
@ -163,13 +163,13 @@ function traverse (obj) {
function resolveSVGElement (element) { function resolveSVGElement (element) {
var prefix = { var prefix = {
xmlns: 'http://www.w3.org/2000/xmlns/', xmlns: 'http://www.w3.org/2000/xmlns/',
xlink: 'http://www.w3.org/1999/xlink', xlink: 'http://www.w3.org/1999/xlink',
svg: 'http://www.w3.org/2000/svg' svg: 'http://www.w3.org/2000/svg'
}, }
doctype = '<!DOCTYPE svg:svg PUBLIC' + // var doctype = '<!DOCTYPE svg:svg PUBLIC' +
' "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN"' + // ' "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN"' +
' "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">' // ' "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
element.setAttribute('version', '1.1') element.setAttribute('version', '1.1')
// removing attributes so they aren't doubled up // removing attributes so they aren't doubled up
@ -187,48 +187,48 @@ function resolveSVGElement (element) {
function setSVGStyle (svg, css) { function setSVGStyle (svg, css) {
if (!css || !svg) { return } if (!css || !svg) { return }
var styles = svg.getElementsByTagName('style') var styles = svg.getElementsByTagName('style')
if (!styles || styles.length == 0) { return } if (!styles || styles.length === 0) { return }
styles[0].textContent = css styles[0].textContent = css
} }
function resolveForeignObjects (element) { function resolveForeignObjects (element) {
return // return
var children, // var children
textElement, // var textElement
textSpan // var textSpan
if (element.tagName === 'foreignObject') { // if (element.tagName === 'foreignObject') {
textElement = document.createElement('text') // textElement = document.createElement('text')
textSpan = document.createElement('tspan') // textSpan = document.createElement('tspan')
textSpan.setAttribute( // textSpan.setAttribute(
'style' // 'style'
, 'font-size: 11.5pt; font-family: "sans-serif";' // , 'font-size: 11.5pt; font-family: "sans-serif";'
) // )
textSpan.setAttribute('x', 0) // textSpan.setAttribute('x', 0)
textSpan.setAttribute('y', 14.5) // textSpan.setAttribute('y', 14.5)
textSpan.textContent = element.textContent // textSpan.textContent = element.textContent
textElement.appendChild(textSpan) // textElement.appendChild(textSpan)
element.parentElement.appendChild(textElement) // element.parentElement.appendChild(textElement)
element.parentElement.removeChild(element) // element.parentElement.removeChild(element)
} // }
} }
// The sandboxed function that's executed in-page by phantom // The sandboxed function that's executed in-page by phantom
function executeInPage (data) { function executeInPage (data) {
var xmlSerializer = new XMLSerializer(), var xmlSerializer = new window.XMLSerializer()
contents = data.contents, var contents = data.contents
sequenceConfig = JSON.stringify(data.sequenceConfig), var sequenceConfig = JSON.stringify(data.sequenceConfig)
ganttConfig = JSON.stringify(data.ganttConfig).replace(/"(function.*})"/, '$1'), var ganttConfig = JSON.stringify(data.ganttConfig).replace(/"(function.*})"/, '$1')
toRemove, // var toRemove
el, // var el
elContent, // var elContent
svg, var svg
svgValue, var svgValue
boundingBox, var boundingBox
width, var width
height, var height
confWidth = data.confWidth var confWidth = data.confWidth
var toRemove = document.getElementsByClassName('mermaid') var toRemove = document.getElementsByClassName('mermaid')
if (toRemove && toRemove.length) { if (toRemove && toRemove.length) {
@ -244,17 +244,17 @@ function executeInPage (data) {
var config = { var config = {
sequenceDiagram: JSON.parse(sequenceConfig), sequenceDiagram: JSON.parse(sequenceConfig),
flowchart: {useMaxWidth: false}, flowchart: { useMaxWidth: false },
logLevel: 1 logLevel: 1
} }
mermaid.initialize(config) window.mermaid.initialize(config)
var sc = document.createElement('script') var sc = document.createElement('script')
sc.appendChild(document.createTextNode('mermaid.ganttConfig = ' + ganttConfig + ';')) sc.appendChild(document.createTextNode('mermaid.ganttConfig = ' + ganttConfig + ';'))
document.body.appendChild(sc) document.body.appendChild(sc)
mermaid.init() window.mermaid.init()
svg = document.querySelector('svg') svg = document.querySelector('svg')

View File

@ -4,12 +4,12 @@ var log = Logger.Log
var relations = [] var relations = []
var classes var classes
var idCache // var idCache
classes = { classes = {
} }
// Functions to be run after graph rendering // Functions to be run after graph rendering
var funs = [] // var funs = []
/** /**
* Function called by parser when a node definition has been found. * Function called by parser when a node definition has been found.
* @param id * @param id

View File

@ -367,9 +367,9 @@ module.exports.draw = function (text, id) {
} }
var relations = cDDb.getRelations() var relations = cDDb.getRelations()
var i = 0 // var i = 0
relations.forEach(function (relation) { relations.forEach(function (relation) {
i = i + 1 // i = i + 1
log.info('tjoho' + getGraphId(relation.id1) + getGraphId(relation.id2) + JSON.stringify(relation)) log.info('tjoho' + getGraphId(relation.id1) + getGraphId(relation.id2) + JSON.stringify(relation))
g.setEdge(getGraphId(relation.id1), getGraphId(relation.id2), {relation: relation}) g.setEdge(getGraphId(relation.id1), getGraphId(relation.id2), {relation: relation})
}) })

View File

@ -17,12 +17,12 @@
// var classRenderer = proxyquire('./classRenderer', { '../../d3': d3 }); // var classRenderer = proxyquire('./classRenderer', { '../../d3': d3 });
// var testDom = require('testdom')('<html><body><div id="tst"></div></body></html>'); // var testDom = require('testdom')('<html><body><div id="tst"></div></body></html>');
var classRenderer = require('./classRenderer') // var classRenderer = require('./classRenderer')
var parser = require('./parser/classDiagram').parser // var parser = require('./parser/classDiagram').parser
describe('class diagram, ', function () { describe('class diagram, ', function () {
describe('when rendering a classDiagram', function () { describe('when rendering a classDiagram', function () {
var conf // var conf
beforeEach(function () { beforeEach(function () {
/// /parser.yy = require('./classDb'); /// /parser.yy = require('./classDb');
/// /parser.yy.clear(); /// /parser.yy.clear();
@ -101,8 +101,8 @@ describe('class diagram, ', function () {
}) })
}) })
it('it should handle one actor', function () { it('it should handle one actor', function () {
var str = 'classDiagram\n' + // var str = 'classDiagram\n' +
'Class01 --|> Class02' // 'Class01 --|> Class02'
// classRenderer.draw(str,'tst'); // classRenderer.draw(str,'tst');

View File

@ -29,7 +29,7 @@ exports.addVertices = function (vert, g) {
var styleFromStyleArr = function (styleStr, arr) { var styleFromStyleArr = function (styleStr, arr) {
var i var i
// Create a compound style definition from the style definitions found for the node in the graph definition // Create a compound style definition from the style definitions found for the node in the graph definition
for (i = 0; i < arr.length; i++) { for (i = 0; i < arr.length; i++) {
if (typeof arr[i] !== 'undefined') { if (typeof arr[i] !== 'undefined') {
styleStr = styleStr + arr[i] + ';' styleStr = styleStr + arr[i] + ';'
@ -39,32 +39,32 @@ exports.addVertices = function (vert, g) {
return styleStr return styleStr
} }
// Iterate through each item in the vertice object (containing all the vertices found) in the graph definition // Iterate through each item in the vertice object (containing all the vertices found) in the graph definition
keys.forEach(function (id) { keys.forEach(function (id) {
var vertice = vert[id] var vertice = vert[id]
var verticeText var verticeText
/** /**
* Variable for storing the classes for the vertice * Variable for storing the classes for the vertice
* @type {string} * @type {string}
*/ */
var classStr = '' var classStr = ''
// log.debug(vertice.classes); // log.debug(vertice.classes);
if (vertice.classes.length > 0) { if (vertice.classes.length > 0) {
classStr = vertice.classes.join(' ') classStr = vertice.classes.join(' ')
} }
/** /**
* Variable for storing the extracted style for the vertice * Variable for storing the extracted style for the vertice
* @type {string} * @type {string}
*/ */
var style = '' var style = ''
// Create a compound style definition from the style definitions found for the node in the graph definition // Create a compound style definition from the style definitions found for the node in the graph definition
style = styleFromStyleArr(style, vertice.styles) style = styleFromStyleArr(style, vertice.styles)
// Use vertice id as text in the box if no text is provided by the graph definition // Use vertice id as text in the box if no text is provided by the graph definition
if (typeof vertice.text === 'undefined') { if (typeof vertice.text === 'undefined') {
verticeText = vertice.id verticeText = vertice.id
} else { } else {
@ -74,11 +74,11 @@ exports.addVertices = function (vert, g) {
var labelTypeStr = '' var labelTypeStr = ''
if (conf.htmlLabels) { if (conf.htmlLabels) {
labelTypeStr = 'html' labelTypeStr = 'html'
verticeText = verticeText.replace(/fa:fa[\w\-]+/g, function (s) { verticeText = verticeText.replace(/fa:fa[\w-]+/g, function (s) {
return '<i class="fa ' + s.substring(3) + '"></i>' return '<i class="fa ' + s.substring(3) + '"></i>'
}) })
} else { } else {
var svg_label = document.createElementNS('http://www.w3.org/2000/svg', 'text') var svgLabel = document.createElementNS('http://www.w3.org/2000/svg', 'text')
var rows = verticeText.split(/<br>/) var rows = verticeText.split(/<br>/)
@ -89,20 +89,20 @@ exports.addVertices = function (vert, g) {
tspan.setAttribute('dy', '1em') tspan.setAttribute('dy', '1em')
tspan.setAttribute('x', '1') tspan.setAttribute('x', '1')
tspan.textContent = rows[j] tspan.textContent = rows[j]
svg_label.appendChild(tspan) svgLabel.appendChild(tspan)
} }
labelTypeStr = 'svg' labelTypeStr = 'svg'
verticeText = svg_label verticeText = svgLabel
// verticeText = verticeText.replace(/<br\/>/g, '\n'); // verticeText = verticeText.replace(/<br\/>/g, '\n');
// labelTypeStr = 'text'; // labelTypeStr = 'text';
} }
var radious = 0 var radious = 0
var _shape = '' var _shape = ''
// Set the shape based parameters // Set the shape based parameters
switch (vertice.type) { switch (vertice.type) {
case 'round': case 'round':
radious = 5 radious = 5
@ -128,14 +128,14 @@ exports.addVertices = function (vert, g) {
break break
case 'group': case 'group':
_shape = 'rect' _shape = 'rect'
// Need to create a text node if using svg labels, see #367 // Need to create a text node if using svg labels, see #367
verticeText = conf.htmlLabels ? '' : document.createElementNS('http://www.w3.org/2000/svg', 'text') verticeText = conf.htmlLabels ? '' : document.createElementNS('http://www.w3.org/2000/svg', 'text')
break break
default: default:
_shape = 'rect' _shape = 'rect'
} }
// Add the node // Add the node
g.setNode(vertice.id, {labelType: labelTypeStr, shape: _shape, label: verticeText, rx: radious, ry: radious, 'class': classStr, style: style, id: vertice.id}) g.setNode(vertice.id, { labelType: labelTypeStr, shape: _shape, label: verticeText, rx: radious, ry: radious, 'class': classStr, style: style, id: vertice.id })
}) })
} }
@ -156,7 +156,7 @@ exports.addEdges = function (edges, g) {
cnt++ cnt++
var edgeData = {} var edgeData = {}
// Set link type for rendering // Set link type for rendering
if (edge.type === 'arrow_open') { if (edge.type === 'arrow_open') {
edgeData.arrowhead = 'none' edgeData.arrowhead = 'none'
} else { } else {
@ -215,7 +215,7 @@ exports.addEdges = function (edges, g) {
edgeData.label = edge.text.replace(/<br>/g, '\n') edgeData.label = edge.text.replace(/<br>/g, '\n')
} }
} }
// Add the edge to the graph // Add the edge to the graph
g.setEdge(edge.start, edge.end, edgeData, cnt) g.setEdge(edge.start, edge.end, edgeData, cnt)
}) })
} }
@ -234,15 +234,15 @@ exports.getClasses = function (text, isDot) {
} }
parser.yy = graph parser.yy = graph
// Parse the graph definition // Parse the graph definition
parser.parse(text) parser.parse(text)
var classes = graph.getClasses() var classes = graph.getClasses()
// Add default class if undefined // Add default class if undefined
if (typeof (classes.default) === 'undefined') { if (typeof (classes.default) === 'undefined') {
classes.default = {id: 'default'} classes.default = { id: 'default' }
// classes.default.styles = ['fill:#ffa','stroke:#666','stroke-width:3px']; // classes.default.styles = ['fill:#ffa','stroke:#666','stroke-width:3px'];
classes.default.styles = [] classes.default.styles = []
classes.default.clusterStyles = ['rx:4px', 'fill: rgb(255, 255, 222)', 'rx: 4px', 'stroke: rgb(170, 170, 51)', 'stroke-width: 1px'] classes.default.clusterStyles = ['rx:4px', 'fill: rgb(255, 255, 222)', 'rx: 4px', 'stroke: rgb(170, 170, 51)', 'stroke-width: 1px']
classes.default.nodeLabelStyles = ['fill:#000', 'stroke:none', 'font-weight:300', 'font-family:"Helvetica Neue",Helvetica,Arial,sans-serf', 'font-size:14px'] classes.default.nodeLabelStyles = ['fill:#000', 'stroke:none', 'font-weight:300', 'font-family:"Helvetica Neue",Helvetica,Arial,sans-serf', 'font-size:14px']
@ -267,34 +267,34 @@ exports.draw = function (text, id, isDot) {
} }
parser.yy = graph parser.yy = graph
// Parse the graph definition // Parse the graph definition
try { try {
parser.parse(text) parser.parse(text)
} catch (err) { } catch (err) {
log.debug('Parsing failed') log.debug('Parsing failed')
} }
// Fetch the default direction, use TD if none was found // Fetch the default direction, use TD if none was found
var dir var dir
dir = graph.getDirection() dir = graph.getDirection()
if (typeof dir === 'undefined') { if (typeof dir === 'undefined') {
dir = 'TD' dir = 'TD'
} }
// Create the input mermaid.graph // Create the input mermaid.graph
var g = new dagreD3.graphlib.Graph({ var g = new dagreD3.graphlib.Graph({
multigraph: true, multigraph: true,
compound: true compound: true
}) })
.setGraph({ .setGraph({
rankdir: dir, rankdir: dir,
marginx: 20, marginx: 20,
marginy: 20 marginy: 20
}) })
.setDefaultEdgeLabel(function () { .setDefaultEdgeLabel(function () {
return {} return {}
}) })
var subG var subG
var subGraphs = graph.getSubGraphs() var subGraphs = graph.getSubGraphs()
@ -304,10 +304,10 @@ exports.draw = function (text, id, isDot) {
graph.addVertex(subG.id, subG.title, 'group', undefined) graph.addVertex(subG.id, subG.title, 'group', undefined)
} }
// Fetch the verices/nodes and edges/links from the parsed graph definition // Fetch the verices/nodes and edges/links from the parsed graph definition
var vert = graph.getVertices() var vert = graph.getVertices()
// log.debug(vert); // log.debug(vert);
var edges = graph.getEdges() var edges = graph.getEdges()
i = 0 i = 0
@ -318,166 +318,167 @@ exports.draw = function (text, id, isDot) {
d3.selectAll('cluster').append('text') d3.selectAll('cluster').append('text')
for (j = 0; j < subG.nodes.length; j++) { for (j = 0; j < subG.nodes.length; j++) {
// log.debug('Setting node',subG.nodes[j],' to subgraph '+id); // log.debug('Setting node',subG.nodes[j],' to subgraph '+id);
g.setParent(subG.nodes[j], subG.id) g.setParent(subG.nodes[j], subG.id)
} }
} }
exports.addVertices(vert, g) exports.addVertices(vert, g)
exports.addEdges(edges, g) exports.addEdges(edges, g)
// Create the renderer // Create the renderer
var render = new dagreD3.render() var Render = dagreD3.render
var render = new Render()
// Add custom shape for rhombus type of boc (decision) // Add custom shape for rhombus type of boc (decision)
render.shapes().question = function (parent, bbox, node) { render.shapes().question = function (parent, bbox, node) {
var w = bbox.width, var w = bbox.width
h = bbox.height, var h = bbox.height
s = (w + h) * 0.8, var s = (w + h) * 0.8
points = [ var points = [
{x: s / 2, y: 0}, { x: s / 2, y: 0 },
{x: s, y: -s / 2}, { x: s, y: -s / 2 },
{x: s / 2, y: -s}, { x: s / 2, y: -s },
{x: 0, y: -s / 2} { x: 0, y: -s / 2 }
] ]
var shapeSvg = parent.insert('polygon', ':first-child') var shapeSvg = parent.insert('polygon', ':first-child')
.attr('points', points.map(function (d) { .attr('points', points.map(function (d) {
return d.x + ',' + d.y return d.x + ',' + d.y
}).join(' ')) }).join(' '))
.attr('rx', 5) .attr('rx', 5)
.attr('ry', 5) .attr('ry', 5)
.attr('transform', 'translate(' + (-s / 2) + ',' + (s * 2 / 4) + ')') .attr('transform', 'translate(' + (-s / 2) + ',' + (s * 2 / 4) + ')')
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point) return dagreD3.intersect.polygon(node, points, point)
} }
return shapeSvg return shapeSvg
} }
// Add custom shape for box with inverted arrow on left side // Add custom shape for box with inverted arrow on left side
render.shapes().rect_left_inv_arrow = function (parent, bbox, node) { render.shapes().rect_left_inv_arrow = function (parent, bbox, node) {
var w = bbox.width, var w = bbox.width
h = bbox.height, var h = bbox.height
points = [ var points = [
{x: -h / 2, y: 0}, { x: -h / 2, y: 0 },
{x: w, y: 0}, { x: w, y: 0 },
{x: w, y: -h}, { x: w, y: -h },
{x: -h / 2, y: -h}, { x: -h / 2, y: -h },
{x: 0, y: -h / 2} { x: 0, y: -h / 2 }
] ]
var shapeSvg = parent.insert('polygon', ':first-child') var shapeSvg = parent.insert('polygon', ':first-child')
.attr('points', points.map(function (d) { .attr('points', points.map(function (d) {
return d.x + ',' + d.y return d.x + ',' + d.y
}).join(' ')) }).join(' '))
.attr('transform', 'translate(' + (-w / 2) + ',' + (h * 2 / 4) + ')') .attr('transform', 'translate(' + (-w / 2) + ',' + (h * 2 / 4) + ')')
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point) return dagreD3.intersect.polygon(node, points, point)
} }
return shapeSvg return shapeSvg
} }
// Add custom shape for box with inverted arrow on right side // Add custom shape for box with inverted arrow on right side
render.shapes().rect_right_inv_arrow = function (parent, bbox, node) { render.shapes().rect_right_inv_arrow = function (parent, bbox, node) {
var w = bbox.width, var w = bbox.width
h = bbox.height, var h = bbox.height
points = [ var points = [
{x: 0, y: 0}, { x: 0, y: 0 },
{x: w + h / 2, y: 0}, { x: w + h / 2, y: 0 },
{x: w, y: -h / 2}, { x: w, y: -h / 2 },
{x: w + h / 2, y: -h}, { x: w + h / 2, y: -h },
{x: 0, y: -h} { x: 0, y: -h }
] ]
var shapeSvg = parent.insert('polygon', ':first-child') var shapeSvg = parent.insert('polygon', ':first-child')
.attr('points', points.map(function (d) { .attr('points', points.map(function (d) {
return d.x + ',' + d.y return d.x + ',' + d.y
}).join(' ')) }).join(' '))
.attr('transform', 'translate(' + (-w / 2) + ',' + (h * 2 / 4) + ')') .attr('transform', 'translate(' + (-w / 2) + ',' + (h * 2 / 4) + ')')
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point) return dagreD3.intersect.polygon(node, points, point)
} }
return shapeSvg return shapeSvg
} }
// Add our custom arrow - an empty arrowhead // Add our custom arrow - an empty arrowhead
render.arrows().none = function normal (parent, id, edge, type) { render.arrows().none = function normal (parent, id, edge, type) {
var marker = parent.append('marker') var marker = parent.append('marker')
.attr('id', id) .attr('id', id)
.attr('viewBox', '0 0 10 10') .attr('viewBox', '0 0 10 10')
.attr('refX', 9) .attr('refX', 9)
.attr('refY', 5) .attr('refY', 5)
.attr('markerUnits', 'strokeWidth') .attr('markerUnits', 'strokeWidth')
.attr('markerWidth', 8) .attr('markerWidth', 8)
.attr('markerHeight', 6) .attr('markerHeight', 6)
.attr('orient', 'auto') .attr('orient', 'auto')
var path = marker.append('path') var path = marker.append('path')
.attr('d', 'M 0 0 L 0 0 L 0 0 z') .attr('d', 'M 0 0 L 0 0 L 0 0 z')
dagreD3.util.applyStyle(path, edge[type + 'Style']) dagreD3.util.applyStyle(path, edge[type + 'Style'])
} }
// Override normal arrowhead defined in d3. Remove style & add class to allow css styling. // Override normal arrowhead defined in d3. Remove style & add class to allow css styling.
render.arrows().normal = function normal (parent, id, edge, type) { render.arrows().normal = function normal (parent, id, edge, type) {
var marker = parent.append('marker') var marker = parent.append('marker')
.attr('id', id) .attr('id', id)
.attr('viewBox', '0 0 10 10') .attr('viewBox', '0 0 10 10')
.attr('refX', 9) .attr('refX', 9)
.attr('refY', 5) .attr('refY', 5)
.attr('markerUnits', 'strokeWidth') .attr('markerUnits', 'strokeWidth')
.attr('markerWidth', 8) .attr('markerWidth', 8)
.attr('markerHeight', 6) .attr('markerHeight', 6)
.attr('orient', 'auto') .attr('orient', 'auto')
var path = marker.append('path') marker.append('path')
.attr('d', 'M 0 0 L 10 5 L 0 10 z') .attr('d', 'M 0 0 L 10 5 L 0 10 z')
.attr('class', 'arrowheadPath') .attr('class', 'arrowheadPath')
.style('stroke-width', 1) .style('stroke-width', 1)
.style('stroke-dasharray', '1,0') .style('stroke-dasharray', '1,0')
} }
// Set up an SVG group so that we can translate the final graph. // Set up an SVG group so that we can translate the final graph.
var svg = d3.select('#' + id) var svg = d3.select('#' + id)
// svgGroup = d3.select('#' + id + ' g'); // svgGroup = d3.select('#' + id + ' g');
// Run the renderer. This is what draws the final graph. // Run the renderer. This is what draws the final graph.
var element = d3.select('#' + id + ' g') var element = d3.select('#' + id + ' g')
render(element, g) render(element, g)
// var tip = d3.tip().html(function(d) { return d; }); // var tip = d3.tip().html(function(d) { return d; });
element.selectAll('g.node') element.selectAll('g.node')
.attr('title', function () { .attr('title', function () {
return graph.getTooltip(this.id) return graph.getTooltip(this.id)
}) })
/* /*
var xPos = document.querySelectorAll('.clusters rect')[0].x.baseVal.value; var xPos = document.querySelectorAll('.clusters rect')[0].x.baseVal.value;
var width = document.querySelectorAll('.clusters rect')[0].width.baseVal.value; var width = document.querySelectorAll('.clusters rect')[0].width.baseVal.value;
var cluster = d3.selectAll('.cluster'); var cluster = d3.selectAll('.cluster');
var te = cluster.append('text'); var te = cluster.append('text');
te.attr('x', xPos+width/2); te.attr('x', xPos+width/2);
te.attr('y', 12); te.attr('y', 12);
//te.stroke('black'); //te.stroke('black');
te.attr('id', 'apa12'); te.attr('id', 'apa12');
te.style('text-anchor', 'middle'); te.style('text-anchor', 'middle');
te.text('Title for cluster'); te.text('Title for cluster');
*/ */
if (conf.useMaxWidth) { if (conf.useMaxWidth) {
// Center the graph // Center the graph
svg.attr('height', '100%') svg.attr('height', '100%')
svg.attr('width', conf.width) svg.attr('width', conf.width)
// svg.attr('viewBox', svgb.getBBox().x + ' 0 '+ g.graph().width+' '+ g.graph().height); // svg.attr('viewBox', svgb.getBBox().x + ' 0 '+ g.graph().width+' '+ g.graph().height);
svg.attr('viewBox', '0 0 ' + (g.graph().width + 20) + ' ' + (g.graph().height + 20)) svg.attr('viewBox', '0 0 ' + (g.graph().width + 20) + ' ' + (g.graph().height + 20))
svg.attr('style', 'max-width:' + (g.graph().width + 20) + 'px;') svg.attr('style', 'max-width:' + (g.graph().width + 20) + 'px;')
} else { } else {
// Center the graph // Center the graph
svg.attr('height', g.graph().height) svg.attr('height', g.graph().height)
if (typeof conf.width === 'undefined') { if (typeof conf.width === 'undefined') {
svg.attr('width', g.graph().width) svg.attr('width', g.graph().width)
} else { } else {
svg.attr('width', conf.width) svg.attr('width', conf.width)
} }
// svg.attr('viewBox', svgb.getBBox().x + ' 0 '+ g.graph().width+' '+ g.graph().height); // svg.attr('viewBox', svgb.getBBox().x + ' 0 '+ g.graph().width+' '+ g.graph().height);
svg.attr('viewBox', '0 0 ' + (g.graph().width + 20) + ' ' + (g.graph().height + 20)) svg.attr('viewBox', '0 0 ' + (g.graph().width + 20) + ' ' + (g.graph().height + 20))
} }
// Index nodes // Index nodes
graph.indexNodes('subGraph' + i) graph.indexNodes('subGraph' + i)
for (i = 0; i < subGraphs.length; i++) { for (i = 0; i < subGraphs.length; i++) {
@ -485,7 +486,7 @@ exports.draw = function (text, id, isDot) {
if (subG.title !== 'undefined') { if (subG.title !== 'undefined') {
var clusterRects = document.querySelectorAll('#' + id + ' #' + subG.id + ' rect') var clusterRects = document.querySelectorAll('#' + id + ' #' + subG.id + ' rect')
// log.debug('looking up: #' + id + ' #' + subG.id) // log.debug('looking up: #' + id + ' #' + subG.id)
var clusterEl = document.querySelectorAll('#' + id + ' #' + subG.id) var clusterEl = document.querySelectorAll('#' + id + ' #' + subG.id)
var xPos = clusterRects[0].x.baseVal.value var xPos = clusterRects[0].x.baseVal.value
@ -503,20 +504,20 @@ exports.draw = function (text, id, isDot) {
if (typeof subG.title === 'undefined') { if (typeof subG.title === 'undefined') {
te.text('Undef') te.text('Undef')
} else { } else {
// te.text(subGraphs[subGraphs.length-i-1].title); // te.text(subGraphs[subGraphs.length-i-1].title);
te.text(subG.title) te.text(subG.title)
} }
} }
} }
// Add label rects for non html labels // Add label rects for non html labels
if (!conf.htmlLabels) { if (!conf.htmlLabels) {
var labels = document.querySelectorAll('#' + id + ' .edgeLabel .label') var labels = document.querySelectorAll('#' + id + ' .edgeLabel .label')
var i var k
for (i = 0; i < labels.length; i++) { for (k = 0; k < labels.length; k++) {
var label = labels[i] var label = labels[i]
// Get dimensions of label // Get dimensions of label
var dim = label.getBBox() var dim = label.getBBox()
var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect') var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect')