BiAuditGraph.php.network-graph.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. var DBG = DBG || false;
  2. var DBG1 = true;
  3. var DBG_INIT_SELECTED = [ "BI_audit_ENERGA_RUM_KONTRAHENCI.18661", "BI_audit_KRS.389967" ];
  4. if ('undefined' === typeof HTML_ID_REF_GRAPH) throw "Missing HTML_ID_REF_GRAPH";
  5. if (!RAPORT_ID) throw "Missing RAPORT_ID";
  6. if (!API_URL) throw "Missing API_URL";
  7. if (!global.p5VendorJs) throw "Missing p5VendorJs";
  8. if (!global.vis) throw "Missing vis";
  9. if (!global.p5VendorJs.Typeahead) throw "Missing Typeahead";
  10. var createReactClass = global.p5VendorJs.createReactClass;
  11. var h = global.p5VendorJs.React.createElement;
  12. var React = global.p5VendorJs.React;
  13. var ReactDOM = global.p5VendorJs.ReactDOM;
  14. var Redux = global.p5VendorJs.Redux;
  15. var ReduxThunk = global.p5VendorJs.ReduxThunk;
  16. var createStoreWithThunkMiddleware = Redux.applyMiddleware(ReduxThunk)(Redux.createStore); // TODO: to vendor.js
  17. var Typeahead = global.p5VendorJs.Typeahead;
  18. var mapStatsNodeToGraphNode = function (node) {
  19. return {
  20. id: node['@object'] + '.' + node['@primaryKey'],
  21. label: node['@label'],
  22. value: 1,
  23. level: 0,
  24. }
  25. };
  26. var mapStatsEdgeToGraphEdge = function (edge) {
  27. return {
  28. id: Utils.makeUniqueEdgeId(edge['source'], edge['target']),
  29. from: edge['source'],
  30. to: edge['target'],
  31. pathId: edge['pathId'],
  32. listPathId: [ edge['pathId'] ],
  33. }
  34. };
  35. //// DBG: Utils:
  36. // var from, to;
  37. // from = 'aa.11'; to = 'bb.22'; console.log('DBG: Utils.makeUniqueEdgeId('+from+', '+to+')', Utils.makeUniqueEdgeId(from, to), { cache: Utils.getCacheAllEdgeId().join(',') })
  38. // from = 'bb.22'; to = 'aa.11'; console.log('DBG: Utils.makeUniqueEdgeId('+from+', '+to+')', Utils.makeUniqueEdgeId(from, to), { cache: Utils.getCacheAllEdgeId().join(',') })
  39. // from = 'cc.22'; to = 'cc.11'; console.log('DBG: Utils.makeUniqueEdgeId('+from+', '+to+')', Utils.makeUniqueEdgeId(from, to), { cache: Utils.getCacheAllEdgeId().join(',') })
  40. var Utils = (function __makeUtils() {
  41. var Utils = {};
  42. var _cacheListFeatureNames = [];
  43. Utils.fidSplit = function (fid) {
  44. var dotPos = fid.indexOf('.');
  45. return [ fid.substr(0, dotPos), fid.substr(dotPos + 1) ];
  46. }
  47. Utils.makeUniqueEdgeId = function (from, to) {
  48. var listFidArr = [ from, to ].sort().map(Utils.fidSplit);
  49. var listIdx = listFidArr.map(function (fidArr) {
  50. var cacheIdx = _cacheListFeatureNames.indexOf(fidArr[0]);
  51. if (-1 === cacheIdx) {
  52. cacheIdx = _cacheListFeatureNames.length;
  53. _cacheListFeatureNames.push(fidArr[0]);
  54. }
  55. return cacheIdx;
  56. })
  57. return listIdx.map(function (cacheIdx, fidIdx) {
  58. return cacheIdx + '.' + listFidArr[fidIdx][1];
  59. }).join('-')
  60. }
  61. Utils.getCacheAllEdgeId = function () {
  62. return [].concat(_cacheListFeatureNames);
  63. }
  64. return Utils;
  65. })();
  66. { // TODO: RaportOutputPanel - mv to another file
  67. var RaportOutputPanel = {};
  68. RaportOutputPanel.initialState = function () {
  69. var nodes = (STATS && STATS.nodes) ? STATS.nodes : [];
  70. var edges = (STATS && STATS.edges) ? STATS.edges : [];
  71. var paths = (STATS && STATS.path_list) ? STATS.path_list : [];
  72. DBG1 && console.log('DBG: STATS', STATS);
  73. return {
  74. nodes: nodes.map(mapStatsNodeToGraphNode),
  75. edges: edges.map(mapStatsEdgeToGraphEdge),
  76. paths: paths,
  77. isLoading: false,
  78. sentRequestId: 0,
  79. receivedRequestId: 0,
  80. }
  81. };
  82. RaportOutputPanel.store = function (state, action) {
  83. var prevState = state || RaportOutputPanel.initialState();
  84. DBG1 && console.log('DBG: store', { prevState, action, actionType: action.type });
  85. switch (action.type) {
  86. case 'SET_SENT_REQUEST_ID': return Object.assign(prevState, {
  87. sentRequestId: action.sentRequestId,
  88. isLoading: true
  89. });
  90. case 'SET_RESPONSE': return Object.assign(prevState, {
  91. receivedRequestId: action.requestId,
  92. nodes: action.body.nodes.map(mapStatsNodeToGraphNode),
  93. edges: action.body.edges,
  94. isLoading: (prevState.sentRequestId > action.requestId) ? true : false,
  95. });
  96. default: return prevState;
  97. }
  98. };
  99. RaportOutputPanel.createActions = function () {
  100. var setSentRequestId = function (sentRequestId) {
  101. return { type: 'SET_SENT_REQUEST_ID', sentRequestId: sentRequestId };
  102. }
  103. var setResponse = function (response) {
  104. return Object.assign(response, { type: 'SET_RESPONSE' });
  105. }
  106. var fetchData = function (raportId, params) {
  107. return function (dispatch, getState) {
  108. var state = getState();
  109. var this__requestId = state.sentRequestId + 1;
  110. dispatch(setSentRequestId(this__requestId));
  111. var reqPromise = window.fetch(API_URL, {
  112. method: 'GET',
  113. credentials: 'same-origin',
  114. }).then(function (response) {
  115. return response.json();
  116. });
  117. return reqPromise.then(function (response) {
  118. var items = response;
  119. var state = getState();
  120. if (state.receivedRequestId > this__requestId) {
  121. DBG1 && console.log('DBG: skipped response', { 'state.receivedRequestId': state.receivedRequestId, this__requestId });
  122. return;
  123. }
  124. dispatch(
  125. setResponse({
  126. requestId: this__requestId,
  127. msg: "Pobrano dane",
  128. body: response.body
  129. })
  130. );
  131. }).catch(function (e) {
  132. p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #GS1: ' + e});
  133. // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
  134. });
  135. }
  136. }
  137. return {
  138. fetchData: fetchData,
  139. }
  140. };
  141. }
  142. { // TODO: NetworkGraph - mv to another file
  143. var NetworkGraph = {};
  144. NetworkGraph.initialState = function () {
  145. var nodes = (STATS && STATS.nodes) ? STATS.nodes : [];
  146. var edges = (STATS && STATS.edges) ? STATS.edges : [];
  147. var paths = (STATS && STATS.path_list) ? STATS.path_list : [];
  148. DBG1 && console.log('DBG: STATS', STATS);
  149. return {
  150. nodes: nodes.map(mapStatsNodeToGraphNode),
  151. edges: edges.map(mapStatsEdgeToGraphEdge),
  152. paths: paths,
  153. isLoading: false,
  154. sentRequestId: 0,
  155. receivedRequestId: 0,
  156. }
  157. };
  158. NetworkGraph.store = function (state, action) {
  159. var prevState = state || NetworkGraph.initialState();
  160. DBG1 && console.log('DBG: store', { prevState, action, actionType: action.type });
  161. switch (action.type) {
  162. case 'SET_SENT_REQUEST_ID': return Object.assign(prevState, {
  163. sentRequestId: action.sentRequestId,
  164. isLoading: true
  165. });
  166. case 'SET_RESPONSE': return Object.assign(prevState, {
  167. receivedRequestId: action.requestId,
  168. nodes: action.body.nodes.map(mapStatsNodeToGraphNode),
  169. edges: action.body.edges,
  170. isLoading: (prevState.sentRequestId > action.requestId) ? true : false,
  171. });
  172. default: return prevState;
  173. }
  174. };
  175. NetworkGraph.createActions = function () {
  176. var setSentRequestId = function (sentRequestId) {
  177. return { type: 'SET_SENT_REQUEST_ID', sentRequestId: sentRequestId };
  178. }
  179. var setResponse = function (response) {
  180. return Object.assign(response, { type: 'SET_RESPONSE' });
  181. }
  182. var fetchData = function (raportId, params) {
  183. return function (dispatch, getState) {
  184. var state = getState();
  185. var this__requestId = state.sentRequestId + 1;
  186. dispatch(setSentRequestId(this__requestId));
  187. var reqPromise = window.fetch(API_URL, {
  188. method: 'GET',
  189. credentials: 'same-origin',
  190. }).then(function (response) {
  191. return response.json();
  192. });
  193. return reqPromise.then(function (response) {
  194. var items = response;
  195. var state = getState();
  196. if (state.receivedRequestId > this__requestId) {
  197. DBG1 && console.log('DBG: skipped response', { 'state.receivedRequestId': state.receivedRequestId, this__requestId });
  198. return;
  199. }
  200. dispatch(
  201. setResponse({
  202. requestId: this__requestId,
  203. msg: "Pobrano dane",
  204. body: response.body
  205. })
  206. );
  207. }).catch(function (e) {
  208. p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #GS1: ' + e});
  209. // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
  210. });
  211. }
  212. }
  213. return {
  214. fetchData: fetchData,
  215. }
  216. };
  217. }
  218. var defaultNetworkGraphOptions = {
  219. nodes: {
  220. shape: 'dot',
  221. scaling: {
  222. min: 8, max: 30,
  223. label: {
  224. min: 8, max: 16, drawThreshold: 6, maxVisible: 20
  225. }
  226. },
  227. font: { color: "#666", size: 10, face: 'Helvetica Neue, Helvetica, Arial' }
  228. // font: "8px Helvetica Neue, Helvetica, Arial"
  229. },
  230. interaction: {
  231. hover: true,
  232. hoverConnectedEdges: false,
  233. selectConnectedEdges: true,
  234. },
  235. };
  236. var TMP_COUNTER = 1;
  237. var p5UI__NetworkGraph = createReactClass({
  238. _network: null,
  239. _visOutputRef: React.createRef(),
  240. _allNodes: null, // new vis.DataSet(),
  241. _allEdges: null, // new vis.DataSet(),
  242. _nodes: new vis.DataSet(),
  243. _edges: new vis.DataSet(),
  244. getStateFromStore: function () {
  245. var state = this.props.store.getState();
  246. return {
  247. isLoading: state.isLoading,
  248. receivedRequestId: state.receivedRequestId, // to force render after udpate nodes, edges
  249. }
  250. },
  251. getInitialState: function () {
  252. if (this.props.selected) this._updateSelected(this.props.selected);
  253. return {
  254. initialized: false,
  255. isLoading: false,
  256. receivedRequestId: null,
  257. };
  258. },
  259. setOutputRef: function (elem) {
  260. this._visOutputRef = elem;
  261. },
  262. componentDidMount: function () {
  263. var data = { nodes: this._nodes, edges: this._edges };
  264. this._network = new vis.Network(this._visOutputRef, data, defaultNetworkGraphOptions);
  265. // bindNetwork();
  266. this.setState({ initialized: true });
  267. this._unsubscribe = this.props.store.subscribe(this._storeUpdated)
  268. },
  269. _storeUpdated: function () {
  270. this.setState( this.getStateFromStore() )
  271. },
  272. testOnClick1: function () {
  273. TMP_COUNTER++;
  274. this._nodes.add({ id: TMP_COUNTER, label: "Node " + TMP_COUNTER, value: TMP_COUNTER, level: 0 });
  275. },
  276. testOnClick2: function () {
  277. TMP_COUNTER++;
  278. var ids = this._nodes.getIds();
  279. var totalNodes = ids.length
  280. if (totalNodes < 3) return;
  281. var fromIdx = Math.floor(Math.random() * totalNodes);
  282. var toIdx = Math.floor(Math.random() * totalNodes);
  283. this._edges.add({ from: ids[fromIdx], to: ids[toIdx] });
  284. },
  285. testOnClick3: function () {
  286. this.props.store.dispatch( this.props.storeActions.fetchData( this.props.raportId ) );
  287. },
  288. shouldComponentUpdate: function (nextProps, nextState) {
  289. // if (this.state.receivedRequestId !== nextState.receivedRequestId) { // add missing nodes
  290. // var state = this.props.store.getState();
  291. // DBG1 && console.warn("TODO: update nodes, edges", { state });
  292. // // this._edges.add( edge_or_edges_array )
  293. // if (state.nodes && state.nodes.length) {
  294. // var __nodes = this._nodes;
  295. // state.nodes.forEach(function (node) {
  296. // __nodes.add(node);
  297. // })
  298. // }
  299. // // edge: { from: page, to: subpageID, color:getEdgeColor(level), level: level, selectionWidth:2, hoverWidth:0 }
  300. // if (state.edges && state.edges.length) {
  301. // var __edges = this._edges;
  302. // // state.edges.forEach(function (edge) {
  303. // state.edges.slice(0, 30).forEach(function (edge) {
  304. // __edges.add({
  305. // from: edge.source,
  306. // to: edge.target,
  307. // });
  308. // })
  309. // }
  310. // }
  311. if (this.props.selected.length != nextProps.selected.length) {
  312. this._updateSelected(nextProps.selected)
  313. }
  314. return false;
  315. },
  316. _updateSelected: function (selected) { // TODO: move to RaportOutputPanel Store
  317. var state = this.props.store.getState();
  318. var idsSelected = (selected || []).map( function (node) { return node.id } )
  319. var nodes = [];
  320. // var edges = state.edges.filter(function (edge) { // use idsSelected - TODO: RMME
  321. // return ( -1 !== idsSelected.indexOf(edge.source) || -1 !== idsSelected.indexOf(edge.target) );
  322. // })
  323. {
  324. // TODO: find all paths with selected fids
  325. var foundPaths = state.paths.filter(function (path) {
  326. for (var i = 0, totalFids = path.fids.length, fid = null; i < totalFids; i++) {
  327. fid = path.fids[i];
  328. DBG && console.log('DBG:foundPaths ', {fid: ''+fid, path});
  329. if ( -1 !== idsSelected.indexOf(fid) ) return true;
  330. }
  331. return false;
  332. })
  333. // TODO: add missing nodes (not selected but on path)
  334. var addFidsToGraph = Array.from(new Set(foundPaths.reduce(function (ret, path) {
  335. return ret.concat(path.fids.filter(function (fid) {
  336. return ( -1 === idsSelected.indexOf(fid) );
  337. }))
  338. }, [])));
  339. // TODO: view only combined path or all not selected nodes? - trying: not selected nodes
  340. // TODO: convert found paths to graph edges
  341. }
  342. DBG1 && console.warn('DBG: TODO set edges by selectd nodes...', { state_nodes: state.nodes, state_edges: state.edges, idsSelected, foundPaths, addFidsToGraph });
  343. this._nodes = new vis.DataSet(selected);
  344. { // TODO: convert fid to node on found list
  345. { // if (!this._allNodes) {
  346. this._allNodes = new vis.DataSet();
  347. this._allNodes.add(state.nodes);
  348. }
  349. var this__allNodes = this._allNodes;
  350. var __nodes = this._nodes;
  351. var addNodesToGraph = addFidsToGraph.map(function (fid) {
  352. var node = this__allNodes.get(fid)
  353. try {
  354. DBG1 && console.log('DBG: TODO add node (fid:'+fid+') ', { node, this__allNodes, fid });
  355. __nodes.add(node);
  356. __nodes.update(Object.assign(node, { color: '#ddd', size: 100 }));
  357. DBG1 && console.log('DBG: added red node (fid:'+fid+') ', { node });
  358. } catch (e) {
  359. DBG1 && console.log(e);
  360. DBG1 && console.log('DBG: skip node (fid:'+fid+') already added');
  361. }
  362. })
  363. }
  364. DBG1 && console.log('DBG: check edges: ', { 'this._edges.length': this._edges.length, 'state.edges.length': state.edges.length });
  365. if (this._edges.length != state.edges.length) {
  366. DBG1 && console.log('DBG: TODO: update edges', { 'state.edges': state.edges });
  367. var this__edges = this._edges;
  368. state.edges.forEach(function (edge) {
  369. var foundEdge = this__edges.get(edge.id);
  370. if (!foundEdge) {
  371. this__edges.add(edge);
  372. } else {
  373. var listPathId = (-1 !== foundEdge.listPathId.indexOf(edge.pathId)) ? foundEdge.listPathId : foundEdge.listPathId.concat(edge.pathId);
  374. var mergedEdge = Object.assign(foundEdge, {
  375. listPathId: listPathId,
  376. width: 1 + (listPathId.length - 1) / 10,
  377. });
  378. this__edges.update(mergedEdge);
  379. }
  380. })
  381. }
  382. if (this._network) {
  383. this._network.setData({ nodes: this._nodes, edges: this._edges });
  384. this._network.fit() // zoom out to fit container size
  385. }
  386. },
  387. render: function () {
  388. DBG1 && console.log('DBG:render');
  389. return h('div', {}, [
  390. h('div', {
  391. ref: this.setOutputRef,
  392. style: {
  393. 'min-height': 600,
  394. 'height': 600,
  395. },
  396. }),
  397. h('div', {}, [
  398. h('button', { onClick: this.testOnClick1 }, [ "TEST 1 ", h('small', [], "(+ node)") ]),
  399. h('button', { onClick: this.testOnClick2 }, [ "TEST 2 ", h('small', [], "(+ edge)") ]),
  400. h('button', { onClick: this.testOnClick3 }, [ "TEST 3 ", h('small', [], "(+ fetch)") ]),
  401. ]),
  402. ]);
  403. }
  404. });
  405. /**
  406. * props.store: networkGraphStore
  407. * - used: state.nodes
  408. */
  409. var p5UI__RaportOutputPanel = createReactClass({
  410. getInitialState: function () {
  411. var initSelected = [];
  412. if (DBG_INIT_SELECTED) {
  413. var state = this.props.store.getState()
  414. initSelected = state.nodes.filter(function (node) {
  415. return ( -1 !== DBG_INIT_SELECTED.indexOf(node.id));
  416. })
  417. }
  418. return {
  419. selected: initSelected,
  420. }
  421. },
  422. handleSelectFeatures: function (selected) {
  423. DBG1 && console.log('DBG:typeahead selected:', { selected })
  424. this.setState({ selected: selected });
  425. },
  426. render: function () {
  427. var state = this.props.store.getState()
  428. DBG1 && console.log('DBG: state', state);
  429. var nodes = state.nodes || [];
  430. return h(React.Fragment, {}, [
  431. h(Typeahead, {
  432. labelKey: "label",
  433. multiple: true,
  434. options: nodes,
  435. placeholder: "Wybierz",
  436. bsSize: 'large',
  437. selected: this.state.selected,
  438. onChange: this.handleSelectFeatures,
  439. }),
  440. h(p5UI__NetworkGraph, {
  441. raportId: this.props.raportId,
  442. store: this.props.store,
  443. storeActions: this.props.storeActions,
  444. selected: this.state.selected,
  445. })
  446. ])
  447. }
  448. })
  449. ReactDOM.render(
  450. h(p5UI__RaportOutputPanel, {
  451. raportId: RAPORT_ID,
  452. store: createStoreWithThunkMiddleware(NetworkGraph.store),
  453. storeActions: NetworkGraph.createActions(),
  454. }),
  455. document.getElementById(HTML_ID_REF_GRAPH)
  456. );