liora-components 0.1.9

Enterprise-style native GPUI component library for Liora applications.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Accordion module.
//!
//! This public module implements the Liora accordion component for compact FAQ, settings, and documentation sections. It keeps the reusable
//! component logic inside `liora-components` rather than Gallery or Docs so
//! downstream GPUI applications can compose the same behavior with their own
//! app state, assets, and release policy.
//!
//! ## Usage model
//!
//! Components in this module render native GPUI element trees. Stateless builder
//! values can be constructed inline, while controls with focus, selection,
//! popup, drag, or editing state should be stored as `gpui::Entity<T>` fields in
//! the parent view so state survives GPUI render passes.
//!
//! ## Design contract
//!
//! The implementation should use Liora theme tokens from `liora-core` and
//! `liora-theme`, keep accessibility-oriented keyboard/pointer behavior close to
//! the component, and avoid app-specific Gallery/Docs resources in this SDK
//! crate.

use crate::{gpui_compat::element_id, motion::pop_in};
use gpui::{
    AnyElement, Context, IntoElement, MouseButton, Pixels, Render, SharedString, Window, div,
    prelude::*, px,
};
use liora_core::{Config, unique_id};
use liora_icons::Icon;
use liora_icons_lucide::IconName;
use std::{collections::HashSet, sync::Arc};

/// Data model used by Accordion item rendering.
pub struct AccordionItem {
    /// Stable identifier used by selection state and callbacks.
    pub id: SharedString,
    /// User-facing heading rendered in the trigger row.
    pub title: SharedString,
    /// Optional secondary description rendered under the title.
    pub description: Option<SharedString>,
    /// Whether the trigger is inert and styled as disabled.
    pub disabled: bool,
    /// Content rendered inside the expanded panel.
    pub content: Arc<dyn Fn(&mut Window, &mut Context<Accordion>) -> AnyElement + 'static>,
}

/// Controls whether one or many panels can be open.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccordionMode {
    /// Only one panel may be open at a time.
    Single,
    /// Multiple panels may remain open together.
    Multiple,
}

/// Size presets for Accordion row spacing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccordionSize {
    /// Compact rows for dense settings pages.
    Small,
    /// Default row spacing.
    Medium,
    /// Larger rows for documentation and onboarding pages.
    Large,
}

/// Fluent native GPUI component for rendering Liora accordion.
pub struct Accordion {
    id: SharedString,
    items: Vec<AccordionItem>,
    open_items: HashSet<SharedString>,
    mode: AccordionMode,
    size: AccordionSize,
    bordered: bool,
}

impl Accordion {
    /// Creates an Accordion in single-open mode.
    pub fn new() -> Self {
        Self {
            id: unique_id("accordion"),
            items: Vec::new(),
            open_items: HashSet::new(),
            mode: AccordionMode::Single,
            size: AccordionSize::Medium,
            bordered: true,
        }
    }

    /// Assigns a stable element id used by GPUI state, hit testing, and automated interaction tests.
    pub fn id(mut self, id: impl Into<SharedString>) -> Self {
        self.id = id.into();
        self
    }

    /// Allows multiple panels to be open at the same time.
    pub fn multiple(mut self) -> Self {
        self.mode = AccordionMode::Multiple;
        self
    }

    /// Restores single-open behavior explicitly.
    pub fn single(mut self) -> Self {
        self.mode = AccordionMode::Single;
        if self.open_items.len() > 1 {
            let first = self.open_items.iter().next().cloned();
            self.open_items.clear();
            if let Some(first) = first {
                self.open_items.insert(first);
            }
        }
        self
    }

    /// Toggles the outer border and item separators.
    pub fn bordered(mut self, bordered: bool) -> Self {
        self.bordered = bordered;
        self
    }

    /// Applies the small sizing preset.
    pub fn small(mut self) -> Self {
        self.size = AccordionSize::Small;
        self
    }

    /// Applies the large sizing preset.
    pub fn large(mut self) -> Self {
        self.size = AccordionSize::Large;
        self
    }

