html_compose.resource.css_import

  1from typing import Literal
  2
  3from .. import elements as el
  4from .util_funcs import _cachebust_resource_uri
  5
  6
  7class css_import:
  8    """
  9    A css import helper class which employs:
 10    - `link(rel="stylesheet")` to define the import
 11    - `link(rel="preload")` to preload the import
 12    - `hash` and `crossorigin` for SRI
 13    - Local resource cache busting
 14
 15    An production usage might look like:
 16    ```python
 17    [
 18    css_import('./static/admin.css',
 19                cache_bust=True),
 20
 21    css_import(
 22        "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css",
 23        hash=(
 24            "sha384-9ndCyUaIbzAi2FUVXJi0CjmCapS"
 25            "mO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
 26            ),
 27        crossorigin="anonymous",
 28        preload=True
 29    )
 30
 31    ]
 32    ```
 33
 34    ## Generated "HTML":
 35
 36    ```python
 37    import json
 38    from html_compose import el
 39
 40    [
 41        link(rel='preload',
 42            href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
 43            as_='style',
 44            integrity='sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7'
 45            'SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM',
 46            crossorigin='anonymous'),
 47
 48        link(rel='stylesheet', href='./static/admin.css?ts=1760153426'),
 49
 50        link(rel='stylesheet',
 51            href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
 52            integrity='sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7'
 53            'SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM',
 54            crossorigin='anonymous')
 55    ]
 56    ```
 57
 58    See:
 59        https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/preload
 60        https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
 61        https://www.srihash.org/
 62
 63    """
 64
 65    def __init__(
 66        self,
 67        href: str,
 68        preload: bool = False,
 69        hash: str | None = None,
 70        crossorigin: Literal["", "anonymous", "user-credentials"]
 71        | str
 72        | None = None,
 73        cache_bust: bool = False,
 74    ):
 75        """
 76        A css import wrapper to wrap some of the complexity of optimal
 77        resource loading.
 78
 79
 80        Parameters
 81        ----------
 82        `href`:
 83            The literal href passed to the link tag
 84
 85        `preload`:
 86            If true, adds a preload link for this resource
 87
 88        `hash`:
 89            An optional SRI integrity hash for the import
 90
 91        `crossorigin`:
 92            Optionally sets the crossorigin attribute on the link tag.
 93            Valid values are "", "anonymous", "use-credentials"
 94
 95        `cache_bust`:
 96            If true, appends a timestamp to the URL to prevent browser
 97            caching. Webservers configured for static resources manage this
 98            feature automatically, but for development this can be useful.
 99
100            This feature only works for local resources, i.e. those that
101            exist in `resource.settings.base_dir`
102
103        """
104        self.href = href
105        self.preload = preload
106        self.hash = hash
107        self.crossorigin = crossorigin
108        self.cache_bust = cache_bust
109        self.has_link = preload
110        self._href = self.uri()
111
112        if hash and self.crossorigin is None:
113            raise ValueError(
114                "If hash is set, crossorigin must be set to ''/'anonymous'"
115            )
116
117    def uri(self):
118        """
119        Returns the source URI - with cache busting if enabled
120        which is implemented by getting the mtime of the local file
121
122        This operation performs up to two fs stats per call
123
124        1. The base static directory is checked once and cached per interpreter
125        2. The specific resource is checked if it is time to poll again
126           based on settings.stat_poll_interval
127        """
128        if not self.cache_bust:
129            return self.href
130
131        return _cachebust_resource_uri(self.href)
132
133    def preloads(self) -> list[el.link]:
134        """
135        Returns a link element for preloading this import if preload is set
136        """
137        attrs = {"href": self._href}
138        if self.hash:
139            attrs["integrity"] = self.hash
140        if self.crossorigin:
141            attrs["crossorigin"] = self.crossorigin
142        if self.preload:
143            return [el.link(attrs=attrs, rel="preload", as_="style")]
144
145        return []
146
147    def links(self):
148        """
149        Returns one or more link element for this import
150        """
151        links = []
152        attrs = {"href": self._href}
153        if self.hash:
154            attrs["integrity"] = self.hash
155        if self.crossorigin:
156            attrs["crossorigin"] = self.crossorigin
157
158        links.append(el.link(attrs=attrs, rel="stylesheet"))
159
160        return links
class css_import:
  8class css_import:
  9    """
 10    A css import helper class which employs:
 11    - `link(rel="stylesheet")` to define the import
 12    - `link(rel="preload")` to preload the import
 13    - `hash` and `crossorigin` for SRI
 14    - Local resource cache busting
 15
 16    An production usage might look like:
 17    ```python
 18    [
 19    css_import('./static/admin.css',
 20                cache_bust=True),
 21
 22    css_import(
 23        "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css",
 24        hash=(
 25            "sha384-9ndCyUaIbzAi2FUVXJi0CjmCapS"
 26            "mO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
 27            ),
 28        crossorigin="anonymous",
 29        preload=True
 30    )
 31
 32    ]
 33    ```
 34
 35    ## Generated "HTML":
 36
 37    ```python
 38    import json
 39    from html_compose import el
 40
 41    [
 42        link(rel='preload',
 43            href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
 44            as_='style',
 45            integrity='sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7'
 46            'SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM',
 47            crossorigin='anonymous'),
 48
 49        link(rel='stylesheet', href='./static/admin.css?ts=1760153426'),
 50
 51        link(rel='stylesheet',
 52            href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
 53            integrity='sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7'
 54            'SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM',
 55            crossorigin='anonymous')
 56    ]
 57    ```
 58
 59    See:
 60        https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/preload
 61        https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
 62        https://www.srihash.org/
 63
 64    """
 65
 66    def __init__(
 67        self,
 68        href: str,
 69        preload: bool = False,
 70        hash: str | None = None,
 71        crossorigin: Literal["", "anonymous", "user-credentials"]
 72        | str
 73        | None = None,
 74        cache_bust: bool = False,
 75    ):
 76        """
 77        A css import wrapper to wrap some of the complexity of optimal
 78        resource loading.
 79
 80
 81        Parameters
 82        ----------
 83        `href`:
 84            The literal href passed to the link tag
 85
 86        `preload`:
 87            If true, adds a preload link for this resource
 88
 89        `hash`:
 90            An optional SRI integrity hash for the import
 91
 92        `crossorigin`:
 93            Optionally sets the crossorigin attribute on the link tag.
 94            Valid values are "", "anonymous", "use-credentials"
 95
 96        `cache_bust`:
 97            If true, appends a timestamp to the URL to prevent browser
 98            caching. Webservers configured for static resources manage this
 99            feature automatically, but for development this can be useful.
100
101            This feature only works for local resources, i.e. those that
102            exist in `resource.settings.base_dir`
103
104        """
105        self.href = href
106        self.preload = preload
107        self.hash = hash
108        self.crossorigin = crossorigin
109        self.cache_bust = cache_bust
110        self.has_link = preload
111        self._href = self.uri()
112
113        if hash and self.crossorigin is None:
114            raise ValueError(
115                "If hash is set, crossorigin must be set to ''/'anonymous'"
116            )
117
118    def uri(self):
119        """
120        Returns the source URI - with cache busting if enabled
121        which is implemented by getting the mtime of the local file
122
123        This operation performs up to two fs stats per call
124
125        1. The base static directory is checked once and cached per interpreter
126        2. The specific resource is checked if it is time to poll again
127           based on settings.stat_poll_interval
128        """
129        if not self.cache_bust:
130            return self.href
131
132        return _cachebust_resource_uri(self.href)
133
134    def preloads(self) -> list[el.link]:
135        """
136        Returns a link element for preloading this import if preload is set
137        """
138        attrs = {"href": self._href}
139        if self.hash:
140            attrs["integrity"] = self.hash
141        if self.crossorigin:
142            attrs["crossorigin"] = self.crossorigin
143        if self.preload:
144            return [el.link(attrs=attrs, rel="preload", as_="style")]
145
146        return []
147
148    def links(self):
149        """
150        Returns one or more link element for this import
151        """
152        links = []
153        attrs = {"href": self._href}
154        if self.hash:
155            attrs["integrity"] = self.hash
156        if self.crossorigin:
157            attrs["crossorigin"] = self.crossorigin
158
159        links.append(el.link(attrs=attrs, rel="stylesheet"))
160
161        return links

