Refactored Binding for better concern consideration
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
import logging
|
||||
import uuid
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
from typing import Optional, Any
|
||||
|
||||
from fasthtml.fastapp import fast_app
|
||||
from myutils.observable import make_observable, bind, collect_return_values
|
||||
from myutils.observable import make_observable, bind, collect_return_values, unbind
|
||||
|
||||
from myfasthtml.core.constants import Routes, ROUTE_ROOT
|
||||
from myfasthtml.core.utils import get_default_attr
|
||||
@@ -105,44 +105,34 @@ class BooleanConverter(DataConverter):
|
||||
|
||||
|
||||
class Binding:
|
||||
def __init__(self, data,
|
||||
attr=None,
|
||||
data_converter: DataConverter = None,
|
||||
ft=None,
|
||||
ft_name=None,
|
||||
ft_attr=None,
|
||||
detection_mode: DetectionMode = DetectionMode.ValueChange,
|
||||
update_mode: UpdateMode = UpdateMode.ValueChange):
|
||||
def __init__(self, data: Any, attr: str = None):
|
||||
"""
|
||||
Creates a new binding object between a data object used as a pivot and an HTML element.
|
||||
The same pivot object must be used for different bindings.
|
||||
This will allow the binding between the HTML elements
|
||||
|
||||
:param data: object used as a pivot
|
||||
:param attr: attribute of the data object
|
||||
:param ft: HTML element to bind to
|
||||
:param ft_name: name of the HTML element to bind to (send by the form)
|
||||
:param ft_attr: value of the attribute to bind to (send by the form)
|
||||
Creates a new binding object between a data object and an HTML element.
|
||||
The binding is not active until bind_ft() is called.
|
||||
|
||||
Args:
|
||||
data: Object used as a pivot
|
||||
attr: Attribute of the data object to bind
|
||||
"""
|
||||
self.id = uuid.uuid4()
|
||||
self.htmx_extra = {}
|
||||
self.data = data
|
||||
self.data_attr = attr or get_default_attr(data)
|
||||
self.data_converter = data_converter
|
||||
self.ft = self._safe_ft(ft)
|
||||
self.ft_name = ft_name
|
||||
self.ft_attr = ft_attr
|
||||
self.detection_mode = detection_mode
|
||||
self.update_mode = update_mode
|
||||
|
||||
self._detection = self._factory(detection_mode)
|
||||
self._update = self._factory(update_mode)
|
||||
# UI-related attributes (configured later via bind_ft)
|
||||
self.ft = None
|
||||
self.ft_name = None
|
||||
self.ft_attr = None
|
||||
self.data_converter = None
|
||||
self.detection_mode = DetectionMode.ValueChange
|
||||
self.update_mode = UpdateMode.ValueChange
|
||||
|
||||
make_observable(self.data)
|
||||
bind(self.data, self.data_attr, self.notify)
|
||||
# Strategy objects (configured later)
|
||||
self._detection = None
|
||||
self._update = None
|
||||
|
||||
# register the command
|
||||
BindingsManager.register(self)
|
||||
# Activation state
|
||||
self._is_active = False
|
||||
|
||||
def bind_ft(self,
|
||||
ft,
|
||||
@@ -152,25 +142,43 @@ class Binding:
|
||||
detection_mode: DetectionMode = None,
|
||||
update_mode: UpdateMode = None):
|
||||
"""
|
||||
Update the elements to bind to
|
||||
:param ft:
|
||||
:param name:
|
||||
:param attr:
|
||||
:param data_converter:
|
||||
:param detection_mode:
|
||||
:param update_mode:
|
||||
:return:
|
||||
Configure the UI element and activate the binding.
|
||||
|
||||
Args:
|
||||
ft: HTML element to bind to
|
||||
name: Name of the HTML element (sent by the form)
|
||||
attr: Attribute of the HTML element to bind to
|
||||
data_converter: Optional converter for data transformation
|
||||
detection_mode: How to detect changes from UI
|
||||
update_mode: How to update the UI element
|
||||
|
||||
Returns:
|
||||
self for method chaining
|
||||
"""
|
||||
# Deactivate if already active
|
||||
if self._is_active:
|
||||
self.deactivate()
|
||||
|
||||
# Configure UI elements
|
||||
self.ft = self._safe_ft(ft)
|
||||
self.ft_name = name
|
||||
self.ft_attr = attr or self.ft_attr
|
||||
self.data_converter = data_converter or self.data_converter
|
||||
self.detection_mode = detection_mode or self.detection_mode
|
||||
self.update_mode = update_mode or self.update_mode
|
||||
self.ft_attr = attr
|
||||
|
||||
# Update optional parameters if provided
|
||||
if data_converter is not None:
|
||||
self.data_converter = data_converter
|
||||
if detection_mode is not None:
|
||||
self.detection_mode = detection_mode
|
||||
if update_mode is not None:
|
||||
self.update_mode = update_mode
|
||||
|
||||
# Create strategy objects
|
||||
self._detection = self._factory(self.detection_mode)
|
||||
self._update = self._factory(self.update_mode)
|
||||
|
||||
# Activate the binding
|
||||
self.activate()
|
||||
|
||||
return self
|
||||
|
||||
def get_htmx_params(self):
|
||||
@@ -180,6 +188,21 @@ class Binding:
|
||||
}
|
||||
|
||||
def notify(self, old, new):
|
||||
"""
|
||||
Callback when the data attribute changes.
|
||||
Updates the UI element accordingly.
|
||||
|
||||
Args:
|
||||
old: Previous value
|
||||
new: New value
|
||||
|
||||
Returns:
|
||||
Updated ft element
|
||||
"""
|
||||
if not self._is_active:
|
||||
logger.warning(f"Binding '{self.id}' received notification but is not active")
|
||||
return None
|
||||
|
||||
logger.debug(f"Binding '{self.id}': Changing from '{old}' to '{new}'")
|
||||
self.ft = self._update.update(self.ft, self.ft_name, self.ft_attr, old, new)
|
||||
|
||||
@@ -198,6 +221,53 @@ class Binding:
|
||||
logger.debug(f"Nothing to trigger in {values}.")
|
||||
return None
|
||||
|
||||
def activate(self):
|
||||
"""
|
||||
Activate the binding by setting up observers and registering it.
|
||||
Should only be called after the binding is fully configured.
|
||||
|
||||
Raises:
|
||||
ValueError: If the binding is not fully configured
|
||||
"""
|
||||
if self._is_active:
|
||||
logger.warning(f"Binding '{self.id}' is already active")
|
||||
return
|
||||
|
||||
# Validate configuration
|
||||
self._validate_configuration()
|
||||
|
||||
# Setup observable
|
||||
make_observable(self.data)
|
||||
bind(self.data, self.data_attr, self.notify)
|
||||
|
||||
# Register in manager
|
||||
BindingsManager.register(self)
|
||||
|
||||
# Mark as active
|
||||
self._is_active = True
|
||||
|
||||
logger.debug(f"Binding '{self.id}' activated for {self.data_attr}")
|
||||
|
||||
def deactivate(self):
|
||||
"""
|
||||
Deactivate the binding by removing observers and unregistering it.
|
||||
Can be called multiple times safely.
|
||||
"""
|
||||
if not self._is_active:
|
||||
logger.debug(f"Binding '{self.id}' is not active, nothing to deactivate")
|
||||
return
|
||||
|
||||
# Remove observer
|
||||
unbind(self.data, self.data_attr, self.notify)
|
||||
|
||||
# Unregister from manager
|
||||
BindingsManager.unregister(self.id)
|
||||
|
||||
# Mark as inactive
|
||||
self._is_active = False
|
||||
|
||||
logger.debug(f"Binding '{self.id}' deactivated")
|
||||
|
||||
@staticmethod
|
||||
def _safe_ft(ft):
|
||||
"""
|
||||
@@ -228,6 +298,25 @@ class Binding:
|
||||
else:
|
||||
raise ValueError(f"Invalid detection mode: {mode}")
|
||||
|
||||
def _validate_configuration(self):
|
||||
"""
|
||||
Validate that the binding is fully configured before activation.
|
||||
|
||||
Raises:
|
||||
ValueError: If required configuration is missing
|
||||
"""
|
||||
if self.ft is None:
|
||||
raise ValueError(f"Binding '{self.id}': ft element is required")
|
||||
|
||||
# if self.ft_name is None:
|
||||
# raise ValueError(f"Binding '{self.id}': ft_name is required")
|
||||
|
||||
if self._detection is None:
|
||||
raise ValueError(f"Binding '{self.id}': detection strategy not initialized")
|
||||
|
||||
if self._update is None:
|
||||
raise ValueError(f"Binding '{self.id}': update strategy not initialized")
|
||||
|
||||
def htmx(self, trigger=None):
|
||||
if trigger:
|
||||
self.htmx_extra["hx-trigger"] = trigger
|
||||
@@ -241,6 +330,17 @@ class BindingsManager:
|
||||
def register(binding: Binding):
|
||||
BindingsManager.bindings[str(binding.id)] = binding
|
||||
|
||||
@staticmethod
|
||||
def unregister(binding_id: str):
|
||||
"""
|
||||
Unregister a binding from the manager.
|
||||
|
||||
Args:
|
||||
binding_id: ID of the binding to unregister
|
||||
"""
|
||||
if str(binding_id) in BindingsManager.bindings:
|
||||
del BindingsManager.bindings[str(binding_id)]
|
||||
|
||||
@staticmethod
|
||||
def get_binding(binding_id: str) -> Optional[Binding]:
|
||||
return BindingsManager.bindings.get(str(binding_id))
|
||||
|
||||
Reference in New Issue
Block a user