    /// Marks an item as initially open.
    pub fn default_open(mut self, id: impl Into<SharedString>) -> Self {
        let id = id.into();
        if self.mode == AccordionMode::Single {
            self.open_items.clear();
        }
        self.open_items.insert(id);
        self
    }

    /// Adds an enabled item.
    pub fn item<F, E>(
        self,
        id: impl Into<SharedString>,
        title: impl Into<SharedString>,
        f: F,
    ) -> Self
    where
        F: Fn(&mut Window, &mut Context<Self>) -> E + 'static,
        E: IntoElement,
    {
        self.item_with_options(id, title, None::<SharedString>, false, f)
    }

    /// Adds a disabled item.
    pub fn disabled_item<F, E>(
        self,
        id: impl Into<SharedString>,
        title: impl Into<SharedString>,
        f: F,
    ) -> Self
    where
        F: Fn(&mut Window, &mut Context<Self>) -> E + 'static,
        E: IntoElement,
    {
        self.item_with_options(id, title, None::<SharedString>, true, f)
    }

    /// Adds an item with secondary description text.
    pub fn item_with_description<F, E>(
        self,
        id: impl Into<SharedString>,
        title: impl Into<SharedString>,
        description: impl Into<SharedString>,
        f: F,
    ) -> Self
    where
        F: Fn(&mut Window, &mut Context<Self>) -> E + 'static,
        E: IntoElement,
    {
        self.item_with_options(id, title, Some(description.into()), false, f)
    }

    fn item_with_options<F, E>(
        mut self,
        id: impl Into<SharedString>,
        title: impl Into<SharedString>,
        description: Option<SharedString>,
        disabled: bool,
        f: F,
    ) -> Self
    where
        F: Fn(&mut Window, &mut Context<Self>) -> E + 'static,
        E: IntoElement,
    {
        self.items.push(AccordionItem {
            id: id.into(),
            title: title.into(),
            description,
            disabled,
            content: Arc::new(move |window, cx| f(window, cx).into_any_element()),
        });
        self
    }

    fn metrics(&self) -> (Pixels, Pixels, Pixels, Pixels) {
        match self.size {
            AccordionSize::Small => (px(10.0), px(12.0), px(12.0), px(14.0)),
            AccordionSize::Medium => (px(13.0), px(16.0), px(14.0), px(16.0)),
            AccordionSize::Large => (px(16.0), px(20.0), px(16.0), px(18.0)),
        }
    }

    fn toggle(&mut self, id: SharedString, disabled: bool, cx: &mut Context<Self>) {
        if disabled {
            return;
        }
        if self.open_items.contains(&id) {
            self.open_items.remove(&id);
        } else {
            if self.mode == AccordionMode::Single {
                self.open_items.clear();
            }
            self.open_items.insert(id);
        }
        cx.notify();
    }
}

impl Render for Accordion {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = cx.global::<Config>().theme.clone();
        let (py_header, px_header, text_size, content_padding) = self.metrics();

        let mut root = div().flex().flex_col().w_full().bg(theme.neutral.card);
        if self.bordered {
            root = root
                .border_1()
                .border_color(theme.neutral.border)
                .rounded(px(theme.radius.md))
                .overflow_hidden();
        } else {
            root = root.gap_2();
        }

