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
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,11 @@ indent-style = "space"
profile = "django"
indent = 2
single_attribute_per_line = true
# {% cf_ui_class %}...{% endcf_ui_class %} is a custom block tag (cf_ui.py)
# that lets a cotton theme partial write its class="..." if/elif chain one
# branch per line — Django has no {%- -%} trim markers, so without this the
# tag looks like an unmatched end tag (T038) to djlint's own parser.
custom_blocks = "cf_ui_class"
# Both extensions are formatted. The Jinja tree is passed `--profile=jinja`
# on its own hook invocation; this file-level setting cannot vary per path.
extension = "html"
Expand Down
35 changes: 34 additions & 1 deletion src/cf_ui/templates/cotton/_themes/bootstrap/button.html
Original file line number Diff line number Diff line change
@@ -1 +1,34 @@
{% with cf_tag=href|yesno:"a,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 class %} {{ 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 %}{{ slot }}</{{ cf_tag }}>{% endwith %}
{% load cf_ui %}
{% cf_ui_class as cf_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 class %}
{{ 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 %}
33 changes: 32 additions & 1 deletion src/cf_ui/templates/cotton/_themes/bulma/button.html
Original file line number Diff line number Diff line change
@@ -1 +1,32 @@
{% with cf_tag=href|yesno:"a,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 class %} {{ 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 %}>{{ slot }}</{{ cf_tag }}>{% endwith %}
{% load cf_ui %}
{% cf_ui_class as cf_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 class %}
{{ 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 %}
35 changes: 34 additions & 1 deletion src/cf_ui/templates/cotton/_themes/daisy/button.html
Original file line number Diff line number Diff line change
@@ -1 +1,34 @@
{% with cf_tag=href|yesno:"a,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 class %} {{ 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 %}{{ slot }}</{{ cf_tag }}>{% endwith %}
{% load cf_ui %}
{% cf_ui_class as cf_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 class %}
{{ 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 %}
35 changes: 34 additions & 1 deletion src/cf_ui/templates/cotton/_themes/fomantic/button.html
Original file line number Diff line number Diff line change
@@ -1 +1,34 @@
{% with cf_tag=href|yesno:"a,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 class %} {{ 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 %}>{{ slot }}</{{ cf_tag }}>{% endwith %}
{% load cf_ui %}
{% cf_ui_class as cf_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 class %}
{{ 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 %}
33 changes: 32 additions & 1 deletion src/cf_ui/templates/cotton/_themes/foundation/button.html
Original file line number Diff line number Diff line change
@@ -1 +1,32 @@
{% with cf_tag=href|yesno:"a,button" %}<{{ cf_tag }} class="button{% if variant == 'primary' %} primary{% elif variant == 'secondary' %} secondary{% elif variant == 'success' %} success{% elif variant == 'warning' %} warning{% elif variant == 'danger' %} alert{% elif variant == 'info' %} secondary{% endif %}{% if size == 'small' %} small{% elif size == 'large' %} large{% endif %}{% if state == 'disabled' %} disabled{% endif %}{% if full_width %} expanded{% endif %}{% if class %} {{ 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 %}>{{ slot }}</{{ cf_tag }}>{% endwith %}
{% load cf_ui %}
{% cf_ui_class as cf_class %}
button
{% if variant == 'primary' %}
primary
{% elif variant == 'secondary' %}
secondary
{% elif variant == 'success' %}
success
{% elif variant == 'warning' %}
warning
{% elif variant == 'danger' %}
alert
{% elif variant == 'info' %}
secondary
{% endif %}
{% if size == 'small' %}
small
{% elif size == 'large' %}
large
{% endif %}
{% if state == 'disabled' %}
disabled
{% endif %}
{% if full_width %}
expanded
{% endif %}
{% if class %}
{{ 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 %}
57 changes: 57 additions & 0 deletions src/cf_ui/templatetags/cf_ui.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import re

from django import template
from django.conf import settings
from django.templatetags.static import static
Expand All @@ -10,6 +12,8 @@

register = template.Library()

_WHITESPACE_RE = re.compile(r"\s+")

_CDN_CSS = {
"bulma": "https://cdn.jsdelivr.net/npm/bulma@{v}/css/bulma.min.css",
"bootstrap": "https://cdn.jsdelivr.net/npm/bootstrap@{v}/dist/css/bootstrap.min.css",
Expand Down Expand Up @@ -136,6 +140,59 @@ def cf_ui_validate(component: str, **axes) -> str:
return validate_primitive(component, **axes)


class ClassCaptureNode(template.Node):
def __init__(self, nodelist, target_var=None):
self.nodelist = nodelist
self.target_var = target_var

def render(self, context) -> str:
collapsed = _WHITESPACE_RE.sub(" ", self.nodelist.render(context)).strip()
if self.target_var:
context[self.target_var] = mark_safe(collapsed)
return ""
return mark_safe(collapsed)


@register.tag("cf_ui_class")
def cf_ui_class(parser, token):
"""Collapse a multi-line ``{% if %}`` class chain to a single-space string.

Django has no Jinja-style ``{%- -%}`` trim markers, so a chained
``{% if %}...{% elif %}...{% endif %}`` class attribute has to stay on one
physical line — a literal newline anywhere in the block becomes literal
whitespace in the rendered ``class`` attribute. This tag lets the same
chain be written readably, one branch per line, by rendering its nodelist
normally (inheriting ambient autoescape — a hostile ``{{ class }}`` is
escaped exactly as it already was) and then collapsing every run of
whitespace between tokens to one space and stripping the ends::

<button class="{% cf_ui_class %}
button
{% if variant == 'primary' %}is-primary{% endif %}
{% endcf_ui_class %}">

``as <varname>`` stores the result in the context and renders nothing
inline, for keeping the multi-line block out of the attribute value::

{% cf_ui_class as cf_class %}
button
{% if variant == 'primary' %}is-primary{% endif %}
{% endcf_ui_class %}
<button class="{{ cf_class }}">
"""
bits = token.split_contents()
target_var = None
if len(bits) == 3 and bits[1] == "as":
target_var = bits[2]
elif len(bits) != 1:
raise template.TemplateSyntaxError(
f"{bits[0]!r} takes either no arguments or 'as <varname>'"
)
nodelist = parser.parse(("endcf_ui_class",))
parser.delete_first_token()
return ClassCaptureNode(nodelist, target_var=target_var)


@register.simple_tag
def cf_ui_body(alpine: bool = True) -> str:
if not alpine:
Expand Down
118 changes: 118 additions & 0 deletions tests/unit/test_cf_ui_class_tag.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"""``{% cf_ui_class %}`` — whitespace-collapse for cotton class chains.

Django has no Jinja-style ``{%- -%}`` trim markers (see
``tests/unit/test_theme_dispatch.py`` for the cotton dispatch story and
CLAUDE.md's django-cotton gotchas), so a chained ``{% if %}...{% elif
%}...{% endif %}`` class attribute has to stay on one physical line or a
literal newline becomes literal whitespace in the rendered ``class``
attribute. This tag lets that chain be written one branch per line by
rendering its nodelist normally and collapsing the result's whitespace runs
to a single space, stripped at both ends.
"""

import pytest
from django.template import Context, Template, TemplateSyntaxError

HOSTILE = '" onmouseover="window.cfPwned=true" x="'


def _render(source: str, **ctx) -> str:
return Template("{% load cf_ui %}" + source).render(Context(ctx))


def test_collapses_internal_whitespace_to_single_spaces():
out = _render(
"{% cf_ui_class %}\n button\n {% if hot %}\n is-primary\n {% endif %}\n"
"{% endcf_ui_class %}",
hot=True,
)
assert out == "button is-primary"


def test_strips_leading_and_trailing_whitespace():
out = _render("{% cf_ui_class %}\n button\n{% endcf_ui_class %}")
assert out == "button"


def test_a_branch_that_does_not_render_leaves_no_double_space():
out = _render(
"{% cf_ui_class %}\n button\n {% if hot %}is-primary{% endif %}\n is-small\n"
"{% endcf_ui_class %}",
hot=False,
)
assert out == "button is-small"
assert " " not in out


def test_renders_inline_by_default():
out = _render('<button class="{% cf_ui_class %}button{% endcf_ui_class %}">')
assert out == '<button class="button">'


def test_as_form_stores_the_result_and_renders_nothing_inline():
out = _render(
"[{% cf_ui_class as cf_class %}\n button\n extra\n{% endcf_ui_class %}]"
'<button class="{{ cf_class }}">'
)
assert out == '[]<button class="button extra">'


def test_hostile_class_prop_is_escaped_like_any_other_django_output():
"""The tag only reflows whitespace — it does not turn off autoescape.

Each ``{{ }}`` inside the captured nodelist is escaped exactly as Django
would escape it in place; ``mark_safe`` on the joined result must not
reopen that hole.
"""
out = _render(
"{% cf_ui_class %}\n button\n {% if extra %}{{ extra }}{% endif %}\n{% endcf_ui_class %}",
extra=HOSTILE,
)
assert 'onmouseover="window.cfPwned=true"' not in out
assert "&#34;" in out or "&quot;" in out


def test_rejects_a_second_bit_that_is_not_as():
with pytest.raises(TemplateSyntaxError, match="takes either no arguments"):
Template("{% load cf_ui %}{% cf_ui_class oops %}x{% endcf_ui_class %}")


def test_rejects_more_than_two_bits_after_as():
with pytest.raises(TemplateSyntaxError, match="takes either no arguments"):
Template("{% load cf_ui %}{% cf_ui_class as x y %}z{% endcf_ui_class %}")


# --- Applied to the real button partials -----------------------------------


@pytest.mark.parametrize("theme", ["bulma", "bootstrap", "foundation", "fomantic", "daisy"])
def test_button_partial_class_attribute_has_no_stray_whitespace(settings, theme):
"""The property the reformat was actually done for.

A regression here would mean either the tag stopped collapsing (multiple
spaces or a stray newline leaking into the attribute) or a template
stopped using it (falling back to Django's raw multi-line join).
"""
import re

from django.template.loader import render_to_string

settings.CF_UI_THEME = theme
html = render_to_string(
"cotton/cf/button.html",
{
"variant": "primary",
"size": "small",
"full_width": True,
"class": "extra-token",
# render_to_string bypasses <c-vars> defaults (see CLAUDE.md's
# django-cotton gotchas), so the type axis needs a value here.
"type": "submit",
},
)
match = re.search(r'class="([^"]*)"', html)
assert match, f"{theme}: no class attribute found in {html!r}"
class_value = match.group(1)
assert " " not in class_value
assert class_value == class_value.strip()
assert "\n" not in class_value
Loading
Loading