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 7f8d8aa commit ac961d1
Show file tree
Hide file tree
Showing 2 changed files with 196 additions and 65 deletions.
98 changes: 63 additions & 35 deletions ui/web/static/js/charts.js
Original file line number Diff line number Diff line change
Expand Up @@ -706,7 +706,14 @@ class HorizontalBarChart extends Echart {
},
dataset: {
source: [
[],
[
"thing",
"value"
],
[
"thing0",
99
],
]
},
grid: { containLabel: true },
Expand Down Expand Up @@ -747,53 +754,74 @@ class HorizontalBarChart extends Echart {
horizontalBarChart.setOption(option);
var chartData = {
channel: '${this.chartData.channel}',
publisher: '${this.chartData.thing}',
channels: ${this.chartData.channel},
things: ${this.chartData.thing},
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 thingIds = getThingIds(chartData);
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.channel[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, chartData, 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,chartData,plotData) {
option = horizontalBarChart.getOption();
option.series[0].encode.x = 'value';
option.series[0].encode.y = 'thing';
option.visualMap.text = ['High'+chartData.name, 'Low'+chartData.name];
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
163 changes: 133 additions & 30 deletions ui/web/templates/charts/horizontalbarchartmodal.html
Original file line number Diff line number Diff line change
Expand Up @@ -63,27 +63,71 @@ <h5 class="modal-title" id="horizontalBarChartModalLabel">Horizontal Bar Chart</
role="tabpanel"
aria-labelledby="data-tab"
>
<div id="data-source-container">
<label class="form-label">Data sources</label>
<div class="input-pair mb-3">
<div class="mb-3">
<input
type="text"
pattern="{{ .UUIDPattern }}"
class="form-control mb-3"
name="channel"
id="channel-id"
placeholder="Enter a channel ID"
required
/>
<div class="invalid-feedback">Please enter a valid uuid</div>
</div>
<div class="mb-3">
<input
type="text"
pattern="{{ .UUIDPattern }}"
class="form-control mb-3"
name="thing"
id="thing-id"
placeholder="Enter a thing ID"
required
/>
<div class="invalid-feedback">Please enter a valid uuid</div>
</div>
</div>
</div>
<button
type="button"
class="btn btn-primary btn-sm"
onclick="addDataSource({removeButtonBool:true});"
>
Add a datasource
</button>
<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 +185,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 @@ -157,6 +194,54 @@ <h5 class="modal-title" id="horizontalBarChartModalLabel">Horizontal Bar Chart</
</div>
</div>
<script>
// Add more data sources
function addDataSource(removeButtonBool) {
const container = document.getElementById("data-source-container");

const inputPairDiv = document.createElement("div");
inputPairDiv.className = "input-pair mb-3";

const removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.className = "btn btn-sm";
removeButton.id = "removeItem";
removeButton.innerHTML = `
<i class="fas fa-trash-can"></i>
`;
removeButton.onclick = function () {
container.removeChild(inputPairDiv);
};

const channelDiv = document.createElement("div");
channelDiv.className = "mb-3";
channelDiv.innerHTML = `
<input type="text"
class="form-control mb-3"
name="channel"
placeholder="Enter a channel ID"
required
/>
<div class="invalid-feedback">Please enter a valid uuid</div>
`;

const thingDiv = document.createElement("div");
thingDiv.className = "mb-3";
thingDiv.innerHTML = `
<input type="text"class="form-control mb-3"
name="thing"
placeholder="Enter a thing ID"
required
/>
<div class="invalid-feedback">Please enter a valid uuid</div>
`;
if (removeButtonBool) {
inputPairDiv.appendChild(removeButton);
}
inputPairDiv.appendChild(channelDiv);
inputPairDiv.appendChild(thingDiv);

container.appendChild(inputPairDiv);
}
// horizontal bar chart form
document
.getElementById("create-horizontalBarChart-button")
Expand All @@ -169,31 +254,49 @@ <h5 class="modal-title" id="horizontalBarChartModalLabel">Horizontal Bar Chart</

// Create an object to store the form data
let chartData = {};
let channels = [];
let 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();
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();
const dataSourceContainer = form.querySelector("#data-source-container");
while (dataSourceContainer.firstChild) {
dataSourceContainer.removeChild(dataSourceContainer.firstChild);
}
addDataSource(false); // add the default data source
form.classList.remove("was-validated");
});
form.reset();
bootstrap.Modal.getInstance(document.getElementById("horizontalBarChartModal")).hide();
}
</script>
{{ end }}

0 comments on commit ac961d1

Please sign in to comment.