Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions docs/primitives.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,47 @@ is built.
| `type` | `"button"` | `button` `submit` `reset`. Only applies to the `<button>` form |
| `full_width` | `false` | |
| `extra_class` / `class` | `""` | `extra_class` in JinjaX, `class` in cotton — `class` is a Python reserved word |
| `attrs` | `{}` | Arbitrary extra HTML attributes — `data-*`, `hx-*`, Alpine bindings. See below |
| slot | — | The label |

### Attribute passthrough

`attrs` is a `dict[str, str]` of extra attributes rendered as literal
`key="value"` pairs on the root element, for attributes no named prop covers
— `data-event`, `hx-get`, `x-on:click`, `aria-controls`:

=== "JinjaX"

```jinja
<Cf:Button :attrs="{'data-event': 'submit', 'hx-post': '/orders'}">
Save
</Cf:Button>
```

=== "django-cotton"

```html
<c-cf.button :attrs="{'data-event': 'submit', 'hx-post': '/orders'}">
Save
</c-cf.button>
```

Rendered by a single implementation, `cf_ui.primitives.render_attrs` — bound
as the Jinja global `cf_ui_render_attrs` and the Django `{% cf_ui_render_attrs %}`
tag — rather than inline per template, the way `cf_ui_validate` already
centralizes the axis vocabulary. It escapes every key and value itself
(`html.escape`), so it does not depend on the surrounding template's
autoescape state, and it validates the **key**, not just the value: an
attribute name may contain only letters, digits, `_`, `.`, `:` and `-`.
That closes a hole plain HTML-entity escaping cannot — a key containing a
space or `=` forges a brand-new attribute even when its value is fully
escaped, because entity escaping never touches either character. A key that
collides with a prop the component already renders (`type`, `class`,
`href`, …) is rejected outright rather than silently losing to HTML's
keep-the-first-duplicate rule. See [Escaping](escaping.md). Currently
`Button`-only; the same shape is expected to roll out to the rest of Tier 1
as separate follow-up work (#71, #72).

### Disabled links

`state="disabled"` with an `href` renders an `<a>` **without an `href`
Expand Down
98 changes: 97 additions & 1 deletion src/cf_ui/primitives.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@
from __future__ import annotations

import json
import re
from copy import deepcopy
from html import escape as _html_escape
from pathlib import Path
from typing import Any

Expand All @@ -57,6 +59,7 @@
"LEVELS",
"PRIMITIVES",
"PRIMITIVE_DEFINITION_PATH",
"RESERVED_ATTRS",
"SIZES",
"STATES",
"TYPES",
Expand All @@ -65,6 +68,7 @@
"PrimitiveConfigError",
"classes_for",
"primitive_definition",
"render_attrs",
"validate",
]

Expand Down Expand Up @@ -776,6 +780,98 @@ def validate(component: str, **axes: Any) -> str:
return ""


#: Attribute names ``attrs`` may carry. HTML5 permits nearly any character in
#: an attribute name, but no legitimate ``data-*``/``hx-*``/``x-*``/``aria-*``
#: identifier needs that latitude, and the latitude itself is the hole: a
#: space or ``=`` inside a key still forges a brand-new attribute even when
#: the value is escaped, because HTML-entity escaping never touches either
#: character. Restricting the character set closes that off structurally
#: rather than trying to escape it.
_ATTR_NAME_RE = re.compile(r"^[A-Za-z_:][A-Za-z0-9_.:-]*$")

#: Attributes each primitive already renders itself, keyed like
#: :data:`PRIMITIVES`. ``attrs`` cannot be used to set one of these: HTML
#: keeps the *first* occurrence of a duplicate attribute, so a caller
#: attempting to override ``type`` or ``class`` through ``attrs`` would not
#: get an error and would not get the override either — the component's own
#: value would silently win. Raising is what makes that attempt visible.
#:
#: A primitive not listed here has not adopted ``attrs`` yet.
RESERVED_ATTRS: dict[str, frozenset[str]] = {
"button": frozenset({"class", "type", "href", "role", "aria-disabled", "disabled"}),
}


class _SafeAttrs(str):
"""A pre-escaped string, safe under both template engines without either
engine's escaping library installed.

``__html__`` is the protocol Jinja's escaping (via markupsafe) and
Django's ``conditional_escape`` both already check for — an object
carrying it is treated as already-safe HTML and is not re-escaped.
Implementing it directly, rather than returning a
:class:`markupsafe.Markup`, means this module — imported by the
Django-only templatetag path — never has to import Jinja2's escaping
library, which the ``django`` extra does not install.
"""

