refactor: allow Checkbox and Radio primitives to render headlessly without labels
This commit is contained in:
@@ -403,7 +403,7 @@ def Label(
|
||||
|
||||
def Checkbox(
|
||||
name: str,
|
||||
label: str,
|
||||
label: str | None = None,
|
||||
checked: bool = False,
|
||||
value: str = "1",
|
||||
attributes: list[HTMLAttribute] | None = None,
|
||||
@@ -421,20 +421,21 @@ def Checkbox(
|
||||
if checked:
|
||||
input_attrs.append(("checked", "true"))
|
||||
|
||||
input_el = Input(type="checkbox", attributes=input_attrs)
|
||||
if label is None:
|
||||
return input_el
|
||||
|
||||
return Label(
|
||||
attributes=[
|
||||
("class", "flex items-center gap-2 text-sm text-heading cursor-pointer")
|
||||
],
|
||||
children=[
|
||||
Input(type="checkbox", attributes=input_attrs),
|
||||
label,
|
||||
],
|
||||
children=[input_el, label],
|
||||
)
|
||||
|
||||
|
||||
def Radio(
|
||||
name: str,
|
||||
label: str,
|
||||
label: str | None = None,
|
||||
checked: bool = False,
|
||||
value: str = "",
|
||||
attributes: list[HTMLAttribute] | None = None,
|
||||
@@ -452,14 +453,15 @@ def Radio(
|
||||
if checked:
|
||||
input_attrs.append(("checked", "true"))
|
||||
|
||||
input_el = Input(type="radio", attributes=input_attrs)
|
||||
if label is None:
|
||||
return input_el
|
||||
|
||||
return Label(
|
||||
attributes=[
|
||||
("class", "flex items-center gap-1.5 text-sm text-heading cursor-pointer")
|
||||
],
|
||||
children=[
|
||||
Input(type="radio", attributes=input_attrs),
|
||||
label,
|
||||
],
|
||||
children=[input_el, label],
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -827,13 +827,22 @@ from common.components.primitives import Checkbox, Radio
|
||||
|
||||
class ComponentPrimitivesTest(SimpleTestCase):
|
||||
def test_checkbox_primitive(self):
|
||||
html = Checkbox(name="test-check", label="Accept Terms", checked=True, value="yes")
|
||||
html = Checkbox(
|
||||
name="test-check", label="Accept Terms", checked=True, value="yes"
|
||||
)
|
||||
self.assertIn('type="checkbox"', html)
|
||||
self.assertIn('name="test-check"', html)
|
||||
self.assertIn('value="yes"', html)
|
||||
self.assertIn('checked="true"', html)
|
||||
self.assertIn("Accept Terms", html)
|
||||
|
||||
def test_checkbox_headless(self):
|
||||
html = Checkbox(name="test-headless", label=None, checked=True)
|
||||
self.assertNotIn("<label", html)
|
||||
self.assertIn("<input", html)
|
||||
self.assertIn('type="checkbox"', html)
|
||||
self.assertIn('name="test-headless"', html)
|
||||
|
||||
def test_radio_primitive(self):
|
||||
html = Radio(name="test-radio", label="Option A", checked=False, value="A")
|
||||
self.assertIn('type="radio"', html)
|
||||
|
||||
Reference in New Issue
Block a user