webfeed: format dates and numbers via javascript

This change adjusts the webfeed.html template to return timestamps in ISO 8601 format in UTC and instead uses JavaScript to format and display using the user's local time.

JavaScript is also used to add a thousands seprator to values in the 'Observations' column.

When formatting the 'Added' column, the time is dropped and now displays as YYYY-MM-DD.
This commit is contained in:
Ryan Smith
2025-04-06 14:55:18 -07:00
parent 0462ed7b4c
commit 444a446b0f

View File

@@ -58,7 +58,7 @@
</header>
<main class="full-width">
{{if .Data}}
<table class="webfeed">
<table id="webfeed" class="webfeed">
<thead>
<tr>
<th><a href="?sort=ip&direction={{if and (eq .SortMethod "ip") (eq .SortDirection "asc")}}desc{{else}}asc{{end}}">
@@ -80,7 +80,7 @@
</tr>
</thead>
<tbody>
{{range .Data}}<tr><td>{{.IP}}<td>{{.Added.Format "2006-01-02 15:04"}}<td>{{.LastSeen.Format "2006-01-02 15:04"}}<td>{{.Observations}}
{{range .Data}}<tr><td>{{.IP}}<td>{{.Added.UTC.Format "2006-01-02T15:04:05.000Z"}}<td>{{.LastSeen.UTC.Format "2006-01-02T15:04:05.000Z"}}<td>{{.Observations}}
{{end}}
</tbody>
</table>
@@ -88,5 +88,52 @@
<p class="no-results">The threat feed is currently empty</p>
{{end}}
</main>
<script>
function formatDatesAndNumbers() {
// Format 'Added' as YYYY-MM-DD.
const addedDateFormat = new Intl.DateTimeFormat('en-CA', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
// Format 'Last Seen' as YYYY-MM-DD hh:mm.
const lastSeenDateFormat = new Intl.DateTimeFormat('en-CA', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
});
// Format 'Observations' with a thousands separator based on user's locale.
const numberFormat = new Intl.NumberFormat();
// Apply formats to table.
document.querySelectorAll("#webfeed tbody tr").forEach(row => {
// Apply format to 'Added' cell (row.cells[1]).
let date = new Date(row.cells[1].textContent);
if (!isNaN(date.valueOf())) {
row.cells[1].textContent = addedDateFormat.format(date);
}
// Apply format to 'Last Seen' cell (row.cells[2]).
date = new Date(row.cells[2].textContent);
if (!isNaN(date.valueOf())) {
row.cells[2].textContent = lastSeenDateFormat.format(date).replace(',', '');
}
// Apply format to 'Observations' cell (row.cells[3]).
const observationCount = parseInt(row.cells[3].textContent, 10);
if (!isNaN(observationCount)) {
row.cells[3].textContent = numberFormat.format(observationCount);
}
});
}
formatDatesAndNumbers();
</script>
</body>
</html>