mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-04-10 21:03:01 +00:00
a8c85dd015d6e12105f592f62cdffe69fdf954cb
3 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
a8c85dd015 |
feat(widgets): add modular widget system for schedule and common inputs (#213)
* 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> |
||
|
|
d0ad2031c8 |
fix(ui): wrap plugin tabs to new lines instead of scrolling (#201)
* fix(ui): wrap plugin tabs to new lines instead of scrolling Change plugin tabs row from overflow-x-auto to flex-wrap so that when many plugins are installed, tabs break to new lines instead of becoming smaller or requiring horizontal scrolling. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): use gap-x instead of space-x for proper wrapped row alignment Switch from space-x-* to gap-x-* utilities so wrapped rows align correctly without indentation on subsequent lines. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): add missing flex-wrap and gap utilities to CSS The project uses hand-written Tailwind-like CSS, not actual Tailwind. Added missing utility classes needed for plugin tabs wrapping: - flex-wrap - gap-x-4, gap-x-6, gap-x-8, gap-y-2 - lg:gap-x-6, xl:gap-x-8 responsive variants Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): apply flex-wrap to system tabs row Apply the same wrapping behavior to the system tabs row (Overview, General, WiFi, etc.) so they also wrap to new lines on smaller viewports instead of scrolling. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): constrain tab container width to enable flex-wrap Add max-w-full and overflow-hidden to tab row containers to properly constrain their width, allowing flex-wrap to work correctly. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): remove overflow-hidden that was hiding tabs Revert the max-w-full overflow-hidden approach as it was hiding content. Keep both rows using flex-wrap with gap utilities. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: Add custom-leagues widget support for soccer plugin - Add server-side template rendering for x-widget="custom-leagues" - Renders table with Name, League Code, Priority, Enabled columns - Includes inline JavaScript for add/remove row functionality - Uses indexed field naming for proper array serialization - Shows common ESPN league codes as hint This enables the soccer scoreboard plugin's custom leagues feature to work properly in the web UI. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): reduce tab gap spacing for tighter layout Reduce horizontal gap between tabs from gap-x-4/6/8 to gap-x-2/3/4 for a more compact appearance. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor(widget): Replace custom-leagues with generic array-table widget - Add generic array-table widget that reads columns from schema - Support x-columns to specify which columns to display - Auto-detect columns from items.properties if x-columns not specified - Remove hardcoded custom-leagues implementation - Any plugin can now use x-widget: "array-table" for array-of-objects Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): use data attributes for array table button to avoid JSON escaping issues Move JSON blobs (item_properties and display_columns) from inline onclick to data-* attributes with proper HTML entity escaping via Jinja's |e filter. Update addArrayTableRow() to read and parse these data attributes. This fixes HTML attribute breakage caused by tojson emitting double quotes inside the onclick attribute value. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): update Add button state when array table rows change Add updateAddButtonState() helper that toggles the Add button's disabled attribute and opacity based on current row count vs maxItems. Called after addArrayTableRow() and removeArrayTableRow(), and also on page load to ensure correct initial state. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(ui): add try/catch for JSON parsing in addArrayTableRow Wrap JSON.parse calls for data-item-properties and data-display-columns in try/catch blocks with fallback to {} and [] respectively. Logs error with raw attribute values to help debug malformed JSON. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(array-table): Fix getValue input name validation and setValue Add button state sync - Fix getValue to use early-continue guard preventing errors on inputs without names - Add updateAddButtonState call in setValue to refresh Add button state after repopulating rows * fix(ui): make Configure button larger than Uninstall in plugin manager Swapped button sizes in installed plugins section - Configure button is now the largest (flex-2), Update is medium (flex-1), and Uninstall is smallest (no flex class). This prioritizes the Configure action over Uninstall. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix(ui): correct forEach continue and plugin button flex sizing - Replace invalid continue with return in array-table forEach callback - Remove redundant hidden input type check in array-table getValue - Fix plugin button sizing using inline flex styles instead of invalid flex-2 class - Configure button now properly sized at flex: 2, Update and Uninstall at flex: 1 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * refactor(ui): reorganize plugin buttons into two-row layout Configure button now takes full width on first row, while Update and Uninstall buttons share the second row evenly. This makes Configure more prominent and separates destructive actions to a second row. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix(ui): override inline-flex on Configure button to enable full width The .btn class uses display: inline-flex which prevents w-full from working. Added inline style to override with display: flex and width: 100% so the Configure button properly takes the full width of its row. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix(ui): use inline styles for plugin action buttons layout Replace Tailwind classes with explicit inline styles to ensure proper two-row layout for plugin action buttons. Configure button on first row at full width, Update and Uninstall sharing second row evenly. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> --------- Co-authored-by: Chuck <chuck@example.com> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> |
||
|
|
71584d4361 |
Feature/widget registry system (#190)
* chore: Update basketball-scoreboard submodule for odds font fix
* feat(widgets): Add widget registry system for plugin configuration forms
- Create core widget registry system (registry.js, base-widget.js)
- Extract existing widgets to separate modules:
- file-upload.js: Image upload with drag-and-drop, preview, delete, scheduling
- checkbox-group.js: Multi-select checkboxes for array fields
- custom-feeds.js: Table-based RSS feed editor with logo uploads
- Implement plugin widget loading system (plugin-loader.js)
- Add comprehensive documentation (widget-guide.md, README.md)
- Include example custom widget (example-color-picker.js)
- Maintain backwards compatibility with existing plugins
- All widget handlers available globally for existing functionality
This enables:
- Reusable UI components for plugin configuration forms
- Third-party plugins to create custom widgets without modifying LEDMatrix
- Modular widget architecture for future enhancements
Existing plugins (odds-ticker, static-image, news) continue to work without changes.
* fix(widgets): Security and correctness fixes for widget system
- base-widget.js: Fix escapeHtml to always escape (coerce to string first)
- base-widget.js: Add sanitizeId helper for safe DOM ID usage
- base-widget.js: Use DOM APIs in showError instead of innerHTML
- checkbox-group.js: Normalize types in setValue for consistent comparison
- custom-feeds.js: Implement setValue with full row creation logic
- example-color-picker.js: Validate hex colors before using in style attributes
- file-upload.js: Replace innerHTML with DOM creation to prevent XSS
- file-upload.js: Preserve open schedule editors when updating image list
- file-upload.js: Normalize types when filtering deleted files
- file-upload.js: Sanitize imageId in openImageSchedule and all schedule handlers
- file-upload.js: Fix max-files check order and use allowed_types from config
- README.md: Add security guidance for ID sanitization in examples
* fix(widgets): Additional security and error handling improvements
- scripts/update_plugin_repos.py: Add explicit UTF-8 encoding and proper error handling for file operations
- scripts/update_plugin_repos.py: Fix git fetch/pull error handling with returncode checks and specific exception types
- base-widget.js: Guard notify method against undefined/null type parameter
- file-upload.js: Remove inline handlers from schedule template, use addEventListener with data attributes
- file-upload.js: Update hideUploadProgress to show dynamic file types from config instead of hardcoded list
- README.md: Update Color Picker example to use sanitized fieldId throughout
* fix(widgets): Update Slider example to use sanitized fieldId
- Add sanitizeId helper to Slider example render, getValue, and setValue methods
- Use sanitizedFieldId for all DOM IDs and query selectors
- Maintain consistency with Color Picker example pattern
* fix(plugins_manager): Move configurePlugin and togglePlugin to top of file
- Move configurePlugin and togglePlugin definitions to top level (after uninstallPlugin)
- Ensures these critical functions are available immediately when script loads
- Fixes 'Critical functions not available after 20 attempts' error
- Functions are now defined before any HTML rendering checks
* fix(plugins_manager): Fix checkbox state saving using querySelector
- Add escapeCssSelector helper function for safe CSS selector usage
- Replace form.elements[actualKey] with form.querySelector for boolean fields
- Properly handle checkbox checked state using element.checked property
- Fix both schema-based and schema-less boolean field processing
- Ensures checkboxes with dot notation names (nested fields) work correctly
Fixes issue where checkbox states were not properly saved when field names
use dot notation (e.g., 'display.scroll_enabled'). The form.elements
collection doesn't reliably handle dot notation in bracket notation access.
* fix(base.html): Fix form element lookup for dot notation field names
- Add escapeCssSelector helper function (both as method and standalone)
- Replace form.elements[key] with form.querySelector for element type detection
- Fixes element lookup failures when field names use dot notation
- Ensures checkbox and multi-select skipping logic works correctly
- Applies fix to both Alpine.js method and standalone function
This complements the fix in plugins_manager.js to ensure all form
element lookups handle nested field names (e.g., 'display.scroll_enabled')
reliably across the entire web interface.
* fix(plugins_manager): Add race condition protection to togglePlugin
- Initialize window._pluginToggleRequests map for per-plugin request tokens
- Generate unique token for each toggle request to track in-flight requests
- Disable checkbox and wrapper UI during request to prevent overlapping toggles
- Add visual feedback with opacity and pointer-events-none classes
- Verify token matches before applying response updates (both success and error)
- Ignore out-of-order responses to preserve latest user intent
- Clear token and re-enable UI after request completes
Prevents race conditions when users rapidly toggle plugins, ensuring
only the latest toggle request's response affects the UI state.
* refactor(escapeCssSelector): Use CSS.escape() for better selector safety
- Prefer CSS.escape() when available for proper CSS selector escaping
- Handles edge cases: unicode characters, leading digits, and spec compliance
- Keep regex-based fallback for older browsers without CSS.escape support
- Update all three instances: plugins_manager.js and both in base.html
CSS.escape() is the standard API for escaping CSS selectors and provides
more robust handling than custom regex, especially for unicode and edge cases.
* fix(plugins_manager): Fix syntax error - missing closing brace for file-upload if block
- Add missing closing brace before else-if for checkbox-group widget
- Fixes 'Unexpected token else' error at line 3138
- The if block for file-upload widget (line 3034) was missing its closing brace
- Now properly structured: if (file-upload) { ... } else if (checkbox-group) { ... }
* fix(plugins_manager): Fix indentation in file-upload widget if block
- Properly indent all code inside the file-upload if block
- Fix template string closing brace indentation
- Ensures proper structure: if (file-upload) { ... } else if (checkbox-group) { ... }
- Resolves syntax error at line 3138
* fix(plugins_manager): Skip checkbox-group [] inputs to prevent config leakage
- Add skip logic for keys ending with '[]' in handlePluginConfigSubmit
- Prevents checkbox-group bracket notation inputs from leaking into config
- Checkbox-group widgets emit name="...[]" checkboxes plus a _data JSON field
- The _data field is already processed correctly, so [] inputs are redundant
- Prevents schema validation failures and extra config keys
The checkbox-group widget creates:
1. Individual checkboxes with name="fullKey[]" (now skipped)
2. Hidden input with name="fullKey_data" containing JSON array (processed)
3. Sentinel hidden input with name="fullKey[]" and empty value (now skipped)
* fix(plugins_manager): Normalize string booleans when checkbox input is missing
- Fix boolean field processing to properly normalize string booleans in fallback path
- Prevents "false"/"0" from being coerced to true when checkbox element is missing
- Handles common string boolean representations: 'true', 'false', '1', '0', 'on', 'off'
- Applies to both schema-based (lines 2386-2400) and schema-less (lines 2423-2433) paths
When a checkbox element cannot be found, the fallback logic now:
1. Checks if value is a string and normalizes known boolean representations
2. Treats undefined/null as false
3. Coerces other types to boolean using Boolean()
This ensures string values like "false" or "0" are correctly converted to false
instead of being treated as truthy non-empty strings.
* fix(base.html): Improve escapeCssSelector fallback to match CSS.escape behavior
- Handle leading digits by converting to hex escape (e.g., '1' -> '\0031 ')
- Handle leading whitespace by converting to hex escape (e.g., ' ' -> '\0020 ')
- Escape internal spaces as '\ ' (preserving space in hex escapes)
- Ensures trailing space after hex escapes per CSS spec
- Applies to both Alpine.js method and standalone function
The fallback now better matches CSS.escape() behavior for older browsers:
1. Escapes leading digits (0-9) as hex escapes with trailing space
2. Escapes leading whitespace as hex escapes with trailing space
3. Escapes all special characters as before
4. Escapes internal spaces while preserving hex escape format
This prevents selector injection issues with field names starting with digits
or whitespace, matching the standard CSS.escape() API behavior.
---------
Co-authored-by: Chuck <chuck@example.com>
|