Files
watcher-visio/static/js/utils.js
Nikolay Tatarinov 656a6bfac4
Some checks failed
CI / ci (push) Has been cancelled
Refactor dashboard data serialization and mock context for improved clarity
- Introduced `serialize_audit_for_response` and `serialize_current_cluster_for_template` functions to handle JSON serialization of audit and cluster data, enhancing data consistency for API responses and template rendering.
- Updated `get_mock_context` in `mock_data.py` to utilize the new serialization functions, simplifying the mock data structure and improving readability.
- Refactored `collect_context` and `collect_audits` in `views.py` to leverage the new serialization methods, ensuring a cleaner and more maintainable codebase.
- Added unit tests for the new serialization functions to ensure correctness and reliability of data formatting.
2026-02-12 20:10:09 +03:00

58 lines
2.0 KiB
JavaScript

// Escape for safe HTML text content (prevents XSS when inserting into HTML)
function escapeHtml(text) {
if (text == null) return '';
const s = String(text);
return s
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
// Format bytes to GB (matches Django convert_bytes filter default)
function formatBytes(bytes, targetUnit = 'GB') {
if (bytes == null || isNaN(Number(bytes))) return '0';
const b = Number(bytes);
const factors = { B: 1, KB: 1024, MB: 1024 * 1024, GB: 1024 ** 3, TB: 1024 ** 4 };
const unit = (targetUnit || 'GB').toUpperCase();
const factor = factors[unit] || factors.GB;
return (b / factor).toFixed(1);
}
// Color utilities
const getCSSVar = (varName) => {
return getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
}
function getColorWithOpacity(className) {
const element = document.createElement('div');
element.className = className;
element.style.opacity = '1'; // Force opacity
element.textContent = '.';
document.body.appendChild(element);
const computedColor = window.getComputedStyle(element).color;
document.body.removeChild(element);
return computedColor;
}
// Format audit date for display (ISO string -> short date, e.g. "Feb 1")
function formatAuditDate(isoString) {
if (!isoString) return '';
try {
return new Date(isoString).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
} catch (e) {
return '';
}
}
// Utility function to calculate mean and standard deviation
function calculateStats(data) {
if (!data || data.length === 0) return { mean: 0, std: 0 };
const mean = data.reduce((a, b) => a + b, 0) / data.length;
const variance = data.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / data.length;
const std = Math.sqrt(variance);
return { mean, std };
}