Spaces:
Running
Running
File size: 11,306 Bytes
b263139 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | // ThaiRice NDVI Visualizer - Main JavaScript
// Initialize application
document.addEventListener('DOMContentLoaded', function() {
console.log('ThaiRice NDVI Visualizer initialized');
// Initialize components
initNDVIInteractions();
initDateDisplay();
initHealthScoreAnimation();
initChartSimulation();
// Set up service worker for offline functionality
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').catch(console.error);
}
});
// NDVI Map Interactions
function initNDVIInteractions() {
const mapControls = document.querySelectorAll('.map-control');
const ndviImage = document.querySelector('img[alt="Rice Field NDVI Map"]');
mapControls.forEach(control => {
control.addEventListener('click', function(e) {
e.preventDefault();
const action = this.querySelector('i').getAttribute('data-feather');
switch(action) {
case 'zoom-in':
simulateZoom(1.2);
break;
case 'zoom-out':
simulateZoom(0.8);
break;
case 'maximize':
toggleFullscreen(ndviImage);
break;
}
// Add click feedback
this.classList.add('scale-95');
setTimeout(() => this.classList.remove('scale-95'), 150);
});
});
}
// Simulate zoom effect
function simulateZoom(factor) {
const mapContainer = document.querySelector('.relative.h-96');
const img = mapContainer.querySelector('img');
// Store current transform
const currentTransform = img.style.transform || 'scale(1)';
const currentScale = parseFloat(currentTransform.match(/scale\(([^)]+)\)/)?.[1] || 1);
const newScale = currentScale * factor;
// Limit zoom range
if (newScale < 0.5 || newScale > 3) return;
img.style.transform = `scale(${newScale})`;
img.style.transition = 'transform 0.3s ease';
// Update controls state
updateZoomControls(newScale);
}
function updateZoomControls(scale) {
const zoomIn = document.querySelector('[data-feather="zoom-in"]').closest('button');
const zoomOut = document.querySelector('[data-feather="zoom-out"]').closest('button');
zoomIn.disabled = scale >= 3;
zoomOut.disabled = scale <= 0.5;
}
function toggleFullscreen(element) {
if (!document.fullscreenElement) {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
}
}
// Initialize date display
function initDateDisplay() {
const dateElements = document.querySelectorAll('[data-date-format]');
const now = new Date();
dateElements.forEach(element => {
const format = element.getAttribute('data-date-format');
let formattedDate;
switch(format) {
case 'relative':
formattedDate = getRelativeDate(now);
break;
case 'full':
formattedDate = now.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
break;
default:
formattedDate = now.toLocaleDateString();
}
if (element.tagName === 'INPUT') {
element.value = formattedDate;
} else {
element.textContent = formattedDate;
}
});
}
function getRelativeDate(date) {
const now = new Date();
const diffMs = now - date;
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffMins < 1) return 'Just now';
if (diffMins < 60) return `${diffMins} minutes ago`;
if (diffHours < 24) return `${diffHours} hours ago`;
if (diffDays === 1) return 'Yesterday';
if (diffDays < 7) return `${diffDays} days ago`;
return date.toLocaleDateString();
}
// Animate health score
function initHealthScoreAnimation() {
const healthScore = document.querySelector('.inline-flex.items-center.justify-center');
if (!healthScore) return;
// Add animation class
healthScore.classList.add('pulse-slow');
// Simulate real-time updates
setInterval(() => {
const randomChange = Math.random() * 0.02 - 0.01; // +/- 1%
const currentScore = parseFloat(healthScore.querySelector('span').textContent);
const newScore = Math.min(100, Math.max(0, currentScore + randomChange));
healthScore.querySelector('span').textContent = `${newScore.toFixed(1)}%`;
// Update gradient based on score
updateHealthGradient(newScore);
}, 10000); // Update every 10 seconds
}
function updateHealthGradient(score) {
const healthIndicator = document.querySelector('.health-indicator');
if (!healthIndicator) return;
let color;
if (score >= 80) color = '#10b981'; // Green
else if (score >= 60) color = '#f59e0b'; // Amber
else color = '#ef4444'; // Red
healthIndicator.style.setProperty('--indicator-color', color);
}
// Simulate chart data updates
function initChartSimulation() {
const chartBars = document.querySelectorAll('.bg-gradient-to-t');
if (!chartBars.length) return;
// Animate bars on load
setTimeout(() => {
chartBars.forEach((bar, index) => {
bar.style.height = bar.style.height || getComputedStyle(bar).height;
bar.style.height = '0';
setTimeout(() => {
bar.style.transition = 'height 0.8s ease';
bar.style.height = bar.dataset.originalHeight || bar.style.height;
}, index * 100);
});
}, 500);
// Simulate real-time updates
setInterval(() => {
const currentNDVI = document.querySelector('.text-2xl.font-bold.text-green-700');
if (!currentNDVI) return;
const currentValue = parseFloat(currentNDVI.textContent);
const randomChange = (Math.random() * 0.04 - 0.02); // +/- 0.02
const newValue = Math.min(0.9, Math.max(0.1, currentValue + randomChange));
// Animate the change
animateValue(currentNDVI, currentValue, newValue, 1000);
// Update trend indicator
updateTrendIndicator(randomChange);
}, 15000); // Update every 15 seconds
}
function animateValue(element, start, end, duration) {
const startTime = performance.now();
function update(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const current = start + (end - start) * progress;
element.textContent = current.toFixed(2);
if (progress < 1) {
requestAnimationFrame(update);
}
}
requestAnimationFrame(update);
}
function updateTrendIndicator(change) {
const trendElement = document.querySelector('.text-xs.text-green-600.mt-1');
if (!trendElement) return;
const icon = trendElement.querySelector('i');
const text = trendElement.querySelector('span') || trendElement;
if (change > 0) {
icon.setAttribute('data-feather', 'trending-up');
text.textContent = `+${Math.abs(change).toFixed(2)} from last update`;
trendElement.className = 'text-xs text-green-600 mt-1';
} else if (change < 0) {
icon.setAttribute('data-feather', 'trending-down');
text.textContent = `-${Math.abs(change).toFixed(2)} from last update`;
trendElement.className = 'text-xs text-red-600 mt-1';
} else {
icon.setAttribute('data-feather', 'minus');
text.textContent = 'No change from last update';
trendElement.className = 'text-xs text-gray-600 mt-1';
}
feather.replace();
}
// Export functionality
function exportNDVIReport() {
const reportData = {
fieldId: 'TH-RF-2023-042',
location: 'Suphan Buri, Thailand',
area: '15.3 hectares',
ndviScore: document.querySelector('.text-4xl.font-bold.text-white')?.textContent || '82%',
currentNDVI: document.querySelector('.text-2xl.font-bold.text-green-700')?.textContent || '0.62',
lastUpdated: new Date().toISOString(),
recommendations: Array.from(document.querySelectorAll('.bg-gradient-to-br')).map(card => ({
category: card.querySelector('h3')?.textContent,
status: card.querySelector('p.text-sm')?.textContent,
details: card.querySelector('p.text-gray-700')?.textContent
}))
};
// Create download link
const dataStr = JSON.stringify(reportData, null, 2);
const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
const exportFileDefaultName = `ndvi-report-${reportData.fieldId}-${new Date().toISOString().split('T')[0]}.json`;
const linkElement = document.createElement('a');
linkElement.setAttribute('href', dataUri);
linkElement.setAttribute('download', exportFileDefaultName);
linkElement.click();
// Show notification
showNotification('Report exported successfully!', 'success');
}
// Notification system
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.className = `fixed top-4 right-4 z-50 px-6 py-4 rounded-lg shadow-lg transform transition-transform duration-300 translate-x-full ${
type === 'success' ? 'bg-green-500 text-white' :
type === 'error' ? 'bg-red-500 text-white' :
'bg-blue-500 text-white'
}`;
notification.textContent = message;
document.body.appendChild(notification);
// Animate in
setTimeout(() => {
notification.classList.remove('translate-x-full');
}, 10);
// Auto remove after 5 seconds
setTimeout(() => {
notification.classList.add('translate-x-full');
setTimeout(() => notification.remove(), 300);
}, 5000);
}
// Error handling
window.addEventListener('error', function(e) {
console.error('Application error:', e.error);
showNotification('An error occurred. Please refresh the page.', 'error');
});
// Performance monitoring
if ('performance' in window) {
window.addEventListener('load', function() {
const timing = performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;
console.log(`Page loaded in ${loadTime}ms`);
if (loadTime > 3000) {
console.warn('Page load time exceeds 3 seconds');
}
});
} |