Skip to main content

tablo_ui/components/composites/
select.rs

1//! Tablo's select: a native `<select>` on the control surface, its picker customizable where the
2//! browser allows. The wrapper carries `data-slot="select"`.
3
4use topcoat::{
5    Result,
6    context::Cx,
7    icon::{IconData, icon, iconify::iconify_icon},
8    view::{Attributes, Child, StaticClass, View, attributes, class, component, view},
9};
10
11/// Classes for the select control, with space for a custom dropdown arrow.
12const SELECT: StaticClass = class!(
13    "h-9 w-full cursor-pointer appearance-none items-center rounded-md border border-input",
14    "bg-control pr-8 pl-3 text-left text-sm text-foreground shadow-control",
15    "transition-[border-color,box-shadow] outline-none",
16    "hover:border-[color-mix(in_oklab,var(--input),var(--foreground)_22%)]",
17    "focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/20",
18    "aria-invalid:border-destructive aria-invalid:focus-visible:ring-destructive/20",
19    "disabled:pointer-events-none",
20);
21
22const PICKER: StaticClass = class!(
23    "[&::picker(select)]:[appearance:base-select]",
24    "[&::picker(select)]:mt-1 [&::picker(select)]:rounded-lg",
25    "[&::picker(select)]:border [&::picker(select)]:border-border",
26    "[&::picker(select)]:bg-popover [&::picker(select)]:p-1",
27    "[&::picker(select)]:text-popover-foreground [&::picker(select)]:shadow-lg",
28    "[&::picker-icon]:hidden",
29    "[&_optgroup>legend]:px-2 [&_optgroup>legend]:py-1.5",
30    "[&_optgroup>legend]:text-xs [&_optgroup>legend]:font-medium",
31    "[&_optgroup>legend]:text-muted-foreground [&_optgroup>legend]:cursor-default",
32    "[&_optgroup>legend]:select-none",
33    "[&_option]:flex [&_option]:items-center [&_option]:gap-2 [&_option]:rounded-md",
34    "[&_option]:px-2 [&_option]:py-1.5 [&_option]:text-sm [&_option]:outline-none",
35    "[&_option:hover]:bg-mark [&_option:focus]:bg-mark",
36    "[&_option:checked]:font-medium",
37    "[&_option::checkmark]:order-1 [&_option::checkmark]:ml-auto",
38    "[&_option::checkmark]:size-4 [&_option::checkmark]:shrink-0",
39    "[&_option::checkmark]:content-[''] [&_option::checkmark]:bg-muted-foreground",
40    "[&_option::checkmark]:[mask-size:100%_100%]",
41    "[&_option::checkmark]:[mask-image:var(--select-checkmark)]",
42);
43
44/// The icon marking the picker's checked option.
45const CHECKMARK: IconData = iconify_icon!("lucide:check");
46
47/// Supplies the checkmark icon as a data URI in `--select-checkmark` so CSS can use it
48/// as a mask.
49fn checkmark_style(cx: &Cx) -> String {
50    let svg = format!(
51        r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="{}">{}</svg>"#,
52        CHECKMARK.view_box(),
53        CHECKMARK.into_body().render(cx),
54    );
55    let mut style = String::from(r#"--select-checkmark: url("data:image/svg+xml,"#);
56    // Percent-encode the characters that cannot appear in a double-quoted
57    // CSS url().
58    for char in svg.chars() {
59        match char {
60            '%' => style.push_str("%25"),
61            '"' => style.push_str("%22"),
62            '#' => style.push_str("%23"),
63            _ => style.push(char),
64        }
65    }
66    style.push_str(r#"")"#);
67    style
68}
69
70/// A styled native select control.
71///
72/// Pass `<option>` or `<optgroup>` elements as children. Classes in `attrs` apply to
73/// the wrapper, while other attributes and event handlers go on the `<select>`. The
74/// control fills its container by default. Set `aria-invalid="true"` to show the error
75/// border and focus ring.
76///
77/// Browsers with customizable select support also style the picker. For a styled group
78/// heading, place a `<legend>` first inside an `<optgroup>` and keep its `label`
79/// attribute for browsers that use the native picker.
80///
81/// ```ignore
82/// view! {
83///     select(
84///         attrs: attributes! { name="region" },
85///         <option>"eu-central-1"</option>
86///         <option>"us-east-1"</option>
87///     )
88/// }
89/// ```
90#[component]
91pub async fn select(
92    cx: &Cx,
93    #[default] mut attrs: Attributes,
94    #[default] child: Child<'_>,
95) -> Result<impl View> {
96    // `appearance: base-select` opts into the customizable picker. It is set
97    // from the wrapper because the descendant selector outranks the
98    // `appearance-none` fallback in specificity, making the outcome
99    // independent of stylesheet order; browsers without support drop the
100    // invalid declaration and keep the fallback.
101    Ok(view! {
102        <span
103            data-slot="select"
104            class=(class!(
105                "relative block has-[:disabled]:opacity-50",
106                "[&>select]:[appearance:base-select]",
107                "[&:has(select:open)>svg]:rotate-180",
108                attrs.remove("class"),
109            ))
110            style=(checkmark_style(cx))
111        >
112            <select class=(class!(SELECT, PICKER)) (attrs)>(child)</select>
113            icon(
114                data: iconify_icon!("lucide:chevron-down"),
115                attrs: attributes! {
116                    class="pointer-events-none absolute top-1/2 right-3 size-4 \
117                        -translate-y-1/2 text-muted-foreground transition-transform"
118                }
119            )
120        </span>
121    })
122}