def __html__(self) -> str:
return str(self)


def render_attrs(component: str, attrs: dict[str, str] | None) -> _SafeAttrs:
"""Render an ``attrs`` passthrough dict as literal ``key="value"`` pairs.

The one implementation every primitive's ``attrs`` prop calls through —
bound as the Jinja global ``cf_ui_render_attrs`` and as the Django
``{% cf_ui_render_attrs %}`` tag — so the validation and escaping rules
live once, the way :func:`validate` already holds the axis vocabulary
once rather than per template.

Every key and value is escaped with :func:`html.escape` directly, rather
than relying on the surrounding template's autoescape state: the two
engines do not share one, and an already-safe result is correct whether
the caller's environment autoescapes or not — see ``docs/escaping.md``.

Args:
component: A key of :data:`RESERVED_ATTRS` — which attribute names
are off-limits because the primitive renders them itself.
Components with no entry accept every syntactically valid name.
attrs: The passthrough dict, or ``None``/empty for no extra
attributes.

Returns:
A leading-space-separated, HTML-safe string — empty when ``attrs``
is empty or ``None`` — ready to interpolate directly before the
element's closing ``>``.

Raises:
PrimitiveConfigError: On an attribute name outside the permitted
character set, or one that collides with a name the component
already renders.
"""
if not attrs:
return _SafeAttrs("")

reserved = RESERVED_ATTRS.get(component, frozenset())
parts: list[str] = []
for name, value in attrs.items():
if not _ATTR_NAME_RE.match(name):
raise PrimitiveConfigError(
f"invalid attrs key {name!r} for {component} — attribute names "
"may contain only letters, digits, '_', '.', ':' and '-', and "
"must not start with a digit or '-'"
)
if name in reserved:
raise PrimitiveConfigError(
f"{component} takes no {name!r} in attrs — it collides with a "
f"prop {component} already renders as an attribute; pass it as "
"that prop instead"
)
parts.append(f' {_html_escape(name, quote=True)}="{_html_escape(str(value), quote=True)}"')
return _SafeAttrs("".join(parts))


def build_primitive_globals() -> dict[str, Any]:
"""Jinja globals the primitive templates call.

Expand All @@ -784,7 +880,7 @@ def build_primitive_globals() -> dict[str, Any]:
the missing piece, which is the same trade ``cf_ui_root_attrs()`` already
makes.
"""
return {"cf_ui_validate": validate}
return {"cf_ui_validate": validate, "cf_ui_render_attrs": render_attrs}