        root.children(self.items.iter().enumerate().map(|(index, item)| {
            let item_id = item.id.clone();
            let is_open = self.open_items.contains(&item_id);
            let is_last = index + 1 == self.items.len();
            let disabled = item.disabled;
            let title_color = if disabled {
                theme.neutral.text_3
            } else if is_open {
                theme.primary.base
            } else {
                theme.neutral.text_1
            };
            let row_bg = if is_open {
                theme.primary.base.opacity(0.06)
            } else {
                theme.neutral.card
            };

            let mut item_root = div().flex().flex_col().w_full();
            if !self.bordered {
                item_root = item_root
                    .border_1()
                    .border_color(theme.neutral.border)
                    .rounded(px(theme.radius.md))
                    .overflow_hidden();
            }

            item_root
                .child(
                    div()
                        .id(element_id(format!("{}-item-{}", self.id, item.id)))
                        .flex()
                        .flex_row()
                        .items_center()
                        .justify_between()
                        .gap_3()
                        .w_full()
                        .px(px_header)
                        .py(py_header)
                        .cursor_pointer()
                        .when(disabled, |s| s.cursor_not_allowed())
                        .bg(row_bg)
                        .text_color(title_color)
                        .hover(move |s| {
                            if disabled {
                                s.bg(row_bg)
                            } else {
                                s.bg(theme.neutral.hover)
                            }
                        })
                        .when(self.bordered && !is_last && !is_open, |s| {
                            s.border_b_1().border_color(theme.neutral.border)
                        })
                        .on_mouse_down(
                            MouseButton::Left,
                            cx.listener({
                                let item_id = item_id.clone();
                                move |this, _, _, cx| this.toggle(item_id.clone(), disabled, cx)
                            }),
                        )
                        .child(
                            div()
                                .flex()
                                .flex_col()
                                .gap_1()
                                .child(
                                    div()
                                        .text_size(text_size)
                                        .font_weight(gpui::FontWeight::BOLD)
                                        .child(item.title.clone()),
                                )
                                .when_some(item.description.clone(), |s, description| {
                                    s.child(
                                        div()
                                            .text_xs()
                                            .text_color(theme.neutral.text_3)
                                            .child(description),
                                    )
                                }),
                        )
                        .child(
                            Icon::new(if is_open {
                                IconName::ChevronDown
                            } else {
                                IconName::ChevronRight
                            })
                            .size(px(16.0))
                            .color(if disabled {
                                theme.neutral.text_3
                            } else {
                                theme.neutral.icon
                            }),
                        ),
                )
                .when(is_open, |s| {
                    s.child(pop_in(
                        element_id(format!("{}-panel-{}", self.id, item.id)),
                        div()
                            .px(content_padding)
                            .py(content_padding)
                            .bg(theme.neutral.card)
                            .when(self.bordered && !is_last, |s| {
                                s.border_b_1().border_color(theme.neutral.border)
                            })
                            .child((item.content)(window, cx)),
                    ))
                })
        }))
    }
}

impl Default for Accordion {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn accordion_builders_track_mode_size_and_open_state() {
        let accordion = Accordion::new()
            .id("settings")
            .multiple()
            .small()
            .bordered(false)
            .default_open("profile")
            .default_open("security")
            .item("profile", "Profile", |_, _| div())
            .disabled_item("billing", "Billing", |_, _| div());

        assert_eq!(accordion.id.as_ref(), "settings");
        assert_eq!(accordion.mode, AccordionMode::Multiple);
        assert_eq!(accordion.size, AccordionSize::Small);
        assert!(!accordion.bordered);
        assert!(accordion.open_items.contains("profile"));
        assert!(accordion.open_items.contains("security"));
        assert_eq!(accordion.items.len(), 2);
        assert!(accordion.items[1].disabled);
    }

    #[test]
    fn accordion_single_mode_keeps_only_one_default_open_item() {
        let accordion = Accordion::new()
            .default_open("first")
            .default_open("second")
            .large();

        assert_eq!(accordion.mode, AccordionMode::Single);
        assert_eq!(accordion.size, AccordionSize::Large);
        assert_eq!(accordion.open_items.len(), 1);
        assert!(accordion.open_items.contains("second"));
    }

    #[test]
    fn accordion_source_uses_motion_and_mouse_down_selection() {
        let source = include_str!("accordion.rs");
        assert!(source.contains("pop_in("));
        assert!(source.contains("on_mouse_down(MouseButton::Left"));
        assert!(source.contains("cursor_not_allowed"));
        assert!(source.contains("AccordionMode::Single"));
        assert!(source.contains("AccordionMode::Multiple"));
    }
}