Skip to main content

euv_example/pages/themes/
fn.rs

1use super::*;
2
3/// Resolves the `(surface, paired foreground)` colors of semantic palette role `idx` so swatch text is always contrast-paired with its own surface.
4///
5/// # Arguments
6///
7/// - `&ThemePalette` - Live palette.
8/// - `usize` - Role index into `THEMES_ROLE_LABELS`.
9///
10/// # Returns
11///
12/// - `(Color, Color)` - Surface color and its readable paired foreground.
13pub(crate) fn themes_role_colors(p: &ThemePalette, idx: usize) -> (Color, Color) {
14    match idx {
15        1 => (p.get_card(), p.get_card_foreground()),
16        2 => (p.get_primary(), p.get_primary_foreground()),
17        3 => (p.get_secondary(), p.get_secondary_foreground()),
18        4 => (p.get_muted(), p.get_foreground()),
19        5 => (p.get_accent(), p.get_foreground()),
20        6 => (p.get_destructive(), p.get_destructive_foreground()),
21        7 => (p.get_success(), p.get_success_foreground()),
22        8 => (p.get_warning(), p.get_warning_foreground()),
23        _ => (p.get_background(), p.get_foreground()),
24    }
25}
26
27/// Resolves the shared corner radius of scale step `idx` from the canonical geometry.
28///
29/// # Arguments
30///
31/// - `&ThemeGeometry` - Live geometry tokens.
32/// - `usize` - Step index into `THEMES_RADIUS_LABELS`.
33///
34/// # Returns
35///
36/// - `f32` - Corner radius in logical pixels.
37pub(crate) fn themes_radius_value(g: &ThemeGeometry, idx: usize) -> f32 {
38    match idx {
39        0 => g.get_radius_sm(),
40        1 => g.get_radius_md(),
41        2 => g.get_radius_lg(),
42        3 => g.get_radius_xl(),
43        _ => THEMES_PILL_RADIUS,
44    }
45}
46
47/// Mounts one live semantic palette swatch whose surface and label colors both track the active scheme.
48///
49/// # Arguments
50///
51/// - `usize` - Role index into `THEMES_ROLE_LABELS`.
52/// - `ThemeTokens` - Design tokens at mount time.
53///
54/// # Returns
55///
56/// - `NodeId` - Mounted swatch node.
57pub(crate) fn mount_theme_swatch(idx: usize, tokens: ThemeTokens) -> NodeId {
58    let label: &'static str = THEMES_ROLE_LABELS[idx];
59    let swatch_style = move || -> Style {
60        let live: ThemeTokens = use_live_tokens(tokens);
61        let (bg, _): (Color, Color) = themes_role_colors(&live.get_palette(), idx);
62        Style::default()
63            .column()
64            .width(Length::Percent(100.0))
65            .height(Length::Px(THEMES_SWATCH_HEIGHT))
66            .padding(Edges::all(SPACE_MD))
67            .gap(SPACE_XS)
68            .justify(JustifyContent::End)
69            .overflow(Overflow::Hidden)
70            .background(bg)
71            .border(
72                live.get_geometry().get_border_width(),
73                live.get_palette().get_border(),
74            )
75            .radius(live.get_geometry().get_radius_lg())
76    };
77    let name_style = move || -> Style {
78        let live: ThemeTokens = use_live_tokens(tokens);
79        let (_, fg): (Color, Color) = themes_role_colors(&live.get_palette(), idx);
80        Style::default()
81            .width(Length::Percent(100.0))
82            .font_size(live.get_geometry().get_font_body())
83            .font_weight(FontWeight::SemiBold)
84            .color(fg)
85    };
86    let hex_style = move || -> Style {
87        let live: ThemeTokens = use_live_tokens(tokens);
88        let (_, fg): (Color, Color) = themes_role_colors(&live.get_palette(), idx);
89        Style::default()
90            .width(Length::Percent(100.0))
91            .font_size(live.get_geometry().get_font_body() - 1.5)
92            .font_family(FontFamily::Monospace)
93            .color(fg)
94    };
95    let hex_text = move || -> String {
96        let live: ThemeTokens = use_live_tokens(tokens);
97        let (bg, _): (Color, Color) = themes_role_colors(&live.get_palette(), idx);
98        format!("#{:02X}{:02X}{:02X}", bg.get_r(), bg.get_g(), bg.get_b())
99    };
100    view! {
101        view {
102            bind_style: swatch_style
103            text {
104                bind_style: name_style
105                { label }
106            }
107            text {
108                bind_style: hex_style
109                { hex_text }
110            }
111        }
112    }
113}
114
115/// Mounts one labelled tile of the shared corner radius scale.
116///
117/// # Arguments
118///
119/// - `usize` - Step index into `THEMES_RADIUS_LABELS`.
120/// - `ThemeTokens` - Design tokens at mount time.
121///
122/// # Returns
123///
124/// - `NodeId` - Mounted radius tile node.
125pub(crate) fn mount_radius_tile(idx: usize, tokens: ThemeTokens) -> NodeId {
126    let p: ThemePalette = tokens.get_palette();
127    let caption: String = THEMES_RADIUS_LABELS[idx].to_string();
128    let tile_style = move || -> Style {
129        let live: ThemeTokens = use_live_tokens(tokens);
130        let live_p: ThemePalette = live.get_palette();
131        Style::default()
132            .width(Length::Px(THEMES_RADIUS_TILE))
133            .height(Length::Px(THEMES_RADIUS_TILE))
134            .background(live_p.get_primary().with_alpha(36))
135            .border(2.0, live_p.get_primary())
136            .radius(themes_radius_value(&live.get_geometry(), idx))
137    };
138    view! {
139        column {
140            style: {
141                align: AlignItems::Center
142                gap: SPACE_XS
143            }
144            view {
145                bind_style: tile_style
146            }
147            text {
148                style: {
149                    font_size: 12.0
150                    font_family: FontFamily::Monospace
151                    color: p.get_muted_foreground()
152                }
153                { caption }
154            }
155        }
156    }
157}
158
159/// Mounts one spec row (label, visual bar sized by `value`, numeric value) used by the control-height, typography and spacing scales.
160///
161/// # Arguments
162///
163/// - `String` - Token label.
164/// - `f32` - Token value in logical pixels.
165/// - `NodeId` - Pre-mounted visual sample.
166/// - `ThemeTokens` - Design tokens at mount time.
167///
168/// # Returns
169///
170/// - `NodeId` - Mounted spec row.
171pub(crate) fn mount_token_row(
172    label: String,
173    value: f32,
174    sample: NodeId,
175    tokens: ThemeTokens,
176) -> NodeId {
177    let p: ThemePalette = tokens.get_palette();
178    let value_txt: String = format!("{value:.0}px");
179    view! {
180        row {
181            style: {
182                width: Length::Percent(100.0)
183                align: AlignItems::Center
184                gap: SPACE_MD
185            }
186            text {
187                style: {
188                    width: Length::Px(96.0)
189                    flex_shrink: 0.0
190                    font_size: 12.5
191                    font_family: FontFamily::Monospace
192                    color: p.get_muted_foreground()
193                }
194                { label }
195            }
196            row {
197                style: {
198                    flex_grow: 1.0
199                    flex_shrink: 1.0
200                    min_width: Length::Px(0.0)
201                    align: AlignItems::Center
202                    overflow: Overflow::Hidden
203                }
204                { sample }
205            }
206            text {
207                style: {
208                    flex_shrink: 0.0
209                    font_size: 12.5
210                    font_family: FontFamily::Monospace
211                    color: p.get_foreground()
212                }
213                { value_txt }
214            }
215        }
216    }
217}
218
219/// Mounts a primary-tinted horizontal bar of `width` x `height` pixels used as a scale sample.
220///
221/// # Arguments
222///
223/// - `f32` - Bar width in logical pixels.
224/// - `f32` - Bar height in logical pixels.
225/// - `ThemeTokens` - Design tokens at mount time.
226///
227/// # Returns
228///
229/// - `NodeId` - Mounted bar node.
230pub(crate) fn mount_scale_bar(width: f32, height: f32, tokens: ThemeTokens) -> NodeId {
231    let bar_style = move || -> Style {
232        let live: ThemeTokens = use_live_tokens(tokens);
233        Style::default()
234            .width(Length::Px(width))
235            .height(Length::Px(height))
236            .background(live.get_palette().get_primary().with_alpha(64))
237            .border(1.0, live.get_palette().get_primary())
238            .radius(live.get_geometry().get_radius_sm())
239    };
240    view! {
241        view {
242            bind_style: bar_style
243        }
244    }
245}
246
247/// Mounts the Design System studio: scheme selector + live preview rail beside the semantic palette, radius, control-height, typography and spacing scales.
248///
249/// # Arguments
250///
251/// - `&ShowcaseState` - Reactive showcase state.
252/// - `ThemeTokens` - Active design tokens.
253///
254/// # Returns
255///
256/// - `NodeId` - Mounted themes page node.
257pub fn mount_themes_page(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
258    let p: ThemePalette = tokens.get_palette();
259    let g: ThemeGeometry = tokens.get_geometry();
260    let scheme_sig: Signal<DesignScheme> = state.get_theme().get_scheme();
261    let mode_sig: Signal<ThemeMode> = state.get_theme().get_mode();
262    let state_for_cycle: ShowcaseState = state.clone();
263    let state_for_mode: ShowcaseState = state.clone();
264    let active_text = move || -> String {
265        format!(
266            "{PREFIX_ACTIVE_SCHEME}{} ({:?})",
267            scheme_sig.get().as_str(),
268            mode_sig.get()
269        )
270    };
271    let on_next_scheme = move |_: &UiEvent| {
272        state_for_cycle.next_scheme();
273    };
274    let on_toggle_mode = move |_: &UiEvent| {
275        state_for_mode.toggle_theme_mode();
276    };
277    let scheme_buttons: Vec<NodeId> = DesignScheme::all()
278        .iter()
279        .copied()
280        .map(|scheme: DesignScheme| {
281            let on_pick = move |_: &UiEvent| {
282                let _: bool = scheme_sig.set_if_changed(scheme);
283            };
284            let btn_style = move || -> Style {
285                let live: ThemeTokens = use_live_tokens(tokens);
286                let live_p: ThemePalette = live.get_palette();
287                let live_g: ThemeGeometry = live.get_geometry();
288                let active: bool = scheme_sig.get() == scheme;
289                let bg: Color = if active {
290                    live_p.get_primary()
291                } else {
292                    live_p.get_background()
293                };
294                let border: Color = if active {
295                    live_p.get_primary()
296                } else {
297                    live_p.get_border()
298                };
299                Style::default()
300                    .row()
301                    .width(Length::Percent(100.0))
302                    .height(Length::Px(live_g.get_control_sm()))
303                    .padding(Edges::symmetric(0.0, SPACE_SM))
304                    .align(AlignItems::Center)
305                    .gap(SPACE_SM)
306                    .overflow(Overflow::Hidden)
307                    .background(bg)
308                    .border(live_g.get_border_width(), border)
309                    .radius(live_g.get_radius_md())
310                    .cursor(CursorIcon::Pointer)
311            };
312            let dot_style = move || -> Style {
313                let mode: ThemeMode = mode_sig.get();
314                let preview: ThemePalette = ThemeTokens::resolve(scheme, mode).get_palette();
315                let live_p: ThemePalette = use_live_tokens(tokens).get_palette();
316                Style::default()
317                    .width(Length::Px(10.0))
318                    .height(Length::Px(10.0))
319                    .flex_shrink(0.0)
320                    .background(preview.get_primary())
321                    .border(1.0, live_p.get_border())
322                    .radius(THEMES_PILL_RADIUS)
323            };
324            let lbl_style = move || -> Style {
325                let live: ThemeTokens = use_live_tokens(tokens);
326                let live_p: ThemePalette = live.get_palette();
327                let active: bool = scheme_sig.get() == scheme;
328                let fg: Color = if active {
329                    live_p.get_primary_foreground()
330                } else {
331                    live_p.get_foreground()
332                };
333                Style::default()
334                    .flex_grow(1.0)
335                    .flex_shrink(1.0)
336                    .min_width(Length::Px(0.0))
337                    .font_size(12.5)
338                    .font_weight(FontWeight::Medium)
339                    .color(fg)
340                    .overflow(Overflow::Hidden)
341                    .text_overflow(TextOverflow::Ellipsis)
342            };
343            view! {
344                row {
345                    bind_style: btn_style
346                    role: A11yRole::Button
347                    on_click: on_pick
348                    view {
349                        bind_style: dot_style
350                    }
351                    text {
352                        bind_style: lbl_style
353                        { scheme.as_str().to_string() }
354                    }
355                }
356            }
357        })
358        .collect();
359    let swatches: Vec<NodeId> = (0..THEMES_ROLE_LABELS.len())
360        .map(|idx: usize| mount_theme_swatch(idx, tokens))
361        .collect();
362    let palette_grid: NodeId = mount_responsive_grid(swatches, 3);
363    let radius_tiles: Vec<NodeId> = (0..THEMES_RADIUS_LABELS.len())
364        .map(|idx: usize| mount_radius_tile(idx, tokens))
365        .collect();
366    let control_values: [f32; 3] = [g.get_control_sm(), g.get_control_md(), g.get_control_lg()];
367    let control_rows: Vec<NodeId> = control_values
368        .iter()
369        .enumerate()
370        .map(|(idx, value): (usize, &f32)| {
371            let bar: NodeId = mount_scale_bar(*value * 3.0, *value, tokens);
372            mount_token_row(THEMES_CONTROL_LABELS[idx].to_string(), *value, bar, tokens)
373        })
374        .collect();
375    let type_values: [f32; 3] = [g.get_font_body(), g.get_font_heading(), g.get_font_title()];
376    let type_rows: Vec<NodeId> = type_values
377        .iter()
378        .enumerate()
379        .map(|(idx, value): (usize, &f32)| {
380            let size: f32 = *value;
381            let sample: NodeId = view! {
382                text {
383                    style: {
384                        font_size: size
385                        font_weight: FontWeight::SemiBold
386                        color: p.get_foreground()
387                        overflow: Overflow::Hidden
388                        text_overflow: TextOverflow::Ellipsis
389                    }
390                    { THEMES_TYPE_SAMPLE }
391                }
392            };
393            mount_token_row(THEMES_TYPE_LABELS[idx].to_string(), size, sample, tokens)
394        })
395        .collect();
396    let space_rows: Vec<NodeId> = THEMES_SPACE_VALUES
397        .iter()
398        .enumerate()
399        .map(|(idx, value): (usize, &f32)| {
400            let bar: NodeId = mount_scale_bar(*value * 4.0, SPACE_MD, tokens);
401            mount_token_row(THEMES_SPACE_LABELS[idx].to_string(), *value, bar, tokens)
402        })
403        .collect();
404    let preview_query: Signal<String> = Signal::new(String::new());
405    let preview_switch: Signal<bool> = Signal::new(true);
406    let selector_card: NodeId = view! {
407        EuvCard {
408            title: THEMES_CARD_TITLE.to_string()
409            tokens: tokens
410            subtitle: THEMES_CARD_SUB
411            text {
412                style: {
413                    width: Length::Percent(100.0)
414                    font_size: 14.0
415                    font_weight: FontWeight::SemiBold
416                    color: p.get_foreground()
417                }
418                { active_text }
419            }
420            EuvActionRow {
421                EuvButton {
422                    label: BTN_NEXT_SCHEME.to_string()
423                    tokens: tokens
424                    sm()
425                    on_click: on_next_scheme
426                }
427                EuvButton {
428                    label: BTN_TOGGLE_MODE.to_string()
429                    tokens: tokens
430                    outline()
431                    sm()
432                    on_click: on_toggle_mode
433                }
434            }
435            grid {
436                style: {
437                    width: Length::Percent(100.0)
438                    columns: 2
439                    gap: SPACE_SM
440                }
441                ..scheme_buttons
442            }
443        }
444    };
445    let preview_card: NodeId = view! {
446        EuvCard {
447            title: THEMES_PREVIEW_TITLE.to_string()
448            tokens: tokens
449            subtitle: THEMES_PREVIEW_SUB
450            EuvInput {
451                value: preview_query
452                placeholder: THEMES_PREVIEW_INPUT.to_string()
453                tokens: tokens
454            }
455            EuvActionRow {
456                EuvButton {
457                    label: THEMES_PREVIEW_PRIMARY.to_string()
458                    tokens: tokens
459                    sm()
460                }
461                EuvButton {
462                    label: THEMES_PREVIEW_SECONDARY.to_string()
463                    tokens: tokens
464                    secondary()
465                    sm()
466                }
467                EuvButton {
468                    label: THEMES_PREVIEW_OUTLINE.to_string()
469                    tokens: tokens
470                    outline()
471                    sm()
472                }
473            }
474            row {
475                style: {
476                    width: Length::Percent(100.0)
477                    flex_wrap: FlexWrap::Wrap
478                    align: AlignItems::Center
479                    gap: SPACE_SM
480                }
481                EuvBadge {
482                    label: THEMES_BADGE_STABLE.to_string()
483                    tone: EuvTone::Success
484                    tokens: tokens
485                }
486                EuvBadge {
487                    label: THEMES_BADGE_BETA.to_string()
488                    tone: EuvTone::Warning
489                    tokens: tokens
490                }
491                EuvBadge {
492                    label: THEMES_BADGE_NEW.to_string()
493                    tone: EuvTone::Primary
494                    tokens: tokens
495                }
496            }
497            EuvSwitch {
498                checked: preview_switch
499                label: THEMES_PREVIEW_SWITCH.to_string()
500                tokens: tokens
501            }
502        }
503    };
504    let rail: NodeId = view! {
505        column {
506            style: {
507                width: Length::Percent(100.0)
508                gap: SPACE_MD
509            }
510            { selector_card }
511            { preview_card }
512        }
513    };
514    let scale_cards: Vec<NodeId> = vec![
515        view! {
516            EuvCard {
517                title: THEMES_RADIUS_TITLE.to_string()
518                tokens: tokens
519                subtitle: THEMES_RADIUS_SUB
520                row {
521                    style: {
522                        width: Length::Percent(100.0)
523                        flex_wrap: FlexWrap::Wrap
524                        gap: SPACE_LG
525                    }
526                    ..radius_tiles
527                }
528            }
529        },
530        view! {
531            EuvCard {
532                title: THEMES_CONTROL_TITLE.to_string()
533                tokens: tokens
534                subtitle: THEMES_CONTROL_SUB
535                ..control_rows
536            }
537        },
538        view! {
539            EuvCard {
540                title: THEMES_TYPE_TITLE.to_string()
541                tokens: tokens
542                subtitle: THEMES_TYPE_SUB
543                ..type_rows
544            }
545        },
546        view! {
547            EuvCard {
548                title: THEMES_SPACE_TITLE.to_string()
549                tokens: tokens
550                subtitle: THEMES_SPACE_SUB
551                ..space_rows
552            }
553        },
554    ];
555    let scale_grid: NodeId = mount_responsive_grid(scale_cards, 2);
556    let main: NodeId = view! {
557        column {
558            style: {
559                width: Length::Percent(100.0)
560                gap: SPACE_MD
561            }
562            EuvCard {
563                title: THEMES_PALETTE_TITLE.to_string()
564                tokens: tokens
565                subtitle: THEMES_PALETTE_SUB
566                { palette_grid }
567            }
568            { scale_grid }
569        }
570    };
571    let studio: NodeId = mount_studio_layout(main, rail);
572    view! {
573        EuvPage {
574            title: THEMES_TITLE.to_string()
575            subtitle: THEMES_SUBTITLE.to_string()
576            tokens: tokens
577            { studio }
578        }
579    }
580}