A css import helper class which employs:

  • link(rel="stylesheet") to define the import
  • link(rel="preload") to preload the import
  • hash and crossorigin for SRI
  • Local resource cache busting

An production usage might look like:

[
css_import('./static/admin.css',
            cache_bust=True),

css_import(
    "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css",
    hash=(
        "sha384-9ndCyUaIbzAi2FUVXJi0CjmCapS"
        "mO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
        ),
    crossorigin="anonymous",
    preload=True
)

]

Generated "HTML":

import json
from html_compose import el

[
    link(rel='preload',
        href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
        as_='style',
        integrity='sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7'
        'SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM',
        crossorigin='anonymous'),

    link(rel='stylesheet', href='./static/admin.css?ts=1760153426'),

    link(rel='stylesheet',
        href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
        integrity='sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7'
        'SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM',
        crossorigin='anonymous')
]

See: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/preload https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity https://www.srihash.org/

css_import( href: str, preload: bool = False, hash: str | None = None, crossorigin: Union[Literal['', 'anonymous', 'user-credentials'], str, NoneType] = None, cache_bust: bool = False)
 66    def __init__(
 67        self,
 68        href: str,
 69        preload: bool = False,
 70        hash: str | None = None,
 71        crossorigin: Literal["", "anonymous", "user-credentials"]
 72        | str
 73        | None = None,
 74        cache_bust: bool = False,
 75    ):
 76        """
 77        A css import wrapper to wrap some of the complexity of optimal
 78        resource loading.
 79
 80
 81        Parameters
 82        ----------
 83        `href`:
 84            The literal href passed to the link tag
 85
 86        `preload`:
 87            If true, adds a preload link for this resource
 88
 89        `hash`:
 90            An optional SRI integrity hash for the import
 91
 92        `crossorigin`:
 93            Optionally sets the crossorigin attribute on the link tag.
 94            Valid values are "", "anonymous", "use-credentials"
 95
 96        `cache_bust`:
 97            If true, appends a timestamp to the URL to prevent browser
 98            caching. Webservers configured for static resources manage this
 99            feature automatically, but for development this can be useful.
100
101            This feature only works for local resources, i.e. those that
102            exist in `resource.settings.base_dir`
103
104        """
105        self.href = href
106        self.preload = preload
107        self.hash = hash
108        self.crossorigin = crossorigin
109        self.cache_bust = cache_bust
110        self.has_link = preload
111        self._href = self.uri()
112
113        if hash and self.crossorigin is None:
114            raise ValueError(
115                "If hash is set, crossorigin must be set to ''/'anonymous'"
116            )