def classes_for(theme: str, component: str, **axes: Any) -> str:
Expand Down
2 changes: 1 addition & 1 deletion src/cf_ui/templates/cotton/_themes/bootstrap/button.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,4 @@
{{ class }}
{% endif %}
{% endcf_ui_class %}
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="{{ cf_class }}"{% if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}{% else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}>{% if state == 'loading' %}<span class="spinner-border spinner-border-sm" aria-hidden="true"></span> {% endif %}{{ slot }}</{{ cf_tag }}>{% endwith %}
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="{{ cf_class }}"{% if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}{% else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}{% cf_ui_render_attrs "button" attrs %}>{% if state == 'loading' %}<span class="spinner-border spinner-border-sm" aria-hidden="true"></span> {% endif %}{{ slot }}</{{ cf_tag }}>{% endwith %}
2 changes: 1 addition & 1 deletion src/cf_ui/templates/cotton/_themes/bulma/button.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@
{{ class }}
{% endif %}
{% endcf_ui_class %}
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="{{ cf_class }}"{% if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}{% else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}>{{ slot }}</{{ cf_tag }}>{% endwith %}
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="{{ cf_class }}"{% if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}{% else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}{% cf_ui_render_attrs "button" attrs %}>{{ slot }}</{{ cf_tag }}>{% endwith %}
2 changes: 1 addition & 1 deletion src/cf_ui/templates/cotton/_themes/daisy/button.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,4 @@
{{ class }}
{% endif %}
{% endcf_ui_class %}
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="{{ cf_class }}"{% if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}{% else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}>{% if state == 'loading' %}<span class="loading loading-spinner"></span> {% endif %}{{ slot }}</{{ cf_tag }}>{% endwith %}
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="{{ cf_class }}"{% if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}{% else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}{% cf_ui_render_attrs "button" attrs %}>{% if state == 'loading' %}<span class="loading loading-spinner"></span> {% endif %}{{ slot }}</{{ cf_tag }}>{% endwith %}
2 changes: 1 addition & 1 deletion src/cf_ui/templates/cotton/_themes/fomantic/button.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,4 @@
{{ class }}
{% endif %}
{% endcf_ui_class %}
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="{{ cf_class }}"{% if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}{% else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}>{{ slot }}</{{ cf_tag }}>{% endwith %}
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="{{ cf_class }}"{% if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}{% else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}{% cf_ui_render_attrs "button" attrs %}>{{ slot }}</{{ cf_tag }}>{% endwith %}
2 changes: 1 addition & 1 deletion src/cf_ui/templates/cotton/_themes/foundation/button.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@
{{ class }}
{% endif %}
{% endcf_ui_class %}
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="{{ cf_class }}"{% if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}{% else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}>{{ slot }}</{{ cf_tag }}>{% endwith %}
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="{{ cf_class }}"{% if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}{% else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}{% cf_ui_render_attrs "button" attrs %}>{{ slot }}</{{ cf_tag }}>{% endwith %}
1 change: 1 addition & 0 deletions src/cf_ui/templates/cotton/cf/button.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
type="button"
full_width=""
class=""
attrs="{}"
/>
{% load cf_ui %}
{% cf_ui_validate "button" variant=variant size=size state=state type=type %}{% cf_ui_theme_path "button" as cf_ui_partial %}
Expand Down
5 changes: 3 additions & 2 deletions src/cf_ui/templates/jinja/bootstrap/Button.jinja
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{#def content="", variant="neutral", size="normal", state="normal", href="", type="button", full_width=false, extra_class="" #}
{#def content="", variant="neutral", size="normal", state="normal", href="", type="button", full_width=false, extra_class="", attrs={} #}
{% autoescape true %}
{% set content = content if content is defined else "" %}
{% set variant = variant if variant is defined else "neutral" %}
Expand All @@ -8,9 +8,10 @@
{% set type = type if type is defined else "button" %}
{% set full_width = full_width if full_width is defined else false %}
{% set extra_class = extra_class if extra_class is defined else "" %}
{% set attrs = attrs if attrs is defined else {} %}
{{ cf_ui_validate("button", variant=variant, size=size, state=state, type=type) }}
{%- set cf_tag = "a" if href else "button" -%}
<{{ cf_tag }} class="btn{% if variant == 'primary' %} btn-primary{% elif variant == 'secondary' %} btn-secondary{% elif variant == 'success' %} btn-success{% elif variant == 'warning' %} btn-warning{% elif variant == 'danger' %} btn-danger{% elif variant == 'info' %} btn-info{% elif variant == 'neutral' %} btn-light{% endif %}{% if size == 'small' %} btn-sm{% elif size == 'large' %} btn-lg{% endif %}{% if state == 'disabled' %} disabled{% endif %}{% if full_width %} w-100{% endif %}{% if extra_class %} {{ extra_class }}{% endif %}"
{%- if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}
{%- else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}>{% if state == 'loading' %}<span class="spinner-border spinner-border-sm" aria-hidden="true"></span> {% endif %}{{ content }}</{{ cf_tag }}>
{%- else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}{{ cf_ui_render_attrs("button", attrs) }}>{% if state == 'loading' %}<span class="spinner-border spinner-border-sm" aria-hidden="true"></span> {% endif %}{{ content }}</{{ cf_tag }}>
{% endautoescape %}
5 changes: 3 additions & 2 deletions src/cf_ui/templates/jinja/bulma/Button.jinja
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{#def content="", variant="neutral", size="normal", state="normal", href="", type="button", full_width=false, extra_class="" #}
{#def content="", variant="neutral", size="normal", state="normal", href="", type="button", full_width=false, extra_class="", attrs={} #}
{% autoescape true %}
{% set content = content if content is defined else "" %}
{% set variant = variant if variant is defined else "neutral" %}
Expand All @@ -8,9 +8,10 @@
{% set type = type if type is defined else "button" %}
{% set full_width = full_width if full_width is defined else false %}
{% set extra_class = extra_class if extra_class is defined else "" %}
{% set attrs = attrs if attrs is defined else {} %}
{{ cf_ui_validate("button", variant=variant, size=size, state=state, type=type) }}
{%- set cf_tag = "a" if href else "button" -%}
<{{ cf_tag }} class="button{% if variant == 'primary' %} is-primary{% elif variant == 'secondary' %} is-link{% elif variant == 'success' %} is-success{% elif variant == 'warning' %} is-warning{% elif variant == 'danger' %} is-danger{% elif variant == 'info' %} is-info{% endif %}{% if size == 'small' %} is-small{% elif size == 'large' %} is-large{% endif %}{% if state == 'loading' %} is-loading{% endif %}{% if full_width %} is-fullwidth{% endif %}{% if extra_class %} {{ extra_class }}{% endif %}"
{%- if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}
{%- else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}>{{ content }}</{{ cf_tag }}>
{%- else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}{{ cf_ui_render_attrs("button", attrs) }}>{{ content }}</{{ cf_tag }}>
{% endautoescape %}
5 changes: 3 additions & 2 deletions src/cf_ui/templates/jinja/daisy/Button.jinja
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{#def content="", variant="neutral", size="normal", state="normal", href="", type="button", full_width=false, extra_class="" #}
{#def content="", variant="neutral", size="normal", state="normal", href="", type="button", full_width=false, extra_class="", attrs={} #}
{% autoescape true %}
{% set content = content if content is defined else "" %}
{% set variant = variant if variant is defined else "neutral" %}
Expand All @@ -8,9 +8,10 @@
{% set type = type if type is defined else "button" %}
{% set full_width = full_width if full_width is defined else false %}
{% set extra_class = extra_class if extra_class is defined else "" %}
{% set attrs = attrs if attrs is defined else {} %}
{{ cf_ui_validate("button", variant=variant, size=size, state=state, type=type) }}
{%- set cf_tag = "a" if href else "button" -%}
<{{ cf_tag }} class="btn{% if variant == 'primary' %} btn-primary{% elif variant == 'secondary' %} btn-secondary{% elif variant == 'success' %} btn-success{% elif variant == 'warning' %} btn-warning{% elif variant == 'danger' %} btn-error{% elif variant == 'info' %} btn-info{% elif variant == 'neutral' %} btn-neutral{% endif %}{% if size == 'small' %} btn-sm{% elif size == 'large' %} btn-lg{% endif %}{% if state == 'disabled' %} btn-disabled{% endif %}{% if full_width %} btn-block{% endif %}{% if extra_class %} {{ extra_class }}{% endif %}"
{%- if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}
{%- else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}>{% if state == 'loading' %}<span class="loading loading-spinner"></span> {% endif %}{{ content }}</{{ cf_tag }}>
{%- else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}{{ cf_ui_render_attrs("button", attrs) }}>{% if state == 'loading' %}<span class="loading loading-spinner"></span> {% endif %}{{ content }}</{{ cf_tag }}>
{% endautoescape %}
5 changes: 3 additions & 2 deletions src/cf_ui/templates/jinja/fomantic/Button.jinja
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{#def content="", variant="neutral", size="normal", state="normal", href="", type="button", full_width=false, extra_class="" #}
{#def content="", variant="neutral", size="normal", state="normal", href="", type="button", full_width=false, extra_class="", attrs={} #}
{% autoescape true %}
{% set content = content if content is defined else "" %}
{% set variant = variant if variant is defined else "neutral" %}
Expand All @@ -8,9 +8,10 @@
{% set type = type if type is defined else "button" %}
{% set full_width = full_width if full_width is defined else false %}
{% set extra_class = extra_class if extra_class is defined else "" %}
{% set attrs = attrs if attrs is defined else {} %}
{{ cf_ui_validate("button", variant=variant, size=size, state=state, type=type) }}
{%- set cf_tag = "a" if href else "button" -%}
<{{ cf_tag }} class="ui button{% if variant == 'primary' %} primary{% elif variant == 'secondary' %} secondary{% elif variant == 'success' %} positive{% elif variant == 'warning' %} yellow{% elif variant == 'danger' %} negative{% elif variant == 'info' %} teal{% endif %}{% if size == 'small' %} small{% elif size == 'large' %} large{% endif %}{% if state == 'loading' %} loading{% elif state == 'disabled' %} disabled{% endif %}{% if full_width %} fluid{% endif %}{% if extra_class %} {{ extra_class }}{% endif %}"
{%- if href %}{% if state == 'disabled' %} role="link" aria-disabled="true"{% else %} href="{{ href }}"{% endif %}
{%- else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}>{{ content }}</{{ cf_tag }}>
{%- else %} type="{{ type }}"{% if state == 'disabled' %} disabled{% endif %}{% endif %}{{ cf_ui_render_attrs("button", attrs) }}>{{ content }}</{{ cf_tag }}>
{% endautoescape %}
Loading
Loading