Files
LEDMatrix/web_interface/static/v3/js/widgets/timezone-selector.js
T
ChuckandClaude Opus 5.5 a8b3e86775 refactor(web): delete dead routes, JS files and duplicate definitions (#609)
* refactor(web): drop validators nothing calls

escape_html, validate_image_url, validate_font_awesome_class,
validate_mime_type, validate_numeric_range, validate_string_length and
sanitize_plugin_config had no callers outside their own tests. Only
validate_file_upload (fonts upload) is imported by the web interface.

dedup_unique_arrays is kept: its one caller in save_plugin_config was
removed by the unrelated sync PR (#330), which looks accidental.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(api): remove the music-auth and of-the-day JSON routes

POST /plugins/authenticate/spotify and /plugins/authenticate/ytm had no
caller but their tests: the music plugin authenticates through its
web_ui_actions (authenticate_spotify.py / authenticate_ytm.py) via
/plugins/action.

POST /plugins/of-the-day/json/upload and /json/delete looked the plugin
up by the id ledmatrix-of-the-day (its manifest id is of-the-day), were
reachable only from a file_type "json" upload field that no schema
declares, and put the plugin directory on sys.path per request to
import scripts.update_config. of-the-day manages its files through
plugin-file-manager and its own web_ui_actions.

The of-the-day branch of GET /plugins/config stays: it matches the real
manifest id and still merges the on-disk category files into the form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(api): read managers only from the blueprints

api_v3/__init__.py and pages_v3.py declared module globals
(plugin_store_manager, saved_repositories_manager, schema_manager,
operation_queue, plugin_state_manager, operation_history, sync_manager,
config_manager, plugin_manager) that nothing assigns: app.py sets the
managers as attributes on the Blueprint objects, and every route reads
them there. The one reader, backup restore's fallback to the module
plugin_store_manager, could only ever fall back to None.

_ensure_cache_manager() built a second CacheManager in the web process
instead of using the one app.py puts on api_v3. The display routes now
read api_v3.cache_manager, creating it on the blueprint only when
nothing set it (the same None handling as the /cache routes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(web): drop run.sh and the unused log_config_change

web_interface/run.sh was referenced only by web_interface/README.md;
the service starts the UI through scripts/utils/start_web_conditionally.py
and the README already documents `python3 web_interface/start.py`.
log_config_change() in web_interface/logging_config.py was never called.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): delete unreferenced store_manager.js, diff_viewer.js, htmx-sse.js

- js/plugins/store_manager.js (window.PluginStoreManager) and
  js/config/diff_viewer.js (window.ConfigDiffViewer) were loaded on every
  page but nothing reads either global.
- htmx-sse.js (plus its CDN fallback) was loaded after HTMX, but no
  template or plugin page uses sse-connect / hx-ext="sse": the live
  streams run through LEDStreams in app-shell.js.

js/plugins/state_manager.js stays: install_manager.js's updateAll()
reads and refreshes window.PluginStateManager.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): remove app.js helpers nothing calls

- hexToRgb, rgbToHex, validateForm, uploadFont and switchTab (whose
  'switch-tab' event had no listener) have no caller in the templates,
  static JS or the plugin monorepo.
- installPlugin: plugins_manager.js (loaded last) assigns
  window.installPlugin, and its own store cards are the only callers.
- The showNotification fallback could never install: app-shell.js is
  deferred ahead of app.js and defines the same fallback at top level.
- performanceMonitor only logged with ?debug=perf and read an unset
  this.measures; the marks it took on every load had no reader.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): drop app-shell.js refreshPlugin

A top-level function in app-shell.js, so a window global, but nothing
calls it (no inline handler, no window lookup, no string-built name).

The other plugin actions in that block stay. updatePlugin is the live
window.updatePlugin: plugins_manager.js only installs its own copy when
none exists. uninstallPlugin/pollUninstallOperation, updateAllPlugins,
executePluginAction and toggleNestedSection are replaced by later
deferred scripts, but a click that lands while those scripts are still
downloading reaches the app-shell copies, so removing them is not a
pure no-op.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): remove definitions plugins_manager.js always overrides

All of these are replaced before anything can call them, checked
against the load order in base.html and the live window.* values:

- openOnDemandModal/requestOnDemandStop stubs: the IIFE later in the
  same script assigns the real functions synchronously.
- updatePlugin and uninstallPlugin stubs (`window.X || stub`): app-shell.js
  already defined both, so the fallback never installed. Same for the
  later updatePlugin override, gated on the live function containing
  '[UPDATE]', which app-shell.js's never does.
- The first addArrayObjectItem/removeArrayObjectItem: reassigned by the
  top-level copies after the IIFE.
- The first `function formatDate` in the IIFE: a later declaration of
  the same name in the same scope wins.
- deleteUploadedImage, getCurrentImages, showUploadProgress,
  formatFileSize and getScheduleSummary: character-for-character
  copies of js/widgets/file-upload.js, which stays the owner.
- `typeof X === 'undefined'` fallbacks and `typeof X !== 'undefined'`
  re-exports after the IIFE: always false, or a self-assignment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): render the shell directly and delete index.html

index.html extended base.html with {% block content %}, but base.html
defines no blocks, so none of index.html ever rendered: rendering both
with jinja2 gives byte-identical output. index() still loaded the config,
read config.json and config_secrets.json raw and json.dumps'd them on
every page load for variables base.html never reads, and flashed errors
that base.html never shows. It now renders base.html with no context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): stop htmx-config.js replacing console.error and console.warn

It swapped both globals for filters that dropped any error mentioning
insertBefore / "Cannot read properties of null" when "htmx" appeared in
the message or stack, and a list of Permissions-Policy warnings. That
hid real errors from every script on the page, and made every logged
error and warning report htmx-config.js as its source. The beforeSwap
target validation above it, which prevents the insertBefore errors in
the first place, stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(web): quiet the widget load announcements and debug logs

About 30 lines hit the console on every page load: one "... widget
registered" per widget file, one "[WidgetRegistry] Registered widget: X"
per registration, plus the registry, base widget and plugin loader
announcing themselves. The load-time announcements are removed; the
per-call ones (registry register, plugin widget loads, "Render called")
now go through the page's debugLog switch (localStorage.pluginDebug),
guarded because the widgets also load in node tests without it.
fonts.html and wifi.html debug logging goes through debugLog as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): drop the removed music-auth and of-the-day JSON routes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:36:53 -04:00

418 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, '&quot;').replace(/'/g, '&#39;');
}
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 {
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 {
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);
});
})();
})();