A css import wrapper to wrap some of the complexity of optimal resource loading.

Parameters

href: The literal href passed to the link tag

preload: If true, adds a preload link for this resource

hash: An optional SRI integrity hash for the import

crossorigin: Optionally sets the crossorigin attribute on the link tag. Valid values are "", "anonymous", "use-credentials"

cache_bust: If true, appends a timestamp to the URL to prevent browser caching. Webservers configured for static resources manage this feature automatically, but for development this can be useful.

This feature only works for local resources, i.e. those that
exist in `resource.settings.base_dir`
href
preload
hash
crossorigin
cache_bust
def uri(self):
118    def uri(self):
119        """
120        Returns the source URI - with cache busting if enabled
121        which is implemented by getting the mtime of the local file
122
123        This operation performs up to two fs stats per call
124
125        1. The base static directory is checked once and cached per interpreter
126        2. The specific resource is checked if it is time to poll again
127           based on settings.stat_poll_interval
128        """
129        if not self.cache_bust:
130            return self.href
131
132        return _cachebust_resource_uri(self.href)

Returns the source URI - with cache busting if enabled which is implemented by getting the mtime of the local file

This operation performs up to two fs stats per call

  1. The base static directory is checked once and cached per interpreter
  2. The specific resource is checked if it is time to poll again based on settings.stat_poll_interval
def preloads(self) -> list[html_compose.elements.link_element.link]:
134    def preloads(self) -> list[el.link]:
135        """
136        Returns a link element for preloading this import if preload is set
137        """
138        attrs = {"href": self._href}
139        if self.hash:
140            attrs["integrity"] = self.hash
141        if self.crossorigin:
142            attrs["crossorigin"] = self.crossorigin
143        if self.preload:
144            return [el.link(attrs=attrs, rel="preload", as_="style")]
145
146        return []

Returns a link element for preloading this import if preload is set