mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-04-10 13:02:59 +00:00
* feat(widgets): add modular widget system for schedule and common inputs Add 15 new reusable widgets following the widget registry pattern: - schedule-picker: composite widget for enable/mode/time configuration - day-selector: checkbox group for days of the week - time-range: paired start/end time inputs with validation - text-input, number-input, textarea: enhanced text inputs - toggle-switch, radio-group, select-dropdown: selection widgets - slider, color-picker, date-picker: specialized inputs - email-input, url-input, password-input: validated string inputs Refactor schedule.html to use the new schedule-picker widget instead of inline JavaScript. Add x-widget support in plugin_config.html for all new widgets so plugins can use them via schema configuration. Fix form submission for checkboxes by using hidden input pattern to ensure unchecked state is properly sent via JSON-encoded forms. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): improve security, validation, and form binding across widgets - Fix XSS vulnerability: escapeHtml now escapes quotes in all widget fallbacks - color-picker: validate presets with isValidHex(), use data attributes - date-picker: add placeholder attribute support - day-selector: use options.name for hidden input form binding - password-input: implement requireUppercase/Number/Special validation - radio-group: fix value injection using this.value instead of interpolation - schedule-picker: preserve day values when disabling (don't clear times) - select-dropdown: remove undocumented searchable/icons options - text-input: apply patternMessage via setCustomValidity - time-range: use options.name for hidden inputs - toggle-switch: preserve configured color from data attribute - url-input: combine browser and custom protocol validation - plugin_config: add widget support for boolean/number types, pass name to day-selector - schedule: handle null config gracefully, preserve explicit mode setting Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): validate day-selector input, consistent minLength default, escape JSON quotes - day-selector: filter incoming selectedDays to only valid entries in DAYS array (prevents invalid persisted values from corrupting UI/state) - password-input: use default minLength of 8 when not explicitly set (fixes inconsistency between render() and onInput() strength meter baseline) - plugin_config.html: escape single quotes in JSON hidden input values (prevents broken attributes when JSON contains single quotes) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(widgets): add global notification widget, consolidate duplicated code - Create notification.js widget with toast-style notifications - Support for success, error, warning, info types - Auto-dismiss with configurable duration - Stacking support with max notifications limit - Accessible with aria-live and role="alert" - Update base.html to load notification widget early - Replace duplicate showNotification in raw_json.html - Simplify fonts.html fallback notification - Net reduction of ~66 lines of duplicated code Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): escape options.name in all widgets, validate day-selector format Security fixes: - Escape options.name attribute in all 13 widgets to prevent injection - Affected: color-picker, date-picker, email-input, number-input, password-input, radio-group, select-dropdown, slider, text-input, textarea, toggle-switch, url-input Defensive coding: - day-selector: validate format option exists in DAY_LABELS before use - Falls back to 'long' format for unsupported/invalid format values Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(plugins): add type="button" to control buttons, add debug logging - Add type="button" attribute to refresh, update-all, and restart buttons to prevent potential form submission behavior - Add console logging to diagnose button click issues: - Log when event listeners are attached (and whether buttons found) - Log when handler functions are called Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): improve security and validation across widget inputs - color-picker.js: Add sanitizeHex() to validate hex values before HTML interpolation, ensuring only safe #rrggbb strings are used - day-selector.js: Escape inputName in hidden input name attribute - number-input.js: Sanitize and escape currentValue in input element - password-input.js: Validate minLength as non-negative integer, clamp invalid values to default of 8 - slider.js: Add null check for input element before accessing value - text-input.js: Clear custom validity before checkValidity() to avoid stale errors, re-check after setting pattern message - url-input.js: Normalize allowedProtocols to array, filter to valid protocol strings, and escape before HTML interpolation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): add defensive fallback for DAY_LABELS lookup in day-selector Extract labelMap with fallback before loop to ensure safe access even if format validation somehow fails. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(widgets): add timezone-selector widget with IANA timezone dropdown - Create timezone-selector.js widget with comprehensive IANA timezone list - Group timezones by region (US & Canada, Europe, Asia, etc.) - Show current UTC offset for each timezone - Display live time preview for selected timezone - Update general.html to use timezone-selector instead of text input - Add script tag to base.html for widget loading Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): suppress on-demand status notification on page load Change loadOnDemandStatus(true) to loadOnDemandStatus(false) during initPluginsPage() to prevent the "on-demand status refreshed" notification from appearing every time a tab is opened or the page is navigated. The notification should only appear on explicit user refresh. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * style(ui): soften notification close button appearance Replace blocky FontAwesome X icon with a cleaner SVG that has rounded stroke caps. Make the button circular, slightly transparent by default, and add smooth hover transitions for a more polished look. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): multiple security and validation improvements - color-picker.js: Ensure presets is always an array before map/filter - number-input.js: Guard against undefined options parameter - number-input.js: Sanitize and escape min/max/step HTML attributes - text-input.js: Clear custom validity in onInput to unblock form submit - timezone-selector.js: Replace legacy Europe/Belfast with Europe/London - url-input.js: Use RFC 3986 scheme pattern for protocol validation - general.html: Use |tojson filter to escape timezone value safely Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor(url-input): centralize RFC 3986 protocol validation Extract protocol normalization into reusable normalizeProtocols() helper function that validates against RFC 3986 scheme pattern. Apply consistently in render, validate, and onInput to ensure protocols like "git+ssh", "android-app" are properly handled everywhere. Also lowercase protocol comparison in isValidUrl(). Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(timezone-selector): use hidden input for form submission Replace direct select name attribute with a hidden input pattern to ensure timezone value is always properly serialized in form submissions. The hidden input is synced on change and setValue calls. This matches the pattern used by other widgets and ensures HTMX json-enc properly captures the value. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(general): preserve timezone dropdown value after save Add inline script to sync the timezone select with the hidden input value after form submission. This prevents the dropdown from visually resetting to the old value while the save has actually succeeded. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): preserve timezone selection across form submission Use before-request handler to capture the selected timezone value before HTMX processes the form, then restore it in after-request. This is more robust than reading from the hidden input which may also be affected by form state changes. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): add HTMX protection to timezone selector Add global HTMX event listeners in the timezone-selector widget that preserve the selected value across any form submissions. This is more robust than form-specific handlers as it protects the widget regardless of how/where forms are submitted. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * debug(widgets): add logging and prevent timezone widget re-init Add debug logging and guards to prevent the timezone widget from being re-initialized after it's already rendered. This should help diagnose why the dropdown is reverting after save. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * debug: add console logging to timezone HTMX protection * debug: add onChange logging to trace timezone selection * fix(widgets): use selectedIndex to force visual update in timezone dropdown The browser's select.value setter sometimes doesn't trigger a visual update when optgroup elements are present. Using selectedIndex instead forces the browser to correctly update the visible selection. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): force browser repaint on timezone dropdown restore Adding display:none/reflow/display:'' pattern to force browser to visually update the select element after changing selectedIndex. Increased timeout to 50ms for reliability. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * chore(widgets): remove debug logging from timezone selector Clean up console.log statements that were used for debugging the timezone dropdown visual update issue. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): improve HTMX after-request handler in general settings - Parse xhr.responseText with JSON.parse in try/catch instead of using nonstandard responseJSON property - Check xhr.status for 2xx success range - Show error notification for non-2xx responses - Default to safe fallback values if JSON parsing fails Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): add input sanitization and timezone validation - Sanitize minLength/maxLength in text-input.js to prevent attribute injection (coerce to integers, validate range) - Update Europe/Kiev to Europe/Kyiv (canonical IANA identifier) - Validate timezone currentValue against TIMEZONE_GROUPS before rendering Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): correct error message fallback in HTMX after-request handler Initialize message to empty string so error responses can use the fallback 'Failed to save settings' when no server message is provided. Previously, the truthy default 'Settings saved' would always be used. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): add constraint normalization and improve value validation - text-input: normalize minLength/maxLength so maxLength >= minLength - timezone-selector: validate setValue input against TIMEZONE_GROUPS - timezone-selector: sync hidden input to actual selected value - timezone-selector: preserve empty selections across HTMX requests Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(widgets): simplify HTMX restore using select.value and dispatch change event Replace selectedIndex manipulation with direct value assignment for cleaner placeholder handling, and dispatch change event to refresh timezone preview. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Chuck <chuck@example.com> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
420 lines
18 KiB
JavaScript
420 lines
18 KiB
JavaScript
/**
|
|
* LEDMatrix Timezone Selector Widget
|
|
*
|
|
* Dropdown for selecting IANA timezone with grouped regions.
|
|
*
|
|
* Schema example:
|
|
* {
|
|
* "timezone": {
|
|
* "type": "string",
|
|
* "x-widget": "timezone-selector",
|
|
* "x-options": {
|
|
* "showOffset": true,
|
|
* "placeholder": "Select timezone..."
|
|
* }
|
|
* }
|
|
* }
|
|
*
|
|
* @module TimezoneSelectorWidget
|
|
*/
|
|
|
|
(function() {
|
|
'use strict';
|
|
|
|
const base = window.BaseWidget ? new window.BaseWidget('TimezoneSelector', '1.0.0') : null;
|
|
|
|
function escapeHtml(text) {
|
|
if (base) return base.escapeHtml(text);
|
|
const div = document.createElement('div');
|
|
div.textContent = String(text);
|
|
return div.innerHTML.replace(/"/g, '"').replace(/'/g, ''');
|
|
}
|
|
|
|
function sanitizeId(id) {
|
|
if (base) return base.sanitizeId(id);
|
|
return String(id).replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
}
|
|
|
|
function triggerChange(fieldId, value) {
|
|
if (base) {
|
|
base.triggerChange(fieldId, value);
|
|
} else {
|
|
const event = new CustomEvent('widget-change', {
|
|
detail: { fieldId, value },
|
|
bubbles: true,
|
|
cancelable: true
|
|
});
|
|
document.dispatchEvent(event);
|
|
}
|
|
}
|
|
|
|
// IANA timezone list grouped by region
|
|
const TIMEZONE_GROUPS = {
|
|
'US & Canada': [
|
|
{ value: 'America/New_York', label: 'Eastern Time (New York)' },
|
|
{ value: 'America/Chicago', label: 'Central Time (Chicago)' },
|
|
{ value: 'America/Denver', label: 'Mountain Time (Denver)' },
|
|
{ value: 'America/Phoenix', label: 'Mountain Time - Arizona (Phoenix)' },
|
|
{ value: 'America/Los_Angeles', label: 'Pacific Time (Los Angeles)' },
|
|
{ value: 'America/Anchorage', label: 'Alaska Time (Anchorage)' },
|
|
{ value: 'Pacific/Honolulu', label: 'Hawaii Time (Honolulu)' },
|
|
{ value: 'America/Detroit', label: 'Eastern Time (Detroit)' },
|
|
{ value: 'America/Indiana/Indianapolis', label: 'Eastern Time (Indianapolis)' },
|
|
{ value: 'America/Toronto', label: 'Eastern Time (Toronto)' },
|
|
{ value: 'America/Vancouver', label: 'Pacific Time (Vancouver)' },
|
|
{ value: 'America/Edmonton', label: 'Mountain Time (Edmonton)' },
|
|
{ value: 'America/Winnipeg', label: 'Central Time (Winnipeg)' },
|
|
{ value: 'America/Halifax', label: 'Atlantic Time (Halifax)' },
|
|
{ value: 'America/St_Johns', label: 'Newfoundland Time (St. Johns)' }
|
|
],
|
|
'Mexico & Central America': [
|
|
{ value: 'America/Mexico_City', label: 'Mexico City' },
|
|
{ value: 'America/Cancun', label: 'Cancun' },
|
|
{ value: 'America/Tijuana', label: 'Tijuana' },
|
|
{ value: 'America/Guatemala', label: 'Guatemala' },
|
|
{ value: 'America/Costa_Rica', label: 'Costa Rica' },
|
|
{ value: 'America/Panama', label: 'Panama' },
|
|
{ value: 'America/El_Salvador', label: 'El Salvador' },
|
|
{ value: 'America/Tegucigalpa', label: 'Honduras' },
|
|
{ value: 'America/Managua', label: 'Nicaragua' },
|
|
{ value: 'America/Belize', label: 'Belize' }
|
|
],
|
|
'South America': [
|
|
{ value: 'America/Sao_Paulo', label: 'Sao Paulo' },
|
|
{ value: 'America/Buenos_Aires', label: 'Buenos Aires' },
|
|
{ value: 'America/Santiago', label: 'Santiago' },
|
|
{ value: 'America/Lima', label: 'Lima' },
|
|
{ value: 'America/Bogota', label: 'Bogota' },
|
|
{ value: 'America/Caracas', label: 'Caracas' },
|
|
{ value: 'America/La_Paz', label: 'La Paz' },
|
|
{ value: 'America/Montevideo', label: 'Montevideo' },
|
|
{ value: 'America/Asuncion', label: 'Asuncion' },
|
|
{ value: 'America/Guayaquil', label: 'Guayaquil' }
|
|
],
|
|
'Europe': [
|
|
{ value: 'Europe/London', label: 'London (GMT/BST)' },
|
|
{ value: 'Europe/Dublin', label: 'Dublin' },
|
|
{ value: 'Europe/Paris', label: 'Paris' },
|
|
{ value: 'Europe/Berlin', label: 'Berlin' },
|
|
{ value: 'Europe/Madrid', label: 'Madrid' },
|
|
{ value: 'Europe/Rome', label: 'Rome' },
|
|
{ value: 'Europe/Amsterdam', label: 'Amsterdam' },
|
|
{ value: 'Europe/Brussels', label: 'Brussels' },
|
|
{ value: 'Europe/Vienna', label: 'Vienna' },
|
|
{ value: 'Europe/Zurich', label: 'Zurich' },
|
|
{ value: 'Europe/Stockholm', label: 'Stockholm' },
|
|
{ value: 'Europe/Oslo', label: 'Oslo' },
|
|
{ value: 'Europe/Copenhagen', label: 'Copenhagen' },
|
|
{ value: 'Europe/Helsinki', label: 'Helsinki' },
|
|
{ value: 'Europe/Warsaw', label: 'Warsaw' },
|
|
{ value: 'Europe/Prague', label: 'Prague' },
|
|
{ value: 'Europe/Budapest', label: 'Budapest' },
|
|
{ value: 'Europe/Athens', label: 'Athens' },
|
|
{ value: 'Europe/Bucharest', label: 'Bucharest' },
|
|
{ value: 'Europe/Sofia', label: 'Sofia' },
|
|
{ value: 'Europe/Lisbon', label: 'Lisbon' },
|
|
{ value: 'Europe/Moscow', label: 'Moscow' },
|
|
{ value: 'Europe/Kyiv', label: 'Kyiv' },
|
|
{ value: 'Europe/Istanbul', label: 'Istanbul' }
|
|
],
|
|
'UK & Ireland': [
|
|
{ value: 'Europe/London', label: 'London' },
|
|
{ value: 'Europe/Dublin', label: 'Dublin' },
|
|
{ value: 'Europe/London', label: 'Belfast' } // Belfast uses Europe/London (canonical IANA identifier)
|
|
],
|
|
'Asia': [
|
|
{ value: 'Asia/Tokyo', label: 'Tokyo' },
|
|
{ value: 'Asia/Seoul', label: 'Seoul' },
|
|
{ value: 'Asia/Shanghai', label: 'Shanghai' },
|
|
{ value: 'Asia/Hong_Kong', label: 'Hong Kong' },
|
|
{ value: 'Asia/Taipei', label: 'Taipei' },
|
|
{ value: 'Asia/Singapore', label: 'Singapore' },
|
|
{ value: 'Asia/Kuala_Lumpur', label: 'Kuala Lumpur' },
|
|
{ value: 'Asia/Bangkok', label: 'Bangkok' },
|
|
{ value: 'Asia/Ho_Chi_Minh', label: 'Ho Chi Minh City' },
|
|
{ value: 'Asia/Jakarta', label: 'Jakarta' },
|
|
{ value: 'Asia/Manila', label: 'Manila' },
|
|
{ value: 'Asia/Kolkata', label: 'India (Kolkata)' },
|
|
{ value: 'Asia/Mumbai', label: 'Mumbai' },
|
|
{ value: 'Asia/Dhaka', label: 'Dhaka' },
|
|
{ value: 'Asia/Karachi', label: 'Karachi' },
|
|
{ value: 'Asia/Dubai', label: 'Dubai' },
|
|
{ value: 'Asia/Riyadh', label: 'Riyadh' },
|
|
{ value: 'Asia/Jerusalem', label: 'Jerusalem' },
|
|
{ value: 'Asia/Tehran', label: 'Tehran' },
|
|
{ value: 'Asia/Kabul', label: 'Kabul' },
|
|
{ value: 'Asia/Kathmandu', label: 'Kathmandu' },
|
|
{ value: 'Asia/Colombo', label: 'Colombo' },
|
|
{ value: 'Asia/Yangon', label: 'Yangon' }
|
|
],
|
|
'Australia & Pacific': [
|
|
{ value: 'Australia/Sydney', label: 'Sydney' },
|
|
{ value: 'Australia/Melbourne', label: 'Melbourne' },
|
|
{ value: 'Australia/Brisbane', label: 'Brisbane' },
|
|
{ value: 'Australia/Perth', label: 'Perth' },
|
|
{ value: 'Australia/Adelaide', label: 'Adelaide' },
|
|
{ value: 'Australia/Darwin', label: 'Darwin' },
|
|
{ value: 'Australia/Hobart', label: 'Hobart' },
|
|
{ value: 'Pacific/Auckland', label: 'Auckland' },
|
|
{ value: 'Pacific/Fiji', label: 'Fiji' },
|
|
{ value: 'Pacific/Guam', label: 'Guam' },
|
|
{ value: 'Pacific/Port_Moresby', label: 'Port Moresby' },
|
|
{ value: 'Pacific/Noumea', label: 'Noumea' }
|
|
],
|
|
'Africa': [
|
|
{ value: 'Africa/Cairo', label: 'Cairo' },
|
|
{ value: 'Africa/Johannesburg', label: 'Johannesburg' },
|
|
{ value: 'Africa/Lagos', label: 'Lagos' },
|
|
{ value: 'Africa/Nairobi', label: 'Nairobi' },
|
|
{ value: 'Africa/Casablanca', label: 'Casablanca' },
|
|
{ value: 'Africa/Algiers', label: 'Algiers' },
|
|
{ value: 'Africa/Tunis', label: 'Tunis' },
|
|
{ value: 'Africa/Accra', label: 'Accra' },
|
|
{ value: 'Africa/Addis_Ababa', label: 'Addis Ababa' },
|
|
{ value: 'Africa/Dar_es_Salaam', label: 'Dar es Salaam' }
|
|
],
|
|
'Atlantic': [
|
|
{ value: 'Atlantic/Reykjavik', label: 'Reykjavik (Iceland)' },
|
|
{ value: 'Atlantic/Azores', label: 'Azores' },
|
|
{ value: 'Atlantic/Cape_Verde', label: 'Cape Verde' },
|
|
{ value: 'Atlantic/Bermuda', label: 'Bermuda' }
|
|
],
|
|
'UTC': [
|
|
{ value: 'UTC', label: 'UTC (Coordinated Universal Time)' },
|
|
{ value: 'Etc/GMT', label: 'GMT (Greenwich Mean Time)' },
|
|
{ value: 'Etc/GMT+0', label: 'GMT+0' },
|
|
{ value: 'Etc/GMT-1', label: 'GMT-1 (UTC+1)' },
|
|
{ value: 'Etc/GMT-2', label: 'GMT-2 (UTC+2)' },
|
|
{ value: 'Etc/GMT+1', label: 'GMT+1 (UTC-1)' },
|
|
{ value: 'Etc/GMT+2', label: 'GMT+2 (UTC-2)' }
|
|
]
|
|
};
|
|
|
|
// Check if a timezone value exists in TIMEZONE_GROUPS
|
|
function isValidTimezone(value) {
|
|
if (!value || typeof value !== 'string') return false;
|
|
for (const timezones of Object.values(TIMEZONE_GROUPS)) {
|
|
for (const tz of timezones) {
|
|
if (tz.value === value) return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// Get current UTC offset for a timezone
|
|
function getTimezoneOffset(tz) {
|
|
try {
|
|
const now = new Date();
|
|
const formatter = new Intl.DateTimeFormat('en-US', {
|
|
timeZone: tz,
|
|
timeZoneName: 'shortOffset'
|
|
});
|
|
const parts = formatter.formatToParts(now);
|
|
const offsetPart = parts.find(p => p.type === 'timeZoneName');
|
|
return offsetPart ? offsetPart.value : '';
|
|
} catch (e) {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
window.LEDMatrixWidgets.register('timezone-selector', {
|
|
name: 'Timezone Selector Widget',
|
|
version: '1.0.0',
|
|
|
|
render: function(container, config, value, options) {
|
|
const fieldId = sanitizeId(options.fieldId || container.id || 'timezone_selector');
|
|
const xOptions = config['x-options'] || config['x_options'] || {};
|
|
const showOffset = xOptions.showOffset !== false;
|
|
const placeholder = xOptions.placeholder || 'Select timezone...';
|
|
const disabled = xOptions.disabled === true;
|
|
|
|
// Validate current value - must be a recognized timezone from TIMEZONE_GROUPS
|
|
const trimmedValue = (typeof value === 'string' && value.trim()) ? value.trim() : '';
|
|
const currentValue = isValidTimezone(trimmedValue) ? trimmedValue : '';
|
|
|
|
let html = `<div id="${fieldId}_widget" class="timezone-selector-widget" data-field-id="${fieldId}">`;
|
|
|
|
// Hidden input for form submission
|
|
html += `<input type="hidden" id="${fieldId}_data" name="${escapeHtml(options.name || fieldId)}" value="${escapeHtml(currentValue)}">`;
|
|
|
|
html += `
|
|
<select id="${fieldId}_input"
|
|
${disabled ? 'disabled' : ''}
|
|
onchange="window.LEDMatrixWidgets.getHandlers('timezone-selector').onChange('${fieldId}')"
|
|
class="form-select w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 ${disabled ? 'bg-gray-100 cursor-not-allowed' : 'bg-white'} text-black">
|
|
`;
|
|
|
|
// Placeholder option
|
|
html += `<option value="" ${!currentValue ? 'selected' : ''} disabled>${escapeHtml(placeholder)}</option>`;
|
|
|
|
// Build options grouped by region
|
|
for (const [groupName, timezones] of Object.entries(TIMEZONE_GROUPS)) {
|
|
html += `<optgroup label="${escapeHtml(groupName)}">`;
|
|
|
|
for (const tz of timezones) {
|
|
const isSelected = currentValue === tz.value;
|
|
let displayLabel = tz.label;
|
|
|
|
// Add UTC offset if enabled
|
|
if (showOffset) {
|
|
const offset = getTimezoneOffset(tz.value);
|
|
if (offset) {
|
|
displayLabel = `${tz.label} (${offset})`;
|
|
}
|
|
}
|
|
|
|
html += `<option value="${escapeHtml(tz.value)}" ${isSelected ? 'selected' : ''}>${escapeHtml(displayLabel)}</option>`;
|
|
}
|
|
|
|
html += '</optgroup>';
|
|
}
|
|
|
|
html += '</select>';
|
|
|
|
// Show current time in selected timezone
|
|
html += `<div id="${fieldId}_preview" class="text-sm text-gray-500 mt-2 ${currentValue ? '' : 'hidden'}">
|
|
<span class="font-medium">Current time:</span>
|
|
<span id="${fieldId}_time"></span>
|
|
</div>`;
|
|
|
|
html += '</div>';
|
|
|
|
container.innerHTML = html;
|
|
|
|
// Update time preview if value is set
|
|
if (currentValue) {
|
|
this.handlers.updateTimePreview(fieldId, currentValue);
|
|
}
|
|
},
|
|
|
|
getValue: function(fieldId) {
|
|
const safeId = sanitizeId(fieldId);
|
|
const input = document.getElementById(`${safeId}_input`);
|
|
return input ? input.value : '';
|
|
},
|
|
|
|
setValue: function(fieldId, value) {
|
|
const safeId = sanitizeId(fieldId);
|
|
const select = document.getElementById(`${safeId}_input`);
|
|
const hiddenInput = document.getElementById(`${safeId}_data`);
|
|
|
|
// Validate incoming value against known timezones
|
|
const requestedValue = (typeof value === 'string' && value.trim()) ? value.trim() : '';
|
|
const validValue = isValidTimezone(requestedValue) ? requestedValue : '';
|
|
|
|
if (select) {
|
|
// Only set to a value that exists in the select options
|
|
select.value = validValue;
|
|
}
|
|
|
|
// Read the actual selected value from the select element
|
|
const actualValue = select ? select.value : '';
|
|
|
|
if (hiddenInput) {
|
|
// Synchronize hidden input to the actual selected value
|
|
hiddenInput.value = actualValue;
|
|
}
|
|
|
|
this.handlers.updateTimePreview(fieldId, actualValue);
|
|
},
|
|
|
|
handlers: {
|
|
onChange: function(fieldId) {
|
|
const safeId = sanitizeId(fieldId);
|
|
const widget = window.LEDMatrixWidgets.get('timezone-selector');
|
|
const value = widget.getValue(fieldId);
|
|
|
|
// Update hidden input for form submission
|
|
const hiddenInput = document.getElementById(`${safeId}_data`);
|
|
if (hiddenInput) {
|
|
hiddenInput.value = value;
|
|
}
|
|
|
|
widget.handlers.updateTimePreview(fieldId, value);
|
|
triggerChange(fieldId, value);
|
|
},
|
|
|
|
updateTimePreview: function(fieldId, timezone) {
|
|
const safeId = sanitizeId(fieldId);
|
|
const previewEl = document.getElementById(`${safeId}_preview`);
|
|
const timeEl = document.getElementById(`${safeId}_time`);
|
|
|
|
if (!previewEl || !timeEl) return;
|
|
|
|
if (!timezone) {
|
|
previewEl.classList.add('hidden');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const now = new Date();
|
|
const formatter = new Intl.DateTimeFormat('en-US', {
|
|
timeZone: timezone,
|
|
weekday: 'short',
|
|
hour: '2-digit',
|
|
minute: '2-digit',
|
|
second: '2-digit',
|
|
hour12: true
|
|
});
|
|
timeEl.textContent = formatter.format(now);
|
|
previewEl.classList.remove('hidden');
|
|
} catch (e) {
|
|
previewEl.classList.add('hidden');
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
// Expose timezone data for external use
|
|
window.LEDMatrixWidgets.get('timezone-selector').TIMEZONE_GROUPS = TIMEZONE_GROUPS;
|
|
|
|
// HTMX form submission protection - preserve timezone selection across requests
|
|
// This handles cases where HTMX or other form handling might reset select values
|
|
(function setupHtmxProtection() {
|
|
let savedTimezoneValues = {};
|
|
|
|
// Before any HTMX request, save timezone select values (including empty selections)
|
|
document.body.addEventListener('htmx:beforeRequest', function(event) {
|
|
document.querySelectorAll('.timezone-selector-widget').forEach(function(widget) {
|
|
const fieldId = widget.dataset.fieldId;
|
|
if (fieldId) {
|
|
const select = document.getElementById(fieldId + '_input');
|
|
// Record value even if empty to preserve cleared selections
|
|
savedTimezoneValues[fieldId] = select ? select.value : '';
|
|
}
|
|
});
|
|
});
|
|
|
|
// After any HTMX request, restore timezone select values
|
|
document.body.addEventListener('htmx:afterRequest', function(event) {
|
|
// Delay to ensure any DOM updates have completed
|
|
setTimeout(function() {
|
|
Object.keys(savedTimezoneValues).forEach(function(fieldId) {
|
|
const select = document.getElementById(fieldId + '_input');
|
|
const hidden = document.getElementById(fieldId + '_data');
|
|
const savedValue = savedTimezoneValues[fieldId];
|
|
|
|
// Check for undefined, not truthiness, so empty strings are restored
|
|
if (select && savedValue !== undefined) {
|
|
// Set value directly (handles empty string and placeholders correctly)
|
|
select.value = savedValue;
|
|
|
|
// Dispatch change event to trigger timezone preview update
|
|
select.dispatchEvent(new Event('change'));
|
|
|
|
// Force browser to repaint by temporarily modifying a style
|
|
select.style.display = 'none';
|
|
void select.offsetHeight;
|
|
select.style.display = '';
|
|
}
|
|
if (hidden && savedValue !== undefined) {
|
|
hidden.value = savedValue;
|
|
}
|
|
});
|
|
}, 50);
|
|
});
|
|
})();
|
|
|
|
console.log('[TimezoneSelectorWidget] Timezone selector widget registered');
|
|
})();
|