duck.html.components.extensions

Extensions module for components.

Usage example:

from duck.html.components.button import Button
from duck.html.components.extensions import Extension

class MyExtension(Extension):
    def my_new_method(self):
        # This method will now be available on component `MyButton`
        # Do something
        pass

    def existing_method(self):
        super().existing_method()
        # When overriding an existing method, don't forget to call `super()`
        # Do something, e.g. access component keyword arguments through `self.kwargs`

    def apply_extension(self):
        super().apply_extension()
        # Modify something or do something
        self.style.update({"background-color", "red"})

class MyButton(MyExtension, Button):
    pass

btn = MyButton()
btn.style["background-color"] == "red"  # Outputs: True

Subpackages

Submodules

Package Contents

Classes

BasicExtension

Basic extension for HTML components, providing common properties like text, id, bg_color, and color.

Extension

Base class for all component extensions.

StyleCompatibilityExtension

Extension for improving CSS style compatibility between browsers. Automatically adds and (optionally) deletes vendor-prefixed versions of certain CSS properties when setting or deleting styles.

Functions

register_default_extension

Attach an extension to every instance of a component class and its subclasses.

resolve_component_class

Resolve a component class with its applicable default extensions mixed in.

unregister_default_extension

Remove a previously registered default extension rule.

Data

DEFAULT_EXTENSIONS

RESOLVED_CLASSES

API

class duck.html.components.extensions.BasicExtension[source]

Bases: duck.html.components.extensions.Extension

Basic extension for HTML components, providing common properties like text, id, bg_color, and color.

apply_extension()[source]

Apply the extension. Applies initial values from kwargs for basic properties such as id, klass, text, bg_color, and color.

property bg_color: Optional[str]

Returns the background color of the component.

Returns:

The background color if set, otherwise None.

Return type:

Optional[str]

property color: Optional[str]

Returns the foreground (text) color of the component.

Returns:

The text color if set, otherwise None.

Return type:

Optional[str]

get_kwarg_or_raise(kwarg: str) → Any[source]

Retrieves an argument from component kwargs or raise an exception.

Raises:

KwargError – If a keyword argument is not provided to the component.

get_request_or_raise() → duck.http.request.HttpRequest[source]

Retrieves a request object from component kwargs or raise an exception.

Raises:

RequestNotFoundError – If the request is not in kwargs or kwargs[‘context’] (if used in templates).

property id: Optional[str]

Returns the ID of the component.

Returns:

The ID if set, otherwise None.

Return type:

Optional[str]

property klass: Optional[str]

Returns the class of the component.

Returns:

The class’ if set, otherwise None.

Return type:

Optional[str]

property text: str

Returns the inner html of the component.

… admonition:: Notes

This escapes HTML if found in text. You can disable this by setting escape_on_text=False on component.

Returns:

The inner content of the component.

Return type:

str

Raises:

ExtensionError – If the component does not support inner_html.

duck.html.components.extensions.DEFAULT_EXTENSIONS: Dict[Tuple[Type, Type], Tuple[Type, ...]]

None

class duck.html.components.extensions.Extension[source]

Base class for all component extensions.

Extensions allow reusable behaviors to be added to components via mixins. Override methods like apply_extension or define new ones for extended logic.

apply_extension()[source]

Overrride this method to apply the desired extensions.

Notes:

  • Don’t forget to call super().apply_extensions() inside the method.

  • Methods or property definations are applied to the component automatically.

load()[source]
exception duck.html.components.extensions.ExtensionError[source]

Bases: Exception

Raised when there is an error related to a component extension.

Initialization

Initialize self. See help(type(self)) for accurate signature.

exception duck.html.components.extensions.KwargError[source]

Bases: duck.html.components.extensions.ExtensionError

Raised when there is no required keyword argument in component kwargs.

Initialization

Initialize self. See help(type(self)) for accurate signature.

duck.html.components.extensions.RESOLVED_CLASSES: Dict[Tuple[Type, FrozenSet[Type]], Type]

None

exception duck.html.components.extensions.RequestNotFoundError[source]

Bases: duck.html.components.extensions.ExtensionError

Raised when there is no required ‘request’ in component kwargs or kwargs['context'] (if component used in a template).

Initialization

Initialize self. See help(type(self)) for accurate signature.

class duck.html.components.extensions.StyleCompatibilityExtension(*args, **kw)[source]

Bases: duck.html.components.extensions.Extension

Extension for improving CSS style compatibility between browsers. Automatically adds and (optionally) deletes vendor-prefixed versions of certain CSS properties when setting or deleting styles.

Initialization

apply_extension()[source]
duck.html.components.extensions.register_default_extension(component_class: type, extension: type[Extension], reject: Iterable[Type] = ()) → None[source]

Attach an extension to every instance of a component class and its subclasses.

Registering the same component class and extension again replaces the previous reject classes, so calling this more than once is safe.

Parameters:
  • component_class – Component class whose instances get the extension.

  • extension – Extension mixed in ahead of the component.

  • reject – Component classes that must not get the extension. Subclasses of these classes are rejected as well.

Raises:

ExtensionError – If reject contains anything other than classes.

… admonition:: Notes

You can only reject other extensions apart from BasicExtension and StyleCompatibiliyExtension because they provide base component operations.

duck.html.components.extensions.resolve_component_class(cls: type, exclude_extensions: Iterable[type[Extension]] = ()) → type[source]

Resolve a component class with its applicable default extensions mixed in.

The derived class is built once per (component class, excluded extensions) pair and cached, so repeated instantiations only cost a dictionary lookup.

Parameters:
  • cls – Component class being instantiated.

  • exclude_extensions – Default extensions to skip for this instance only, even if otherwise applicable.

Returns:

cls itself when no extension applies, otherwise a generated subclass with the extensions ahead of cls in the MRO.

Return type:

Type

… admonition:: Notes

Only other extensions apart from BasicExtension and StyleCompatibiliyExtension can be excluded because these provide base component operations.

duck.html.components.extensions.unregister_default_extension(component_class: type, extension: type[Extension], failsafe: bool = False) → None[source]

Remove a previously registered default extension rule.

Parameters:
  • component_class – Component class the rule was registered under.

  • extension – Extension to stop attaching by default.

  • failsafe – If True, do nothing when the rule was never registered, instead of raising.

Raises:

ExtensionError – If the rule was never registered and failsafe is False.

… admonition:: Notes

You can only unregister other extensions apart from BasicExtension and StyleCompatibiliyExtension because they provide base component operations.