RefGraph.php.view.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. // @require variables:
  2. if ('undefined' === typeof HTML_ID_REF_GRAPH) throw "Missing HTML_ID_REF_GRAPH";
  3. if ('undefined' === typeof TYPENAME) throw "Missing TYPENAME";
  4. if ('undefined' === typeof PRIMARY_KEY) throw "Missing PRIMARY_KEY";
  5. // if ('undefined' === typeof FUNCTION_FETCH_CHILDRENS) throw "Missing FUNCTION_FETCH_CHILDRENS";
  6. // if ('undefined' === typeof FUNCTION_FETCH_PARENTS) throw "Missing FUNCTION_FETCH_PARENTS";
  7. // if ('undefined' === typeof JS_CHANNEL_UPDATE_NAME) throw "Missing JS_CHANNEL_UPDATE_NAME";
  8. var DBG = DBG || 0;
  9. var SHOW_FLOW_DIAGRAM = SHOW_FLOW_DIAGRAM || 0;
  10. var _isFullScreen = true; // TODO: get from arg
  11. var _html = {
  12. container: null,
  13. top: null,
  14. fullscreenBtn: null,
  15. selected: null
  16. }
  17. var _nodes = new vis.DataSet(); // [ { id: '', label: '' }, ... ]
  18. var _edges = new vis.DataSet(); // [ { id: '', from: '', to: '' }, ... ]
  19. var _network = null; // graph object
  20. if (SHOW_FLOW_DIAGRAM) {
  21. var _sankeyNode = null;
  22. var _sankeyLink = null;
  23. var sankey = null;
  24. var _sankeySvgNode = null;
  25. var _sankeySvgWidth = 0;
  26. var _sankeyHeight = 0;
  27. var _sankeyFormatNumber = d3.format(",.0f");
  28. var _sankeyFormat = function(d) { return _sankeyFormatNumber(d) + " TWh"; };
  29. var _sankeyColor = d3.scaleOrdinal(d3.schemeCategory10);
  30. }
  31. var _todoGraphData = [ { nodes: [], edges: [] } ]; // data by levels
  32. var _defaultWfsParams = {
  33. resolve: 'all',
  34. resolveDepth: 2,
  35. }
  36. if ('undefined' !== typeof WFS_URL) {
  37. _defaultWfsParams['WFS_URL'] = WFS_URL
  38. }
  39. var _defaultVisJsOptions = {
  40. nodes: {
  41. shape: 'box'
  42. },
  43. interaction: {
  44. dragNodes: false
  45. },
  46. physics: {
  47. enabled: false
  48. },
  49. layout: {
  50. hierarchical: {
  51. direction: 'LR',
  52. levelSeparation: 500, // hierarchical.levelSeparation Number 150 The distance between the different levels.
  53. 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.
  54. 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.
  55. sortMethod: 'directed'
  56. // 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.
  57. // 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!
  58. // 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!
  59. // hierarchical.parentCentralization Boolean true When true, the parents nodes will be centered again after the the layout algorithm has been finished.
  60. // 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.
  61. // hierarchical.sortMethod String 'hubsize' The algorithm used to ascertain the levels of the nodes based on the data. The possible options are: hubsize, directed.
  62. //
  63. // Hubsize takes the nodes with the most edges and puts them at the top. From that the rest of the hierarchy is evaluated.
  64. //
  65. // Directed adheres to the to and from data of the edges. A --> B so B is a level lower than A.
  66. }
  67. }
  68. };
  69. function dataMakeNode(params) {
  70. var objectName = params.typeName.substr(params.typeName.indexOf(':') + 1)
  71. var nodeId = objectName + '.' + params.primaryKey // TODO: primaryKey?
  72. return {
  73. id: nodeId,
  74. label: makeShortLabel(nodeId), // TODO: get from schema assert @label attribute
  75. group: objectName,
  76. _loaded: true,
  77. typeName: params.typeName,
  78. primaryKey: params.primaryKey // TODO: _primaryKey
  79. }
  80. }
  81. function dataMakeEdge(parentNodeId, nodeObject) {
  82. return {
  83. id: parentNodeId + nodeObject.id,
  84. from: parentNodeId,
  85. to: nodeObject.id,
  86. }
  87. }
  88. function dataMakeXlinkNode(params) {
  89. var objectName = params.typeName.substr(params.typeName.indexOf(':') + 1)
  90. var nodeId = params.xlink.substr(params.xlink.indexOf('#') + 1)
  91. var primaryKey = nodeId.substr(nodeId.lastIndexOf('.') + 1)
  92. return {
  93. id: nodeId,
  94. label: makeShortLabel(nodeId) + ' (+)',
  95. group: objectName,
  96. _loaded: false,
  97. typeName: params.typeName,
  98. primaryKey: primaryKey
  99. }
  100. }
  101. function dataMakeFetchMoreNode(params) {
  102. // params = {
  103. // parentNodeId: parentNodeId,
  104. // type: json.type,
  105. // objectName: objectName,
  106. // ref: json,
  107. // }
  108. if(DBG)console.log('DBG dataMakeFetchMoreNode(params)', params)
  109. var nodeId = params.parentNodeId+'fetch-more-features-'+params.type+'-on-' + params.objectName;
  110. return {
  111. id: nodeId,
  112. label: 'Pobierz więcej (+)',
  113. group: 'fetch-more-data', // params.objectName,
  114. _loaded: false,
  115. _type: 'ref',
  116. parentNodeId: params.parentNodeId,
  117. ref: params.ref,
  118. // typeName: typeName,
  119. // primaryKey: nodeId.substr(nodeId.lastIndexOf('.') + 1)
  120. };
  121. }
  122. function dataMakeFetchMoreEdge(parentNodeId, fetchMoreNode) {
  123. // @param parentNodeId - from node id
  124. // @param fetchMoreNode - from dataMakeFetchMoreNode
  125. if(DBG)console.log('DBG dataMakeFetchMoreEdge(parentNodeId, fetchMoreNode)', {parentNodeId:parentNodeId, fetchMoreNode:fetchMoreNode})
  126. return {
  127. id: fetchMoreNode.id,
  128. from: parentNodeId,
  129. to: fetchMoreNode.id
  130. }
  131. }
  132. (function () {
  133. var form = document.getElementById('wfs_request')
  134. var featureTypeName = TYPENAME
  135. var wfsParams = Object.assign({}, _defaultWfsParams, {
  136. primaryKey: PRIMARY_KEY,
  137. })
  138. if(DBG)console.log('p5WFS_GetFeature', featureTypeName, wfsParams)
  139. p5WFS_GetFeature(featureTypeName, wfsParams).then(function (features) {
  140. if(DBG)console.log('features', features)
  141. updateWfsResponse(features, featureTypeName)
  142. updateSankeyDiagram()
  143. }).catch(function (e) {
  144. if(DBG)console.warn(e)
  145. p5UI__notifyAjaxCallback({ type: 'error', msg: e })
  146. })
  147. if (SHOW_FLOW_DIAGRAM) {
  148. _sankeySvgNode = document.getElementById("d3-sankey-test")
  149. var d3SvgNode = d3.select(_sankeySvgNode);
  150. var svgWidth = d3SvgNode.attr("width")
  151. if ('%' === svgWidth.substr(-1)) {
  152. svgWidth = parseInt(svgWidth.substr(0, svgWidth.length - 1))
  153. svgWidth = (isNaN(svgWidth) || svgWidth > 100 || svgWidth < 0) ? 100 : svgWidth
  154. var parentNodeStyle = getComputedStyle(_sankeySvgNode.parentNode)
  155. var wrapNodeWidth = _sankeySvgNode.parentNode.clientWidth - parseFloat(parentNodeStyle.paddingLeft || 0) - parseFloat(parentNodeStyle.paddingRight || 0);
  156. d3SvgNode.attr("width", (100 === svgWidth)
  157. ? wrapNodeWidth
  158. : Math.floor(wrapNodeWidth * svgWidth / 100)
  159. )
  160. }
  161. _sankeySvgWidth = parseInt(d3SvgNode.attr("width"));
  162. _sankeyHeight = parseInt(d3SvgNode.attr("height"));
  163. sankey = d3.sankey()
  164. .nodeWidth(15)
  165. .nodePadding(10)
  166. .extent([ [ 1, 1 ], [ _sankeySvgWidth - 1, _sankeyHeight - 6 ] ]);
  167. }
  168. renderLayout()
  169. })();
  170. function updateWfsResponse(features, featureTypeName) {
  171. if(DBG)console.log('updateWfsResponse', { features: features, featureTypeName: featureTypeName })
  172. // if (_network !== null) {
  173. // _network.destroy();
  174. // _network = null;
  175. // }
  176. parseResponseRec(_todoGraphData, features, featureTypeName)
  177. var _graphData = {
  178. nodes: _nodes,
  179. edges: _edges,
  180. };
  181. _todoGraphData.forEach(function (levelData, levelIdx) {
  182. if (levelData.nodes && levelData.nodes.length) {
  183. levelData.nodes.forEach(function (node) {
  184. try {
  185. _nodes.add(node)
  186. } catch (e) {
  187. if(DBG)console.log('_graphData.nodes.add [level='+levelIdx+'] error:', e);
  188. }
  189. })
  190. }
  191. if (levelData.edges && levelData.edges.length) {
  192. levelData.edges.forEach(function (edge) {
  193. try {
  194. _edges.add(edge)
  195. } catch (e) {
  196. if(DBG)console.log('_graphData.edges.add [level='+levelIdx+'] error:', e);
  197. }
  198. })
  199. }
  200. })
  201. _todoGraphData = [ { nodes: [], edges: [] } ]; // clear to default values
  202. var options = _defaultVisJsOptions
  203. if(DBG)console.log('_graphData', _graphData)
  204. if (!_network) {
  205. _network = new vis.Network(_html['container'], _graphData, options); // graphData: { nodes: [], edges: [] }
  206. // add event listeners
  207. _network.on('selectNode', function (params) {
  208. if(DBG)console.log('Selection: ', params.nodes)
  209. var featureID = params.nodes[0]
  210. if (!featureID) return;
  211. if ('-loading' === featureID.substr(-1 * '-loading'.length)) {
  212. // TODO: gui msg...
  213. if(DBG)console.log('loading nodes connected with: "' +featureID.substr(0, featureID.length - '-loading'.length) + '" ...')
  214. return;
  215. }
  216. var selectedNode = _nodes.get(featureID)
  217. if(DBG)console.log('Selection: selectedNode:', selectedNode)
  218. if (!selectedNode) return;
  219. if ('ref' === selectedNode._type) {
  220. fetchNodeMoreRefs(selectedNode, featureID)
  221. } else {
  222. renderSelectedNode(selectedNode)
  223. if (selectedNode._loaded) return;
  224. fetchNodeRecurse(selectedNode, featureID)
  225. }
  226. });
  227. }
  228. }
  229. function isP5LinkObject(json) {
  230. if ( !('type' in json) || !json['type'] ) return false;
  231. if ( !('value' in json) || !json['value'] ) return false;
  232. if ( !('@typeName' in json) || !json['@typeName'] ) return false;
  233. if ( !('@startIndex' in json) || !json['@startIndex'] ) return false;
  234. if ( !('@backRefPK' in json) || !json['@backRefPK'] ) return false;
  235. if ( !('@backRefNS' in json) || !json['@backRefNS'] ) return false;
  236. return true;
  237. }
  238. function parseResponseRec(_todoGraphData, json, typeName, parentNodeId, level) {
  239. var level = level || 0
  240. var parentNodeId = parentNodeId || null
  241. if(DBG)console.log('DBG::parseResponseRec', {json:json, typeName:typeName, parentNodeId:parentNodeId, isString: p5Utils__isString(json), isArray: p5Utils__isArray(json), isObject: p5Utils__isObject(json)});
  242. if (p5Utils__isArray(json)) {
  243. // TODO: create named group
  244. var isXlinkList = (json.length > 0 && p5Utils__isString(json[0]))
  245. json.forEach(function (subJson) {
  246. if (isXlinkList) {
  247. parseResponseXlinkListRec(_todoGraphData, subJson, typeName, parentNodeId, level)
  248. } else {
  249. parseResponseRec(_todoGraphData, subJson, typeName, parentNodeId, level)
  250. }
  251. })
  252. } else if (p5Utils__isObject(json) && isP5LinkObject(json)) {
  253. if(DBG)console.log('DBG::parseResponseRec isP5LinkObject');
  254. parseResponseP5Link(_todoGraphData, json, typeName, parentNodeId, level)
  255. } else if (p5Utils__isObject(json)) {
  256. // _todoGraphData.nodes.add({ id: nodeId, label: nodeId })
  257. if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
  258. var nodeObject = dataMakeNode({
  259. typeName: typeName,
  260. primaryKey: (json['ID']) ? json['ID'] : null, // TODO: get primaryKey from object
  261. })
  262. var nodeId = nodeObject.id
  263. _todoGraphData[level].nodes.push(nodeObject)
  264. if (parentNodeId) {
  265. _todoGraphData[level].edges.push(dataMakeEdge(parentNodeId, nodeObject))
  266. }
  267. Object.keys(json).filter(function (fieldName) {
  268. return (fieldName.indexOf(':') > -1)
  269. })
  270. .forEach(function (fieldName) {
  271. var value = json[fieldName]
  272. parseResponseRec(_todoGraphData, value, fieldName, nodeId, level + 1)
  273. })
  274. } else if (p5Utils__isString(json)) {
  275. if(DBG)console.log('TODO: Not implemented - parseResponseRec isString');
  276. } else {
  277. if(DBG)console.log('TODO: Not implemented - parseResponseRec is not string, not array and not object');
  278. }
  279. }
  280. function parseResponseXlinkListRec(_todoGraphData, json, typeName, parentNodeId, level) {
  281. 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)});
  282. if (p5Utils__isString(json)) { // xlink "https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI#BI_audit_ENERGA_RUM_KONTRAHENCI.9233",
  283. var nodeId = json.substr(json.indexOf('#') + 1)
  284. {
  285. // _graphData.nodes.add({ id: nodeId, label: nodeId })
  286. if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
  287. var nodeObject = dataMakeXlinkNode({
  288. xlink: json,
  289. typeName: typeName,
  290. primaryKey: (json['ID']) ? json['ID'] : null, // TODO: get primaryKey from object
  291. })
  292. _todoGraphData[level].nodes.push(nodeObject)
  293. if (parentNodeId) {
  294. _todoGraphData[level].edges.push(dataMakeEdge(parentNodeId, nodeObject))
  295. }
  296. }
  297. } else if (p5Utils__isObject(json) && isP5LinkObject(json)) {
  298. parseResponseP5Link(_todoGraphData, json, typeName, parentNodeId, level)
  299. } else {
  300. if(DBG)console.log('TODO: Not implemented - parseResponseRec:XlinkList is not string and not object');
  301. }
  302. }
  303. function parseResponseP5Link(_todoGraphData, json, typeName, parentNodeId, level) {
  304. if(DBG)console.log('parseResponseRec isObject and P5Link - fetch more xlink object');
  305. // example json: { type: "next",
  306. // @backRefNS: "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA",
  307. // @backRefPK: "42",
  308. // @typeName: "default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_P…ow:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row",
  309. // @startIndex: "10" }
  310. if (!parentNodeId) throw "Missing parentNodeId for ref link object";
  311. var objectName = typeName.substr(typeName.indexOf(':') + 1)
  312. {
  313. // _graphData.nodes.add({ id: nodeId, label: nodeId })
  314. if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
  315. switch (json.type) {
  316. case 'next': {
  317. var nodeObject = dataMakeFetchMoreNode({
  318. parentNodeId: parentNodeId,
  319. type: json.type,
  320. objectName: objectName,
  321. ref: json,
  322. })
  323. _todoGraphData[level].nodes.push(nodeObject)
  324. _todoGraphData[level].edges.push(dataMakeFetchMoreEdge(parentNodeId, nodeObject))
  325. } break;
  326. default: {
  327. if(DBG)console.log('TODO: Not implemented - parseResponseRec isObject with type "'+json.type+'" - fetch more xlink object');
  328. }
  329. }
  330. }
  331. }
  332. function fetchNodeMoreRefs(selectedNode, featureID) {
  333. try {
  334. if (!selectedNode) throw "Missing featureID"
  335. if (!featureID) throw "Missing featureID"
  336. if (!selectedNode.ref) throw "Missing selectedNode.ref"
  337. var idSelectedNode = selectedNode.id
  338. var idSelectedEdge = selectedNode.id
  339. var parentNodeId = selectedNode.parentNodeId
  340. var featureTypeName = selectedNode.ref['@typeName']
  341. var backRefNS = selectedNode.ref['@backRefNS']
  342. var backRefPK = selectedNode.ref['@backRefPK']
  343. var backRefField = selectedNode.ref['@typeName']
  344. var startIndex = selectedNode.ref['@startIndex']
  345. _nodes.update({
  346. id: idSelectedNode,
  347. label: "Pobieranie danych..."
  348. })
  349. var wfsParams = {
  350. backRefNS: backRefNS,
  351. backRefPK: backRefPK,
  352. backRefField: backRefField,
  353. startIndex: startIndex,
  354. maxFeatures: 10,
  355. };
  356. p5WFS_GetFeature(featureTypeName, wfsParams).then(function (features) {
  357. if(DBG)console.log('features', features)
  358. if (!features.length) throw "Brak danych"
  359. features.forEach(function (feature) {
  360. // TODO: validate
  361. var objectName = featureTypeName.substr(featureTypeName.indexOf(':') + 1)
  362. var nodeId = objectName + '.' + feature.ID // TODO: primaryKey?
  363. _todoGraphData[0].edges.push({ id: parentNodeId + nodeId, from: parentNodeId, to: nodeId })
  364. })
  365. // var refFields = Object.keys(features[0]).filter(function (fieldName) {
  366. // return (fieldName.indexOf(':') > -1)
  367. // }).filter(function (fieldName) {
  368. // return (features[0][fieldName].length > 0)
  369. // })
  370. // if (!refFields.length) return "Brak danych"
  371. // features = features.map(function (feature) {
  372. // return {
  373. // feature
  374. // }
  375. // })
  376. // console.log('TODO: features: ', features);
  377. // updateWfsResponse(features[0], featureTypeName) // TODO: RMME DBG
  378. // updateWfsResponse(features[1], featureTypeName) // TODO: RMME DBG
  379. // var feature = features[1]
  380. // var nodeId = featureTypeName + '.' + feature['ID']
  381. // try {
  382. // _edges.add({
  383. // id: parentNodeId + nodeId,
  384. // from: parentNodeId,
  385. // to: nodeId
  386. // })
  387. // } catch (e) {
  388. // if(DBG)console.warn('TODO: XXX: ' + e)
  389. // }
  390. features.forEach(function (feature) {
  391. updateWfsResponse(feature, featureTypeName)
  392. })
  393. var nodeSelectedData = _nodes.get(idSelectedNode)
  394. var edgeSelectedData = _nodes.get(idSelectedEdge)
  395. _nodes.remove({ id: idSelectedNode })
  396. _edges.remove({ id: idSelectedEdge })
  397. if (features.length >= 10) {
  398. var nodeObject = dataMakeFetchMoreNode({
  399. parentNodeId: nodeSelectedData.parentNodeId,
  400. type: nodeSelectedData.type,
  401. objectName: nodeSelectedData.objectName,
  402. ref: Object.assign(nodeSelectedData.ref, {
  403. '@startIndex': (10 + parseInt(startIndex)),
  404. value: nodeSelectedData.ref.value.replace('startIndex=' + startIndex, 'startIndex=' + (10 + parseInt(startIndex)))
  405. })
  406. })
  407. _nodes.add(nodeObject)
  408. _edges.add(dataMakeFetchMoreEdge(parentNodeId, nodeObject))
  409. }
  410. updateSankeyDiagram()
  411. return "Pobrano nowe dane"
  412. }).then(function (msg) {
  413. p5UI__notifyAjaxCallback({ type: 'info', msg: msg })
  414. }).catch(function (e) {
  415. if(DBG)console.warn(e)
  416. p5UI__notifyAjaxCallback({ type: 'error', msg: e })
  417. _nodes.remove({ id: idSelectedNode })
  418. _edges.remove({ id: idSelectedEdge })
  419. })
  420. } catch (e) {
  421. if(DBG)console.warn(e)
  422. }
  423. }
  424. function fetchNodeRecurse(selectedNode, featureID) {
  425. try {
  426. var selectedNodeId = selectedNode.id
  427. if (!selectedNode) throw "Missing featureID"
  428. if (!featureID) throw "Missing featureID"
  429. var featureEx = featureID.split('.')
  430. if (2 !== featureEx.length) throw "Not supported featureID format"
  431. var featureTypeName = 'default_db__x3A__' + featureEx[0] + ':' + featureEx[0]
  432. var wfsParams = Object.assign({}, _defaultWfsParams, {
  433. primaryKey: featureEx[1]
  434. });
  435. // view-source:http://visjs.org/examples/network/data/dynamicData.html
  436. _nodes.update({
  437. id: featureID,
  438. label: makeShortLabel(selectedNodeId) + ' ...'
  439. })
  440. p5WFS_GetFeature(featureTypeName, wfsParams).then(function (features) {
  441. if(DBG)console.log('features', features)
  442. if (!features.length || 1 !== features.length) throw "Brak danych" // require 1 feature with recurse
  443. var refFields = Object.keys(features[0]).filter(function (fieldName) {
  444. return (fieldName.indexOf(':') > -1)
  445. }).filter(function (fieldName) {
  446. return (features[0][fieldName].length > 0)
  447. })
  448. if (!refFields.length) return "Brak danych"
  449. updateWfsResponse(features, featureTypeName)
  450. updateSankeyDiagram()
  451. return "Pobrano nowe dane"
  452. }).then(function (msg) {
  453. p5UI__notifyAjaxCallback({ type: 'info', msg: msg })
  454. _nodes.update({ id: featureID, label: makeShortLabel(selectedNodeId), _loaded: true })
  455. }).catch(function (e) {
  456. if(DBG)console.warn(e)
  457. p5UI__notifyAjaxCallback({ type: 'error', msg: e })
  458. _nodes.update({ id: featureID, label: makeShortLabel(selectedNodeId), _loaded: true })
  459. })
  460. } catch (e) {
  461. if(DBG)console.warn(e)
  462. }
  463. }
  464. function makeShortLabel(label) { // TODO: shorter name
  465. // BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.1234567
  466. if (label.length < 30) return label;
  467. var exLabel = label.split('.')
  468. if (exLabel.length !== 2) return label;
  469. return exLabel[0].substr(0, 24) + '...' + exLabel[0].substr(-10) + '.' + exLabel[1];
  470. }
  471. function renderLayout(mode) {
  472. if ('undefined' !== typeof mode && _isFullScreen !== mode) _isFullScreen = mode
  473. // create a network
  474. if (!_html['container']) {
  475. _html['container'] = document.getElementById(HTML_ID_REF_GRAPH)
  476. }
  477. _html['container'].style.position = (_isFullScreen) ? 'fixed' : 'relative'
  478. _html['container'].style.top = (_isFullScreen) ? '40px' : ''
  479. _html['container'].style.left = '0px'
  480. _html['container'].style.margin = '0'
  481. _html['container'].style.border = (_isFullScreen) ? '0' : '1px solid silver'
  482. _html['container'].style.padding = '0'
  483. _html['container'].style.backgroundColor = '#fff'
  484. _html['container'].style.height = (_isFullScreen) ? ''+(window.innerHeight-40)+'px' : ''+(window.innerHeight-60-_html['container'].offsetTop)+'px'
  485. _html['container'].style.width = (_isFullScreen) ? '' + (window.innerWidth) + 'px' : '100%'
  486. if (!_html['top']) {
  487. _html['top'] = document.createElement('div')
  488. _html['container'].parentNode.insertBefore(_html['top'], _html['container'].nextSibling)
  489. }
  490. _html['top'].style.position = (_isFullScreen) ? 'fixed' : 'relative'
  491. _html['top'].style.top = '0px'
  492. _html['top'].style.left = '0px'
  493. _html['top'].style.margin = '0'
  494. _html['top'].style.border = '0'
  495. _html['top'].style.padding = '0'
  496. _html['top'].style.backgroundColor = '#101010'
  497. _html['top'].style.height = '40px'
  498. _html['top'].style.width = (_isFullScreen) ? '' + (window.innerWidth) + 'px' : '100%'
  499. _html['top'].style.zIndex = 3
  500. if (!_html['fullscreenBtn']) {
  501. _html['fullscreenBtn'] = document.createElement('button')
  502. _html['fullscreenBtn'].className = 'btn btn-lg btn-link'
  503. _html['top'].appendChild(_html['fullscreenBtn'])
  504. _html['fullscreenBtn'].style.color = '#fff'
  505. _html['fullscreenBtn'].style.float = 'right'
  506. _html['fullscreenBtn'].style.outline = 'none'
  507. _html['fullscreenBtn'].addEventListener('click', function () {
  508. _isFullScreen = !_isFullScreen
  509. renderLayout()
  510. })
  511. }
  512. _html['fullscreenBtn'].innerHTML = (_isFullScreen)
  513. ? '<i class="glyphicon glyphicon-resize-small" title="Zamknij pełny ekran"></i>'
  514. : '<i class="glyphicon glyphicon-resize-full" title="Pełny ekran"></i>'
  515. ;
  516. if (!_html['selected']) {
  517. _html['selected'] = document.createElement('span')
  518. var htmlSelectedWrap = document.createElement('div')
  519. htmlSelectedWrap.style.color = '#fff'
  520. htmlSelectedWrap.style.fontSize = '14px'
  521. htmlSelectedWrap.style.lineHeight = '40px'
  522. htmlSelectedWrap.style.paddingLeft = '12px'
  523. htmlSelectedWrap.appendChild(document.createTextNode("Wybrany: "))
  524. htmlSelectedWrap.appendChild(_html['selected'])
  525. _html['top'].appendChild(htmlSelectedWrap)
  526. _html['selected'].innerHTML = 'brak'
  527. }
  528. }
  529. function renderSelectedNode(node) {
  530. var gotToTableLink = (node.typeName)
  531. ? '<a href="index.php?_route=ViewTableAjax&namespace=' + node.typeName.replace('__x3A__', '/').replace(':', '/') + '" class="btn btn-link" style="color:#fff" title="Przejdź do tabeli ' + node.typeName + '">' +
  532. '<i class="glyphicon glyphicon-list-alt"></i>' +
  533. '</a>'
  534. : ''
  535. ;
  536. var editLink = (node.typeName && node.primaryKey)
  537. ? '<a href="index.php?_route=ViewTableAjax&namespace=' + node.typeName.replace('__x3A__', '/').replace(':', '/') + '#EDIT/' + node.primaryKey + '" class="btn btn-link" style="color:#fff" title="Edytuj rekord ' + node.primaryKey + '">' +
  538. '<i class="glyphicon glyphicon-pencil"></i>' +
  539. '</a>'
  540. : ''
  541. ;
  542. _html['selected'].innerHTML = '' + node.id + ' ' + gotToTableLink + ' ' + editLink;
  543. }
  544. function updateSankeyDiagram() {
  545. console.log('updateSankeyDiagram..');
  546. if (!SHOW_FLOW_DIAGRAM || !sankey) return;
  547. // var sankeyData = { // example
  548. // nodes: [
  549. // /* 0 */ { name: "A" },
  550. // /* 1 */ { name: "B" },
  551. // /* 2 */ { name: "C" },
  552. // /* 3 */ { name: "D" },
  553. // /* 4 */ { name: "E" },
  554. // /* 5 */ { name: "F" },
  555. // ],
  556. // links: [
  557. // { "source": 0, "target": 1, "value": 100 },
  558. // { "source": 1, "target": 2, "value": 100 },
  559. // { "source": 2, "target": 3, "value": 100 },
  560. // { "source": 3, "target": 4, "value": 100 },
  561. // { "source": 5, "target": 2, "value": 100 },
  562. // { "source": 0, "target": 4, "value": 100 },
  563. // ]
  564. // }
  565. p5Utils__clearNode(_sankeySvgNode)
  566. var d3SvgNode = d3.select(_sankeySvgNode);
  567. _sankeyLink = d3SvgNode.append("g")
  568. .attr("class", "links")
  569. .attr("fill", "none")
  570. .attr("stroke", "#000")
  571. .attr("stroke-opacity", 0.2)
  572. .selectAll("path");
  573. _sankeyNode = d3SvgNode.append("g")
  574. .attr("class", "nodes")
  575. .attr("font-family", "sans-serif")
  576. .attr("font-size", 10)
  577. .selectAll("g");
  578. // var sankeyInstance = sankey(sankeyData);
  579. var mapVisNodeIdToIdx = _nodes.getIds().reduce(function (ret, id, idx) {
  580. ret[id] = idx;
  581. return ret;
  582. }, {});
  583. var countOutLinks = _edges.get().reduce(function (ret, edge) {
  584. if (!mapVisNodeIdToIdx.hasOwnProperty(edge.from)) throw "Missing to in mapVisNodeIdToIdx["+edge.from+"]"
  585. var idxTarget = mapVisNodeIdToIdx[edge.from]
  586. ret[idxTarget] = (ret[idxTarget] > 0) ? ret[idxTarget] + 1 : 1
  587. console.log('DBG:sankey: countOutLinks reduce', edge, ret);
  588. return ret
  589. }, {})
  590. console.log('DBG:sankey: mapVisNodeIdToIdx', mapVisNodeIdToIdx);
  591. console.log('DBG:sankey: countOutLinks', countOutLinks);
  592. var sankeyInstance = sankey({
  593. nodes: _nodes.map(function (node) {
  594. return {
  595. name: node.label
  596. }
  597. }),
  598. links: _edges.map(function (edge) {
  599. if (!mapVisNodeIdToIdx.hasOwnProperty(edge.from)) throw "Missing from in mapVisNodeIdToIdx["+edge.from+"]"
  600. if (!mapVisNodeIdToIdx.hasOwnProperty(edge.to)) throw "Missing to in mapVisNodeIdToIdx["+edge.to+"]"
  601. var idxTarget = mapVisNodeIdToIdx[edge.to]
  602. return {
  603. source: mapVisNodeIdToIdx[edge.from],
  604. target: idxTarget,
  605. value: (countOutLinks[idxTarget] || 1) * 10
  606. }
  607. }),
  608. });
  609. // var sankeyInstance = sankey()
  610. // .nodes(
  611. // _nodes.map(function (node) {
  612. // return {
  613. // name: node.label
  614. // }
  615. // })
  616. // )
  617. // .edges(
  618. // _edges.map(function (edge) {
  619. // if (!mapVisNodeIdToIdx.hasOwnProperty(edge.from)) throw "Missing from in mapVisNodeIdToIdx["+edge.from+"]"
  620. // if (!mapVisNodeIdToIdx.hasOwnProperty(edge.to)) throw "Missing to in mapVisNodeIdToIdx["+edge.to+"]"
  621. // var idxTarget = mapVisNodeIdToIdx[edge.to]
  622. // return {
  623. // source: mapVisNodeIdToIdx[edge.from],
  624. // target: idxTarget,
  625. // value: (countOutLinks[idxTarget] || 1) * 10
  626. // }
  627. // })
  628. // )
  629. // .layout(32);
  630. _sankeyLink = _sankeyLink
  631. .data(sankeyInstance.links)
  632. .enter().append("path")
  633. .attr("d", d3.sankeyLinkHorizontal())
  634. .attr("stroke-width", function(d) { return Math.max(1, d.width); });
  635. _sankeyLink.append("title")
  636. .text(function(d) { return d.source.name + " → " + d.target.name + "\n" + _sankeyFormat(d.value); });
  637. _sankeyNode = _sankeyNode
  638. .data(sankeyInstance.nodes)
  639. .enter().append("g");
  640. _sankeyNode.append("rect")
  641. .attr("x", function(d) { return d.x0; })
  642. .attr("y", function(d) { return d.y0; })
  643. .attr("height", function(d) { return d.y1 - d.y0; })
  644. .attr("width", function(d) { return d.x1 - d.x0; })
  645. .attr("fill", function(d) { return _sankeyColor(d.name.replace(/ .*/, "")); })
  646. .attr("stroke", "#000");
  647. _sankeyNode.append("text")
  648. .attr("x", function(d) { return d.x0 - 6; })
  649. .attr("y", function(d) { return (d.y1 + d.y0) / 2; })
  650. .attr("dy", "0.35em")
  651. .attr("text-anchor", "end")
  652. .text(function(d) { return d.name; })
  653. .filter(function(d) { return d.x0 < _sankeySvgWidth / 2; })
  654. .attr("x", function(d) { return d.x1 + 6; })
  655. .attr("text-anchor", "start");
  656. _sankeyNode.append("title")
  657. .text(function(d) { return d.name + "\n" + _sankeyFormat(d.value); });
  658. }
  659. // global['FUNCTION_FETCH_CHILDRENS'] = 'refGraphFetchChildrens'
  660. // global['FUNCTION_FETCH_PARENTS'] = 'refGraphFetchParents'
  661. // global['_nodes'] = _nodes // TODO: DBG
  662. // global['_edges'] = _edges // TODO: DBG