Skip to content

Commit

Permalink
feat: Change chart modal for data sources
Browse files Browse the repository at this point in the history
Signed-off-by: 1998-felix <[email protected]>
  • Loading branch information
felixgateru committed Mar 15, 2024
1 parent 5085b3f commit 628742f
Show file tree
Hide file tree
Showing 2 changed files with 171 additions and 67 deletions.
95 changes: 59 additions & 36 deletions ui/web/static/js/charts.js
Original file line number Diff line number Diff line change
Expand Up @@ -706,7 +706,10 @@ class HorizontalBarChart extends Echart {
},
dataset: {
source: [
[],
[
"thing",
"value"
],
]
},
grid: { containLabel: true },
Expand All @@ -727,7 +730,7 @@ class HorizontalBarChart extends Echart {
left: 'center',
min: 0,
max: 100,
text: ['High temperature', 'Low temperature'],
text: ['High', 'Low'],
// Map the score column to color
dimension: 0,
inRange: {
Expand All @@ -747,53 +750,73 @@ class HorizontalBarChart extends Echart {
horizontalBarChart.setOption(option);
var chartData = {
channel: '${this.chartData.channel}',
publisher: '${this.chartData.thing}',
channels: '${this.chartData.channels}'.split(','),
things: '${this.chartData.things}'.split(','),
name: '${this.chartData.valueName}',
from: ${this.chartData.startTime},
to: ${this.chartData.stopTime},
aggregation: '${this.chartData.aggregationType}',
limit: 100,
interval : getInterval(),
}
async getData(horizontalBarChart, chartData) {
};
fetchData(horizontalBarChart, chartData);
async function fetchData(horizontalBarChart, chartData) {
try {
const apiEndpoint = "/data?channel=" + chartData.channel +
"&name=" + chartData.name +
"&from=" + chartData.from +
"&to=" + chartData.to +
"&aggregation=" + chartData.aggregation +
"&limit=" + chartData.limit +
"&interval=" + chartData.interval;
const response = await fetch(apiEndpoint);
const plotData = [['value', 'thing']];
if (!response.ok) {
throw new Error('API request failed with status ${response.status}');
}
const data = await response.json();
updateChart(data);
for (let i = 0; i < chartData.channels.length; i++) {
const apiEndpoint = '${pathPrefix}/data?channel=' + chartData.channels[i] +
'&name=' + chartData.name +
'&from='+ chartData.from +
'&to=' + chartData.to +
'&aggregation=' + chartData.aggregation +
'&limit=10' +
'&interval=' + getInterval(chartData) +
'&publisher=' + chartData.things[i];
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error('HTTP request failed with status:', response.status)
}
const data = await response.json();
plotData.push([data.messages[0].value, 'thing'+i.toString()]);
}
updateChart(horizontalBarChart, plotData);
} catch (error) {
console.error("Error fetching data:", error);
// Handle the error (e.g., display an error message)
} finally {
// Schedule the next update
setTimeout(() => this.fetchDataAndUpdate(), 5000); // Example: 5 seconds
console.error("Error fetching data:", error);
}
}
updateChart(data) {
const barChart = echarts.init(document.getElementById(this.ID));
const option = barChart.getOption(); // Get the existing options
option.series[0].data = data.seriesData;
barChart.setOption(option); // Update the chart
function updateChart(horizontalBarChart, plotData) {
option = horizontalBarChart.getOption();
option.series[0].encode.x = 'value';
option.series[0].encode.y = 'thing';
option.visualMap.text = ['High', 'Low'];
option.dataset[0].source = plotData;
horizontalBarChart.setOption(option);
}
function getInterval(chartData) {
const interval = chartData.to - chartData.from;
const nanosecondsPerSecond = 1e3;
const secondsPerMinute = 60;
const minutesPerHour = 60;
let minutes = 0;
let hours = 0;
let intervalString = "";
let seconds = parseInt(interval) / nanosecondsPerSecond;
intervalString = Math.ceil(seconds).toString() +'s';
if (seconds >= secondsPerMinute) {
minutes = seconds/ secondsPerMinute;
intervalString = Math.ceil(minutes).toString() + 'm';
}
if (minutes >= minutesPerHour) {
hours = minutes /minutesPerHour;
intervalString = Math.ceil(hours).toString() + 'h';
}
return intervalString;
}
}
`;
}
}
Expand Down
143 changes: 112 additions & 31 deletions ui/web/templates/charts/horizontalbarchartmodal.html
Original file line number Diff line number Diff line change
Expand Up @@ -63,27 +63,79 @@ <h5 class="modal-title" id="horizontalBarChartModalLabel">Horizontal Bar Chart</
role="tabpanel"
aria-labelledby="data-tab"
>
<div class="table-responsive-md mb-3 p-2 border rounded">
<h5>Data Source</h5>
<table class="table" id="linechart-data">
<thead>
<tr>
<th scope="col">Channel</th>
<th scope="col">Thing</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input
type="text"
pattern="{{ .UUIDPattern }}"
class="form-control"
name="channel"
placeholder="channel ID"
required
/>
</td>
<td>
<input
type="text"
pattern="{{ .UUIDPattern }}"
class="form-control"
name="thing"
placeholder="thing ID"
required
/>
</td>
<td class="text-center">
<button type="button" class="btn btn-sm" onclick="removeRow(this)">
<i class="fas fa-trash-alt"></i>
</button>
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn body-button btn-sm" onclick="addRow()">
Add source
</button>
</div>
<div class="mb-3">
<label for="channel-id" class="form-label">Channel ID</label>
<label for="value-name" class="form-label">Value name</label>
<input
type="text"
pattern="{{ .UUIDPattern }}"
class="form-control mb-3"
name="channel"
id="channel-id"
placeholder="Enter the channel ID"
name="valueName"
id="value-name"
placeholder="Enter the value name eg. temperature"
required
/>
<div class="invalid-feedback">Please enter a valid uuid</div>
</div>
<div class="mb-3">
<label for="value-name" class="form-label">Value name</label>
<label for="start-time" class="form-label">Start time</label>
<input
type="text"
type="datetime-local"
class="form-control mb-3"
name="valueName"
id="value-name"
placeholder="Enter the value name eg. temperature"
name="startTime"
id="start-time"
required
/>
<div class="invalid-time"></div>
</div>
<div class="mb-3">
<label for="stop-time" class="form-label">Stop time</label>
<input
type="datetime-local"
class="form-control mb-3"
name="stopTime"
id="stop-time"
required
/>
</div>
Expand Down Expand Up @@ -141,14 +193,7 @@ <h5 class="modal-title" id="horizontalBarChartModalLabel">Horizontal Bar Chart</
</form>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
id="close-horizontalBarChart-button"
data-bs-dismiss="modal"
>
Close
</button>
<button type="button" class="btn btn-secondary" onclick="resetForm();">Close</button>
<button type="button" class="btn body-button" id="create-horizontalBarChart-button">
Create Chart
</button>
Expand All @@ -169,31 +214,67 @@ <h5 class="modal-title" id="horizontalBarChartModalLabel">Horizontal Bar Chart</

// Create an object to store the form data
let chartData = {};
const channels = [];
const things = [];
let formData = new FormData(form);
for (var pair of formData.entries()) {
if (pair[0] === "startTime" || pair[0] === "stopTime") {
const inputDate = new Date(pair[1]);
chartData[pair[0]] = inputDate.getTime() * 1e6;
} else {
chartData[pair[0]] = pair[1];
switch (pair[0]) {
case "startTime":
case "stopTime":
const inputDate = new Date(pair[1]);
chartData[pair[0]] = inputDate.getTime() * 1e6;
break;
case "channel":
channels.push(pair[1]);
break;
case "thing":
things.push(pair[1]);
break;
default:
chartData[pair[0]] = pair[1];
break;
}
}

var widgetID = "horizontalBarchart-" + Date.now();

chartData["Type"] = "horizontalBarChart";
chartData["channels"] = channels;
chartData["things"] = things;
addWidget(chartData, widgetID);
metadataBuffer[widgetID] = chartData;

form.reset();
form.classList.remove("was-validated");
bootstrap.Modal.getInstance(document.getElementById("horizontalBarChartModal")).hide();
resetForm();
});

document.getElementById("horizontalBarChartModal").addEventListener("click", function () {
function resetForm() {
const form = document.getElementById("create-horizontalBarChart-form");
form.reset();
form.classList.remove("was-validated");
});
form.reset();
bootstrap.Modal.getInstance(document.getElementById("horizontalBarChartModal")).hide();
}

function addRow() {
const uuidPattern = "{{ .UUIDPattern }}";
const table = document.getElementById("linechart-data");
const newRow = table.insertRow(-1);
newRow.innerHTML = ` <td>
<input type="text" pattern="${uuidPattern}" class="form-control" name="channel"
placeholder="channel ID" required />
</td>
<td>
<input type="text" pattern="${uuidPattern}" class="form-control" name="thing"
placeholder="thing ID" required />
</td>
<td class="text-center">
<button type="button" class="btn btn-sm" onclick="removeRow(this)">
<i class="fas fa-trash-alt"></i>
</button>
</td>`;
}

function removeRow(button) {
const row = button.parentNode.parentNode;
row.parentNode.removeChild(row);
}
</script>
{{ end }}

0 comments on commit 628742f

Please sign in to comment.