3.0 KiB
3.0 KiB
Template Light Refactoring Plan: Consolidate Color Mode Handling
Current State Analysis
The LightTemplate class in homeassistant/components/template/light.py (~1000 lines) has massive duplication for each color mode:
- 7 color modes: RGB, RGBW, RGBWW, HS, legacy COLOR, COLOR_TEMP, BRIGHTNESS, EFFECT
- Each mode has: script variable, template variable, state variable, property, template setup block, update callback, and turn_on handling logic
Refactoring Goal
Create a ColorModeHandler dataclass/protocol that encapsulates per-mode configuration (script, template, state attr, property name, ColorMode enum, validation/update logic). Loop over supported modes instead of 7× copy-pasted blocks.
Suggested 5-Turn Plan
Turn 1: Define ColorModeHandler and Refactor init
- Create
ColorModeHandlerdataclass with fields:color_mode,script_attr,template_attr,state_attr,property_name,update_callback,validation_fn,turn_on_priority,script_param_builder - In
__init__, build a listself._color_mode_handlersby checking which scripts/templates are configured - Replace individual
_rgb_script,_hs_script, etc. with handler-based lookup - Compute
supported_color_modesfrom handlers dynamically
Turn 2: Refactor _async_setup_templates
- Replace 8 separate
if self._xxx_template:blocks with a loop overself._color_mode_handlers - Each handler registers its template with
add_template_attributeusing its update callback - Handle special cases (min/max mireds, transition, effect_list) separately or as additional handlers
Turn 3: Consolidate Update Callbacks and Properties
- Replace
_update_rgb,_update_rgbw,_update_rgbww,_update_hs,_update_temperature,_update_brightnesswith a generic_update_color_mode(handler, value)method - Use handler's
validation_fnfor mode-specific validation - Replace individual property methods (
rgb_color,hs_color, etc.) with a generic approach using__getattr__or a property map
Turn 4: Refactor async_turn_on
- Replace the long if/elif chain (lines 300-450) with a loop over handlers sorted by
turn_on_priority - Each handler provides a
script_param_builder(kwargs)that returns(script, params)orNone - First matching handler wins, executes its script with built params
- Handle optimistic state setting generically per handler
Turn 5: Verify Tests Pass & Clean Up
- Run
pytest tests/components/template/test_light.py -v - Fix any regressions
- Remove now-unused constants (CONF_RGB_ACTION, CONF_RGB_TEMPLATE, etc. - but keep for schema compatibility)
- Remove unused instance variables
- Ensure all 50+ tests still pass
Key Design Decisions
- Keep schema constants (CONF_*) for backward compatibility
- Handler priority order: EFFECT > RGBWW > RGBW > RGB > HS > COLOR > COLOR_TEMP > BRIGHTNESS > ONOFF (matches current if/elif order)
- Validation functions can be closures or static methods capturing mode-specific bounds
- Script param builders handle the different variable names each script expects (h/s vs r/g/b vs rgbww tuple, etc.)