$(document).ready(function () { // Circle Packing /* **** VARIABLES **** */ // Append container g to svg let svg = d3.select("svg"), margin = 20; const docWidth = $(document).width(); const docHeight = $(document).height(); // Draw svg depending on bootstrap size const svgSize = docWidth>1200&&docWidth<1600 ? docWidth*0.45 : (docWidth<768 ? docWidth*0.95 : docHeight*0.89); svg.attr("width", svgSize) .attr("height", svgSize); let diameter = +svg.attr("width"), g = svg.append("g").attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")"); // Color Scale let color = d3.scaleLinear() .domain([-1, 5]) .range(["hsl(152,80%,80%)", "hsl(228,30%,40%)"]) .interpolate(d3.interpolateHcl); // Packing function let pack = d3.pack() .size([diameter - margin, diameter - margin]) .padding(2); // Circle data let circleData = { name: "adt", children: [] }; let portData = {}; const BASE_URL = document.getElementById('span_id1').textContent; const TOKEN = document.getElementById('span_id2').textContent; /* **** FUNCTIONS **** */ function clearTable() { let tbody = $("#tbody"); tbody.empty(); $("#operating_system").html(""); $("#vlan_name").html(""); $("#host_name").html(""); $("#current_snapshot").html("") } function updateTable(discoveryMethod, hostname) { let tbody = $("#tbody"); clearTable(); let hosts = portData[discoveryMethod]; if(!hosts)return; let hostData = hosts[hostname]; if(hostData == undefined) return; if(hostData.ports == undefined) return; $("#operating_system").html(hostData.operating_system); $("#vlan_name").html(hostData.vlan_id); $("#host_name").html(hostname); // Write current date time const [{value: mo},, {value: day},, {value: ye},, {value: h},, {value: m},, {value: t}] = new Intl.DateTimeFormat('en', { month:'short', day:'numeric', year:'numeric', hour:'numeric', minute:'2-digit', hour12: true }).formatToParts(new Date(hostData.timestamp_device_scan_start)); $("#current_snapshot").html(`${mo} ${day}, ${ye} ${h}:${m} ${t}${discoveryMethod}`); if(hostData.ports.length == 0) return; hostData.ports.sort((a, b) => Number(a.port) - Number(b.port)).forEach((d) => { let port = $("").html(d.port); let service = $("").html(d.service); let status = $("").html(d.state); let row = $("").append(port).append(service).append(status); tbody.append(row); }); } // Function for getting snapshot data function getSnapshotData(vlans, date) { // List of promises to wait through (each vlan request) let promises = []; // Reset circle pack data circleData.children = []; // Iterate through each vlan vlans.forEach((vlan) => { if(vlan.snapshots.length === 0) return; let vlanData = { name: vlan.distributedNodeId, children: [] }; // Get one snapshot per discoveryMethod let snapshots = vlan.snapshots; let discoveryMethods = [...new Set(snapshots.map(d=>d.discoveryMethod))]; discoveryMethods.forEach(dM=>{ //get all snapshots from current discoveryMethod let snapshotsDM = snapshots.filter(s => s.discoveryMethod === dM); // Get the snapshot closest to the selected date (and for the given discoveryMethod) snapshotsDM.sort((a, b) => { let distanceA = Math.abs(new Date(date) - new Date(a.timestamp_dist_node_scan_start)); let distanceB = Math.abs(new Date(date) - new Date(b.timestamp_dist_node_scan_start)); return distanceA - distanceB; // sort a before b when the distance is smaller }); let snapshot_id = snapshotsDM[0].snapshotId; let snapshot_url = BASE_URL + "/snapshots?snapshotId=" + snapshot_id + "&token=" + TOKEN; // Push request for *this* snapshot into list of promises promises.push( fetch(snapshot_url).then(response => response.json()) .then((data) => { // Get the data from each host if (!portData[dM]){portData[dM]={}} data[0].devices.forEach((d) => { /*console.log(({ 'vlan': vlan.vlan_name, 'idList':snapshotsDM, 'id': snapshot_id, 'd':d, 'dM':dM, 'hostmame':d.hostname }));*/ // Store host -> ports for table portData[dM][d.hostname] = d; // Create object for circle packing data vlanData.children.push({ name: d.hostname, size: d.ports.length, discoveryMethod: dM }); }); }) ); }); // Push this vlan's snapshot data into the circleData circleData.children.push(vlanData); return true; }); return promises; } // Load parent dataset on vlans (which contains names of other files to load) const fetchAndDraw = function(date=""){ fetch(BASE_URL + "?token=" + TOKEN).then(response => { // Convert to json (which is a *promise*) return response.json() }) .then(data => { // Set vlan_data // vlan_data = data; let dates = []; // Get range of date/times data.forEach((vlan) => { // Get range of dates for testing vlan.snapshots.forEach((d) => dates.push(new Date(d.timestamp_dist_node_scan_start))) }); dates.sort(); // Create date-picker with min and max dates flatpickr("#time_selector", { enableTime: true, altInput: true, dateFormat: "Y-m-d H:i", minDate:dates[0], maxDate:dates[dates.length - 1], onClose:function(selectedDates) { document.getElementById("time_selector").value = selectedDates; //d3.event.stopPropagation(); // Get snapshot data //let snapshotPromises = getSnapshotData(data, selectedDates); //Promise.all(snapshotPromises).then(() => buildCircles(circleData)); } }); // Set the start date as the lowest one if (date===""){date=dates[dates.length-1];} // Get snapshot data let snapshotPromises = getSnapshotData(data, date); return Promise.all(snapshotPromises); }).then(() => { buildCircles(circleData)})}; // Function to build the circles function buildCircles (root) { // g.selectAll("cirlce, text").remove(); g.selectAll("*").remove(); root = d3.hierarchy(root) .sum(function(d) { return d.size || .1; }) .sort(function(a, b) { return b.value - a.value; }); let focus = root, nodes = pack(root).descendants(), view; let circle = g.selectAll("circle") .data(nodes) .enter().append("circle") .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; }) .style("fill", function(d) { return d.children ? color(d.depth) : null; }) .on("click", function(d) { updateTable(); // Zoom out when clicking on a childless circle (if zoomed in on the parent) if(d.children == undefined && focus == d.parent) { updateTable(d.data.discoveryMethod, d.data.name); d3.event.stopPropagation() } // Zoom into the parent (if it doesn't have children) else if(focus !== d && d.children == undefined && focus !== d.parent) zoom(d.parent), d3.event.stopPropagation(); // Zoom into the clicked element else if (focus !== d) zoom(d), d3.event.stopPropagation(); }); let text = g.selectAll("text") .data(nodes) .enter().append("text") .attr("class", "label") .style("fill-opacity", function(d) { return d.parent === root ? 1 : 0; }) .style("display", function(d) { return d.parent === root ? "inline" : "none"; }) .text(function(d) { return d.data.name; }); let node = g.selectAll("circle,text"); svg .on("click", function() { updateTable(); zoom(root); }); // Zoom function function zoom(d) { let focus0 = focus; focus = d; let transition = d3.transition() .duration(d3.event.altKey ? 7500 : 750) .tween("zoom", function(d) { let i = d3.interpolateZoom(view, [focus.x, focus.y, focus.r * 2 + margin]); return function(t) { zoomTo(i(t)); }; }); transition.selectAll("text") .filter(function(d) { return d.parent === focus || this.style.display === "inline"; }) .style("fill-opacity", function(d) { return d.parent === focus ? 1 : 0; }) .on("start", function(d) { if (d.parent === focus) this.style.display = "inline"; }) .on("end", function(d) { if (d.parent !== focus) this.style.display = "none"; }); } // Zoom to function function zoomTo(v) { let k = diameter / v[2]; view = v; node.attr("transform", function(d) { return "translate(" + (d.x - v[0]) * k + "," + (d.y - v[1]) * k + ")"; }); circle.attr("r", function(d) { return d.r * k; }); } zoomTo([root.x, root.y, root.r * 2 + margin]); } /* ***** ACTIONS **** */ //fetch data and draw svg fetchAndDraw(); // refetch and redraw svg on submit $("#submit").on('click', function(){ let date = document.getElementById("time_selector").value; if (date!==""){ clearTable(); fetchAndDraw(date); } else { const fadeOut = function(){ $('#error_message').fadeOut('slow', 'swing', function () { $('#error_message').addClass('d-none') $('#error_message').removeAttr('style') }) }; Promise.resolve( $('#error_message').removeClass('d-none') ).then(()=> setTimeout(fadeOut, 2000) ) } }); // avoid svg - table overlap on window resize $(window).resize(()=>{ if(svgSize-5>= $(document).width()/2){ $("#overlapped").attr("style","-ms-flex: 0 0 100% !important;\n" + "flex: 0 0 100% !important;\n" + "max-width: 100% !important;"); $("#svg-wrapper").addClass("offset-xl-3") } else{ $("#overlapped").removeAttr("style"); $("#svg-wrapper").removeClass("offset-xl-3"); } }); });