// @require variables:
if ('undefined' === typeof HTML_ID_REF_GRAPH) throw "Missing HTML_ID_REF_GRAPH";
if ('undefined' === typeof TYPENAME) throw "Missing TYPENAME";
if ('undefined' === typeof PRIMARY_KEY) throw "Missing PRIMARY_KEY";
// if ('undefined' === typeof FUNCTION_FETCH_CHILDRENS) throw "Missing FUNCTION_FETCH_CHILDRENS";
// if ('undefined' === typeof FUNCTION_FETCH_PARENTS) throw "Missing FUNCTION_FETCH_PARENTS";
// if ('undefined' === typeof JS_CHANNEL_UPDATE_NAME) throw "Missing JS_CHANNEL_UPDATE_NAME";
var DBG = DBG || 0;
var DBG_SANKEY = DBG_SANKEY || 0;
var SHOW_FLOW_DIAGRAM = SHOW_FLOW_DIAGRAM || 0;
var _isFullScreen = true; // TODO: get from arg
var _html = {
container: null,
top: null,
fullscreenBtn: null,
selected: null
}
var _nodes = new vis.DataSet(); // [ { id: '', label: '' }, ... ]
var _edges = new vis.DataSet(); // [ { id: '', from: '', to: '' }, ... ]
var _network = null; // graph object
if (SHOW_FLOW_DIAGRAM) {
var _sankeyNode = null;
var _sankeyLink = null;
var sankey = null;
var _sankeySvgNode = null;
var _sankeySvgWidth = 0;
var _sankeyHeight = 0;
var _sankeyFormatNumber = d3.format(",.0f");
var _sankeyFormat = function(d) { return _sankeyFormatNumber(d) + " TWh"; };
var _sankeyColor = d3.scaleOrdinal(d3.schemeCategory10);
}
var _todoGraphData = [ { nodes: [], edges: [] } ]; // data by levels
var _defaultWfsParams = {
resolve: 'all',
resolveDepth: 2,
}
if ('undefined' !== typeof WFS_URL) {
_defaultWfsParams['WFS_URL'] = WFS_URL
}
var _defaultVisJsOptions = {
nodes: {
shape: 'box'
},
interaction: {
dragNodes: false
},
physics: {
enabled: false
},
layout: {
hierarchical: {
direction: 'LR',
levelSeparation: 500, // hierarchical.levelSeparation Number 150 The distance between the different levels.
nodeSpacing: 50, // hierarchical.nodeSpacing Number 100 Minimum distance between nodes on the free axis. This is only for the initial layout. If you enable physics, the node distance there will be the effective node distance.
treeSpacing: 500, // hierarchical.treeSpacing Number 200 Distance between different trees (independent networks). This is only for the initial layout. If you enable physics, the repulsion model will denote the distance between the trees.
sortMethod: 'directed'
// hierarchical.enabled Boolean false Toggle the usage of the hierarchical layout system. If this option is not defined, it is set to true if any of the properties in this object are defined.
// hierarchical.blockShifting Boolean true Method for reducing whitespace. Can be used alone or together with edge minimization. Each node will check for whitespace and will shift it's branch along with it for as far as it can, respecting the nodeSpacing on any level. This is mainly for the initial layout. If you enable physics, they layout will be determined by the physics. This will greatly speed up the stabilization time though!
// hierarchical.edgeMinimization Boolean true Method for reducing whitespace. Can be used alone or together with block shifting. Enabling block shifting will usually speed up the layout process. Each node will try to move along its free axis to reduce the total length of it's edges. This is mainly for the initial layout. If you enable physics, they layout will be determined by the physics. This will greatly speed up the stabilization time though!
// hierarchical.parentCentralization Boolean true When true, the parents nodes will be centered again after the the layout algorithm has been finished.
// hierarchical.direction String 'UD' The direction of the hierarchical layout. The available options are: UD, DU, LR, RL. To simplify: up-down, down-up, left-right, right-left.
// hierarchical.sortMethod String 'hubsize' The algorithm used to ascertain the levels of the nodes based on the data. The possible options are: hubsize, directed.
//
// Hubsize takes the nodes with the most edges and puts them at the top. From that the rest of the hierarchy is evaluated.
//
// Directed adheres to the to and from data of the edges. A --> B so B is a level lower than A.
}
}
};
function dataMakeNode(params) {
var objectName = params.typeName.substr(params.typeName.indexOf(':') + 1)
var nodeId = objectName + '.' + params.primaryKey // TODO: primaryKey?
return {
id: nodeId,
label: makeShortLabel(nodeId), // TODO: get from schema assert @label attribute
group: objectName,
_loaded: true,
typeName: params.typeName,
primaryKey: params.primaryKey // TODO: _primaryKey
}
}
function dataMakeEdge(parentNodeId, nodeObject) {
return {
id: parentNodeId + nodeObject.id,
from: parentNodeId,
to: nodeObject.id,
}
}
function dataMakeXlinkNode(params) {
var objectName = params.typeName.substr(params.typeName.indexOf(':') + 1)
var nodeId = params.xlink.substr(params.xlink.indexOf('#') + 1)
var primaryKey = nodeId.substr(nodeId.lastIndexOf('.') + 1)
return {
id: nodeId,
label: makeShortLabel(nodeId) + ' (+)',
group: objectName,
_loaded: false,
typeName: params.typeName,
primaryKey: primaryKey
}
}
function dataMakeFetchMoreNode(params) {
// params = {
// parentNodeId: parentNodeId,
// type: json.type,
// objectName: objectName,
// ref: json,
// }
if(DBG)console.log('DBG dataMakeFetchMoreNode(params)', params)
var nodeId = params.parentNodeId+'fetch-more-features-'+params.type+'-on-' + params.objectName;
return {
id: nodeId,
label: 'Pobierz więcej (+)',
group: 'fetch-more-data', // params.objectName,
_loaded: false,
_type: 'ref',
parentNodeId: params.parentNodeId,
ref: params.ref,
// typeName: typeName,
// primaryKey: nodeId.substr(nodeId.lastIndexOf('.') + 1)
};
}
function dataMakeFetchMoreEdge(parentNodeId, fetchMoreNode) {
// @param parentNodeId - from node id
// @param fetchMoreNode - from dataMakeFetchMoreNode
if(DBG)console.log('DBG dataMakeFetchMoreEdge(parentNodeId, fetchMoreNode)', {parentNodeId:parentNodeId, fetchMoreNode:fetchMoreNode})
return {
id: fetchMoreNode.id,
from: parentNodeId,
to: fetchMoreNode.id
}
}
(function () {
var form = document.getElementById('wfs_request')
var featureTypeName = TYPENAME
var wfsParams = Object.assign({}, _defaultWfsParams, {
primaryKey: PRIMARY_KEY,
})
if(DBG)console.log('p5WFS_GetFeature', featureTypeName, wfsParams)
p5WFS_GetFeature(featureTypeName, wfsParams).then(function (features) {
if(DBG)console.log('features', features)
updateWfsResponse(features, featureTypeName)
if (SHOW_FLOW_DIAGRAM) updateSankeyDiagram()
}).catch(function (e) {
if(DBG)console.warn(e)
p5UI__notifyAjaxCallback({ type: 'error', msg: e })
})
if (SHOW_FLOW_DIAGRAM) {
_sankeySvgNode = document.getElementById("d3-sankey-test")
var d3SvgNode = d3.select(_sankeySvgNode);
var svgWidth = d3SvgNode.attr("width")
if ('%' === svgWidth.substr(-1)) {
svgWidth = parseInt(svgWidth.substr(0, svgWidth.length - 1))
svgWidth = (isNaN(svgWidth) || svgWidth > 100 || svgWidth < 0) ? 100 : svgWidth
var parentNodeStyle = getComputedStyle(_sankeySvgNode.parentNode)
var wrapNodeWidth = _sankeySvgNode.parentNode.clientWidth - parseFloat(parentNodeStyle.paddingLeft || 0) - parseFloat(parentNodeStyle.paddingRight || 0);
d3SvgNode.attr("width", (100 === svgWidth)
? wrapNodeWidth
: Math.floor(wrapNodeWidth * svgWidth / 100)
)
}
_sankeySvgWidth = parseInt(d3SvgNode.attr("width"));
_sankeyHeight = parseInt(d3SvgNode.attr("height"));
sankey = d3.sankey()
.nodeWidth(15)
.nodePadding(10)
.extent([ [ 1, 1 ], [ _sankeySvgWidth - 1, _sankeyHeight - 6 ] ]);
}
renderLayout()
})();
function updateWfsResponse(features, featureTypeName) {
if(DBG)console.log('updateWfsResponse', { features: features, featureTypeName: featureTypeName })
// if (_network !== null) {
// _network.destroy();
// _network = null;
// }
parseResponseRec(_todoGraphData, features, featureTypeName)
var _graphData = {
nodes: _nodes,
edges: _edges,
};
_todoGraphData.forEach(function (levelData, levelIdx) {
if (levelData.nodes && levelData.nodes.length) {
levelData.nodes.forEach(function (node) {
try {
_nodes.add(node)
} catch (e) {
if(DBG)console.log('_graphData.nodes.add [level='+levelIdx+'] error:', e);
}
})
}
if (levelData.edges && levelData.edges.length) {
levelData.edges.forEach(function (edge) {
try {
_edges.add(edge)
} catch (e) {
if(DBG)console.log('_graphData.edges.add [level='+levelIdx+'] error:', e);
}
})
}
})
_todoGraphData = [ { nodes: [], edges: [] } ]; // clear to default values
var options = _defaultVisJsOptions
if(DBG)console.log('_graphData', _graphData)
if (!_network) {
_network = new vis.Network(_html['container'], _graphData, options); // graphData: { nodes: [], edges: [] }
// add event listeners
_network.on('selectNode', function (params) {
if(DBG)console.log('Selection: ', params.nodes)
var featureID = params.nodes[0]
if (!featureID) return;
if ('-loading' === featureID.substr(-1 * '-loading'.length)) {
// TODO: gui msg...
if(DBG)console.log('loading nodes connected with: "' +featureID.substr(0, featureID.length - '-loading'.length) + '" ...')
return;
}
var selectedNode = _nodes.get(featureID)
if(DBG)console.log('Selection: selectedNode:', selectedNode)
if (!selectedNode) return;
if ('ref' === selectedNode._type) {
fetchNodeMoreRefs(selectedNode, featureID)
} else {
renderSelectedNode(selectedNode)
if (selectedNode._loaded) return;
fetchNodeRecurse(selectedNode, featureID)
}
});
}
}
function isP5LinkObject(json) {
if ( !('type' in json) || !json['type'] ) return false;
if ( !('value' in json) || !json['value'] ) return false;
if ( !('@typeName' in json) || !json['@typeName'] ) return false;
if ( !('@startIndex' in json) || !json['@startIndex'] ) return false;
if ( !('@backRefPK' in json) || !json['@backRefPK'] ) return false;
if ( !('@backRefNS' in json) || !json['@backRefNS'] ) return false;
return true;
}
function parseResponseRec(_todoGraphData, json, typeName, parentNodeId, level) {
var level = level || 0
var parentNodeId = parentNodeId || null
if(DBG)console.log('DBG::parseResponseRec', {json:json, typeName:typeName, parentNodeId:parentNodeId, isString: p5Utils__isString(json), isArray: p5Utils__isArray(json), isObject: p5Utils__isObject(json)});
if (p5Utils__isArray(json)) {
// TODO: create named group
var isXlinkList = (json.length > 0 && p5Utils__isString(json[0]))
json.forEach(function (subJson) {
if (isXlinkList) {
parseResponseXlinkListRec(_todoGraphData, subJson, typeName, parentNodeId, level)
} else {
parseResponseRec(_todoGraphData, subJson, typeName, parentNodeId, level)
}
})
} else if (p5Utils__isObject(json) && isP5LinkObject(json)) {
if(DBG)console.log('DBG::parseResponseRec isP5LinkObject');
parseResponseP5Link(_todoGraphData, json, typeName, parentNodeId, level)
} else if (p5Utils__isObject(json)) {
// _todoGraphData.nodes.add({ id: nodeId, label: nodeId })
if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
var nodeObject = dataMakeNode({
typeName: typeName,
primaryKey: (json['ID']) ? json['ID'] : null, // TODO: get primaryKey from object
})
var nodeId = nodeObject.id
_todoGraphData[level].nodes.push(nodeObject)
if (parentNodeId) {
_todoGraphData[level].edges.push(dataMakeEdge(parentNodeId, nodeObject))
}
Object.keys(json).filter(function (fieldName) {
return (fieldName.indexOf(':') > -1)
})
.forEach(function (fieldName) {
var value = json[fieldName]
parseResponseRec(_todoGraphData, value, fieldName, nodeId, level + 1)
})
} else if (p5Utils__isString(json)) {
if(DBG)console.log('TODO: Not implemented - parseResponseRec isString');
} else {
if(DBG)console.log('TODO: Not implemented - parseResponseRec is not string, not array and not object');
}
}
function parseResponseXlinkListRec(_todoGraphData, json, typeName, parentNodeId, level) {
if(DBG)console.log('DBG::parseResponseRec:XlinkList', {json:json, typeName:typeName, parentNodeId:parentNodeId, isString: p5Utils__isString(json), isArray: p5Utils__isArray(json), isObject: p5Utils__isObject(json)});
if (p5Utils__isString(json)) { // xlink "https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI#BI_audit_ENERGA_RUM_KONTRAHENCI.9233",
var nodeId = json.substr(json.indexOf('#') + 1)
{
// _graphData.nodes.add({ id: nodeId, label: nodeId })
if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
var nodeObject = dataMakeXlinkNode({
xlink: json,
typeName: typeName,
primaryKey: (json['ID']) ? json['ID'] : null, // TODO: get primaryKey from object
})
_todoGraphData[level].nodes.push(nodeObject)
if (parentNodeId) {
_todoGraphData[level].edges.push(dataMakeEdge(parentNodeId, nodeObject))
}
}
} else if (p5Utils__isObject(json) && isP5LinkObject(json)) {
parseResponseP5Link(_todoGraphData, json, typeName, parentNodeId, level)
} else {
if(DBG)console.log('TODO: Not implemented - parseResponseRec:XlinkList is not string and not object');
}
}
function parseResponseP5Link(_todoGraphData, json, typeName, parentNodeId, level) {
if(DBG)console.log('parseResponseRec isObject and P5Link - fetch more xlink object');
// example json: { type: "next",
// @backRefNS: "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA",
// @backRefPK: "42",
// @typeName: "default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_P…ow:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row",
// @startIndex: "10" }
if (!parentNodeId) throw "Missing parentNodeId for ref link object";
var objectName = typeName.substr(typeName.indexOf(':') + 1)
{
// _graphData.nodes.add({ id: nodeId, label: nodeId })
if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
switch (json.type) {
case 'next': {
var nodeObject = dataMakeFetchMoreNode({
parentNodeId: parentNodeId,
type: json.type,
objectName: objectName,
ref: json,
})
_todoGraphData[level].nodes.push(nodeObject)
_todoGraphData[level].edges.push(dataMakeFetchMoreEdge(parentNodeId, nodeObject))
} break;
default: {
if(DBG)console.log('TODO: Not implemented - parseResponseRec isObject with type "'+json.type+'" - fetch more xlink object');
}
}
}
}
function fetchNodeMoreRefs(selectedNode, featureID) {
try {
if (!selectedNode) throw "Missing featureID"
if (!featureID) throw "Missing featureID"
if (!selectedNode.ref) throw "Missing selectedNode.ref"
var idSelectedNode = selectedNode.id
var idSelectedEdge = selectedNode.id
var parentNodeId = selectedNode.parentNodeId
var featureTypeName = selectedNode.ref['@typeName']
var backRefNS = selectedNode.ref['@backRefNS']
var backRefPK = selectedNode.ref['@backRefPK']
var backRefField = selectedNode.ref['@typeName']
var startIndex = selectedNode.ref['@startIndex']
if(DBG)console.log('DBG:fetch: fetchNodeMoreRefs', { 'selectedNode': selectedNode, 'featureID': featureID });
_nodes.update({
id: idSelectedNode,
label: "Pobieranie danych..."
})
var wfsParams = {
backRefNS: backRefNS,
backRefPK: backRefPK,
backRefField: backRefField,
startIndex: startIndex,
maxFeatures: 10,
};
p5WFS_GetFeature(featureTypeName, wfsParams).then(function (features) {
if(DBG)console.log('features', features)
if (!features.length) throw "Brak danych"
features.forEach(function (feature) {
// TODO: validate
var objectName = featureTypeName.substr(featureTypeName.indexOf(':') + 1)
var nodeId = objectName + '.' + feature.ID // TODO: primaryKey?
_todoGraphData[0].edges.push({ id: parentNodeId + nodeId, from: parentNodeId, to: nodeId })
})
// var refFields = Object.keys(features[0]).filter(function (fieldName) {
// return (fieldName.indexOf(':') > -1)
// }).filter(function (fieldName) {
// return (features[0][fieldName].length > 0)
// })
// if (!refFields.length) return "Brak danych"
// features = features.map(function (feature) {
// return {
// feature
// }
// })
// console.log('TODO: features: ', features);
// updateWfsResponse(features[0], featureTypeName) // TODO: RMME DBG
// updateWfsResponse(features[1], featureTypeName) // TODO: RMME DBG
// var feature = features[1]
// var nodeId = featureTypeName + '.' + feature['ID']
// try {
// _edges.add({
// id: parentNodeId + nodeId,
// from: parentNodeId,
// to: nodeId
// })
// } catch (e) {
// if(DBG)console.warn('TODO: XXX: ' + e)
// }
features.forEach(function (feature) {
updateWfsResponse(feature, featureTypeName)
})
var nodeSelectedData = _nodes.get(idSelectedNode)
var edgeSelectedData = _nodes.get(idSelectedEdge)
_nodes.remove({ id: idSelectedNode })
_edges.remove({ id: idSelectedEdge })
if (features.length >= 10) {
var nodeObject = dataMakeFetchMoreNode({
parentNodeId: nodeSelectedData.parentNodeId,
type: nodeSelectedData.type,
objectName: nodeSelectedData.objectName,
ref: Object.assign(nodeSelectedData.ref, {
'@startIndex': (10 + parseInt(startIndex)),
value: nodeSelectedData.ref.value.replace('startIndex=' + startIndex, 'startIndex=' + (10 + parseInt(startIndex)))
})
})
_nodes.add(nodeObject)
_edges.add(dataMakeFetchMoreEdge(parentNodeId, nodeObject))
}
updateSankeyDiagram()
return "Pobrano nowe dane"
}).then(function (msg) {
p5UI__notifyAjaxCallback({ type: 'info', msg: msg })
}).catch(function (e) {
if(DBG)console.warn(e)
p5UI__notifyAjaxCallback({ type: 'error', msg: e })
_nodes.remove({ id: idSelectedNode })
_edges.remove({ id: idSelectedEdge })
})
} catch (e) {
if(DBG)console.warn(e)
}
}
function fetchNodeRecurse(selectedNode, featureID) {
try {
var selectedNodeId = selectedNode.id
if (!selectedNode) throw "Missing featureID"
if (!featureID) throw "Missing featureID"
var featureEx = featureID.split('.')
if (2 !== featureEx.length) throw "Not supported featureID format"
var featureTypeName = selectedNode.typeName; // 'default_db__x3A__' + featureEx[0] + ':' + featureEx[0]
var wfsParams = Object.assign({}, _defaultWfsParams, {
primaryKey: featureEx[1]
});
if(DBG)console.log('DBG:fetch: fetchNodeRecurse', { 'selectedNode': selectedNode, 'featureID': featureID });
// view-source:http://visjs.org/examples/network/data/dynamicData.html
_nodes.update({
id: featureID,
label: makeShortLabel(selectedNodeId) + ' ...'
})
p5WFS_GetFeature(featureTypeName, wfsParams).then(function (features) {
if(DBG)console.log('features', features)
if (!features.length || 1 !== features.length) throw "Brak danych" // require 1 feature with recurse
var refFields = Object.keys(features[0]).filter(function (fieldName) {
return (fieldName.indexOf(':') > -1)
}).filter(function (fieldName) {
return (features[0][fieldName].length > 0)
})
if (!refFields.length) return "Brak danych"
updateWfsResponse(features, featureTypeName)
updateSankeyDiagram()
return "Pobrano nowe dane"
}).then(function (msg) {
p5UI__notifyAjaxCallback({ type: 'info', msg: msg })
_nodes.update({ id: featureID, label: makeShortLabel(selectedNodeId), _loaded: true })
}).catch(function (e) {
if(DBG)console.warn(e)
p5UI__notifyAjaxCallback({ type: 'error', msg: e })
_nodes.update({ id: featureID, label: makeShortLabel(selectedNodeId), _loaded: true })
})
} catch (e) {
if(DBG)console.warn(e)
}
}
function makeShortLabel(label) { // TODO: shorter name
// BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.1234567
if (label.length < 30) return label;
var exLabel = label.split('.')
if (exLabel.length !== 2) return label;
return exLabel[0].substr(0, 24) + '...' + exLabel[0].substr(-10) + '.' + exLabel[1];
}
function renderLayout(mode) {
if ('undefined' !== typeof mode && _isFullScreen !== mode) _isFullScreen = mode
// create a network
if (!_html['container']) {
_html['container'] = document.getElementById(HTML_ID_REF_GRAPH)
}
_html['container'].style.position = (_isFullScreen) ? 'fixed' : 'relative'
_html['container'].style.top = (_isFullScreen) ? '40px' : ''
_html['container'].style.left = '0px'
_html['container'].style.margin = '0'
_html['container'].style.border = (_isFullScreen) ? '0' : '1px solid silver'
_html['container'].style.padding = '0'
_html['container'].style.backgroundColor = '#fff'
_html['container'].style.height = (_isFullScreen) ? ''+(window.innerHeight-40)+'px' : ''+(window.innerHeight-60-_html['container'].offsetTop)+'px'
_html['container'].style.width = (_isFullScreen) ? '' + (window.innerWidth) + 'px' : '100%'
if (!_html['top']) {
_html['top'] = document.createElement('div')
_html['container'].parentNode.insertBefore(_html['top'], _html['container'].nextSibling)
}
_html['top'].style.position = (_isFullScreen) ? 'fixed' : 'relative'
_html['top'].style.top = '0px'
_html['top'].style.left = '0px'
_html['top'].style.margin = '0'
_html['top'].style.border = '0'
_html['top'].style.padding = '0'
_html['top'].style.backgroundColor = '#101010'
_html['top'].style.height = '40px'
_html['top'].style.width = (_isFullScreen) ? '' + (window.innerWidth) + 'px' : '100%'
_html['top'].style.zIndex = 3
if (!_html['fullscreenBtn']) {
_html['fullscreenBtn'] = document.createElement('button')
_html['fullscreenBtn'].className = 'btn btn-lg btn-link'
_html['top'].appendChild(_html['fullscreenBtn'])
_html['fullscreenBtn'].style.color = '#fff'
_html['fullscreenBtn'].style.float = 'right'
_html['fullscreenBtn'].style.outline = 'none'
_html['fullscreenBtn'].addEventListener('click', function () {
_isFullScreen = !_isFullScreen
renderLayout()
})
}
_html['fullscreenBtn'].innerHTML = (_isFullScreen)
? ''
: ''
;
if (!_html['selected']) {
_html['selected'] = document.createElement('span')
var htmlSelectedWrap = document.createElement('div')
htmlSelectedWrap.style.color = '#fff'
htmlSelectedWrap.style.fontSize = '14px'
htmlSelectedWrap.style.lineHeight = '40px'
htmlSelectedWrap.style.paddingLeft = '12px'
htmlSelectedWrap.appendChild(document.createTextNode("Wybrany: "))
htmlSelectedWrap.appendChild(_html['selected'])
_html['top'].appendChild(htmlSelectedWrap)
_html['selected'].innerHTML = 'brak'
}
}
function renderSelectedNode(node) {
var gotToTableLink = (node.typeName)
? '' +
'' +
''
: ''
;
var editLink = (node.typeName && node.primaryKey)
? '' +
'' +
''
: ''
;
_html['selected'].innerHTML = '' + node.id + ' ' + gotToTableLink + ' ' + editLink;
}
function updateSankeyDiagram() {
if(DBG||DBG_SANKEY)console.log('DBG:sankey: updateSankeyDiagram..');
if (!SHOW_FLOW_DIAGRAM || !sankey) return;
// var sankeyData = { // example
// nodes: [
// /* 0 */ { name: "A" },
// /* 1 */ { name: "B" },
// /* 2 */ { name: "C" },
// /* 3 */ { name: "D" },
// /* 4 */ { name: "E" },
// /* 5 */ { name: "F" },
// ],
// links: [
// { "source": 0, "target": 1, "value": 100 },
// { "source": 1, "target": 2, "value": 100 },
// { "source": 2, "target": 3, "value": 100 },
// { "source": 3, "target": 4, "value": 100 },
// { "source": 5, "target": 2, "value": 100 },
// { "source": 0, "target": 4, "value": 100 },
// ]
// }
p5Utils__clearNode(_sankeySvgNode)
var d3SvgNode = d3.select(_sankeySvgNode);
_sankeyLink = d3SvgNode.append("g")
.attr("class", "links")
.attr("fill", "none")
.attr("stroke", "#000")
.attr("stroke-opacity", 0.2)
.selectAll("path");
_sankeyNode = d3SvgNode.append("g")
.attr("class", "nodes")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("g");
// var sankeyInstance = sankey(sankeyData);
var mapVisNodeIdToIdx = _nodes.getIds().reduce(function (ret, id, idx) {
ret[id] = idx;
return ret;
}, {});
// TODO: fix - count from leaf's to root's
var countOutLinks = _edges.get().reduce(function (ret, edge) {
if (!mapVisNodeIdToIdx.hasOwnProperty(edge.from)) throw "Missing to in mapVisNodeIdToIdx["+edge.from+"]"
var idxTarget = mapVisNodeIdToIdx[edge.from]
ret[idxTarget] = (ret[idxTarget] > 0) ? ret[idxTarget] + 1 : 1
// if(DBG||DBG_SANKEY)console.log('DBG:sankey: countOutLinks reduce', edge, ret);
return ret
}, {})
if(DBG||DBG_SANKEY)console.log('DBG:sankey: countOutLinks', Object.keys(countOutLinks).map(function (idx) {
return '' + _nodes.get()[idx].label + ' ('+countOutLinks[idx]+')';
}));
var sankeyInstance = sankey({
nodes: _nodes.map(function (node) {
if(DBG||DBG_SANKEY)console.log('DBG:sankey: loop nodes');
return {
name: node.label
}
}),
links: _edges.map(function (edge) {
if(DBG||DBG_SANKEY)console.log('DBG:sankey: loop links');
if (!mapVisNodeIdToIdx.hasOwnProperty(edge.from)) throw "Missing from in mapVisNodeIdToIdx["+edge.from+"]"
if (!mapVisNodeIdToIdx.hasOwnProperty(edge.to)) throw "Missing to in mapVisNodeIdToIdx["+edge.to+"]"
var idxTarget = mapVisNodeIdToIdx[edge.to]
return {
source: mapVisNodeIdToIdx[edge.from],
target: idxTarget,
value: (countOutLinks[idxTarget] || 1) * 10
}
}),
});
if(DBG||DBG_SANKEY)console.log('DBG:sankey: sankeyInstance created');
// var sankeyInstance = sankey()
// .nodes(
// _nodes.map(function (node) {
// return {
// name: node.label
// }
// })
// )
// .edges(
// _edges.map(function (edge) {
// if (!mapVisNodeIdToIdx.hasOwnProperty(edge.from)) throw "Missing from in mapVisNodeIdToIdx["+edge.from+"]"
// if (!mapVisNodeIdToIdx.hasOwnProperty(edge.to)) throw "Missing to in mapVisNodeIdToIdx["+edge.to+"]"
// var idxTarget = mapVisNodeIdToIdx[edge.to]
// return {
// source: mapVisNodeIdToIdx[edge.from],
// target: idxTarget,
// value: (countOutLinks[idxTarget] || 1) * 10
// }
// })
// )
// .layout(32);
_sankeyLink = _sankeyLink
.data(sankeyInstance.links)
.enter().append("path")
.attr("d", d3.sankeyLinkHorizontal())
.attr("stroke-width", function(d) { return Math.max(1, d.width); });
_sankeyLink.append("title")
.text(function(d) { return d.source.name + " → " + d.target.name + "\n" + _sankeyFormat(d.value); });
_sankeyNode = _sankeyNode
.data(sankeyInstance.nodes)
.enter().append("g");
_sankeyNode.append("rect")
.attr("x", function(d) { return d.x0; })
.attr("y", function(d) { return d.y0; })
.attr("height", function(d) { return d.y1 - d.y0; })
.attr("width", function(d) { return d.x1 - d.x0; })
.attr("fill", function(d) { return _sankeyColor(d.name.replace(/ .*/, "")); })
.attr("stroke", "#000");
_sankeyNode.append("text")
.attr("x", function(d) { return d.x0 - 6; })
.attr("y", function(d) { return (d.y1 + d.y0) / 2; })
.attr("dy", "0.35em")
.attr("text-anchor", "end")
.text(function(d) { return d.name; })
.filter(function(d) { return d.x0 < _sankeySvgWidth / 2; })
.attr("x", function(d) { return d.x1 + 6; })
.attr("text-anchor", "start");
_sankeyNode.append("title")
.text(function(d) { return d.name + "\n" + _sankeyFormat(d.value); });
}
// global['FUNCTION_FETCH_CHILDRENS'] = 'refGraphFetchChildrens'
// global['FUNCTION_FETCH_PARENTS'] = 'refGraphFetchParents'
// global['_nodes'] = _nodes // TODO: DBG
// global['_edges'] = _edges // TODO: DBG