azul-layout 0.0.12

Layout solver + font and image loader the Azul GUI framework
Documentation
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Chip / tag widget — a compact rounded "pill" holding a short label plus an
//! optional removable "x" affordance. A blend of
//! [`crate::widgets::badge::Badge`] (the coloured pill visual + [`ChipKind`]
//! colour variants) and [`crate::widgets::alert::Alert`] (the dismiss pattern:
//! a stateful close affordance that hides the widget on click).
//!
//! When made removable (`with_removable(true)` or `set_on_remove`), the chip
//! mirrors the stateful pattern of [`crate::widgets::alert::Alert`]: it carries a
//! [`ChipStateWrapper`] (`{ visible } + on_remove`) in a [`RefAny`] attached to
//! the "x" node. Clicking "x" flips `visible` to `false`, invokes the optional
//! user `on_remove`, and hides the whole chip by setting `display: none` on the
//! container via `set_css_property` (mirroring alert's live restyle). A
//! non-removable chip renders no "x" and carries no live callback — it is then
//! just a stateless styled pill (a near-clone of [`Badge`]).
//!
//! Key types: [`Chip`], [`ChipKind`], [`ChipState`], [`ChipOnRemove`],
//! [`ChipOnClick`].

use azul_core::{
    callbacks::{CoreCallbackData, Update},
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec, TabIndex},
    refany::RefAny,
};
use azul_css::dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec};
use azul_css::{
    props::{
        basic::{color::ColorU, font::{StyleFontFamily, StyleFontFamilyVec}, StyleFontSize},
        layout::{LayoutDisplay, LayoutFlexDirection, LayoutAlignItems, LayoutAlignSelf, LayoutFlexGrow, LayoutPaddingTop, LayoutPaddingBottom, LayoutPaddingLeft, LayoutPaddingRight, LayoutMarginLeft},
        property::{CssProperty, *},
        style::{StyleBackgroundContentVec, StyleBackgroundContent, StyleBorderTopLeftRadius, StyleBorderTopRightRadius, StyleBorderBottomLeftRadius, StyleBorderBottomRightRadius, StyleTextColor, StyleTextAlign, StyleUserSelect, StyleCursor},
    },
    impl_option_inner, AzString,
};

use crate::callbacks::{Callback, CallbackInfo};

static CHIP_CONTAINER_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str("__azul-native-chip"))];
static CHIP_LABEL_CLASS: &[IdOrClass] =
    &[Class(AzString::from_const_str("__azul-native-chip-label"))];
static CHIP_REMOVE_CLASS: &[IdOrClass] =
    &[Class(AzString::from_const_str("__azul-native-chip-remove"))];

const SYSTEM_UI_STR: AzString = AzString::from_const_str("system:ui");
const SYSTEM_UI_FAMILIES: &[StyleFontFamily] = &[StyleFontFamily::System(SYSTEM_UI_STR)];
const SYSTEM_UI_FAMILY: StyleFontFamilyVec =
    StyleFontFamilyVec::from_const_slice(SYSTEM_UI_FAMILIES);

/// Callback function type invoked when a removable chip's "x" is clicked.
pub type ChipOnRemoveCallbackType = extern "C" fn(RefAny, CallbackInfo, ChipState) -> Update;
impl_widget_callback!(
    ChipOnRemove,
    OptionChipOnRemove,
    ChipOnRemoveCallback,
    ChipOnRemoveCallbackType
);

azul_core::impl_managed_callback! {
    wrapper:        ChipOnRemoveCallback,
    info_ty:        CallbackInfo,
    return_ty:      Update,
    default_ret:    Update::DoNothing,
    invoker_static: CHIP_ON_REMOVE_INVOKER,
    invoker_ty:     AzChipOnRemoveCallbackInvoker,
    thunk_fn:       az_chip_on_remove_callback_thunk,
    setter_fn:      AzApp_setChipOnRemoveCallbackInvoker,
    from_handle_fn: AzChipOnRemoveCallback_createFromHostHandle,
    extra_args:     [ state: ChipState ],
}

/// Callback function type invoked when the chip's label area is clicked.
pub type ChipOnClickCallbackType = extern "C" fn(RefAny, CallbackInfo, ChipState) -> Update;
impl_widget_callback!(
    ChipOnClick,
    OptionChipOnClick,
    ChipOnClickCallback,
    ChipOnClickCallbackType
);

azul_core::impl_managed_callback! {
    wrapper:        ChipOnClickCallback,
    info_ty:        CallbackInfo,
    return_ty:      Update,
    default_ret:    Update::DoNothing,
    invoker_static: CHIP_ON_CLICK_INVOKER,
    invoker_ty:     AzChipOnClickCallbackInvoker,
    thunk_fn:       az_chip_on_click_callback_thunk,
    setter_fn:      AzApp_setChipOnClickCallbackInvoker,
    from_handle_fn: AzChipOnClickCallback_createFromHostHandle,
    extra_args:     [ state: ChipState ],
}

/// The semantic colour variant of a [`Chip`] (mirrors `badge::BadgeKind`).
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
#[repr(C)]
pub enum ChipKind {
    /// Neutral light-grey chip — the default.
    #[default]
    Default,
    /// Blue "primary" chip.
    Primary,
    /// Green "success" chip.
    Success,
    /// Red "danger" chip.
    Danger,
    /// Yellow "warning" chip (uses dark text).
    Warning,
    /// Cyan "info" chip (uses dark text).
    Info,
}

impl ChipKind {
    /// Returns the `(background, text)` colours for this chip kind.
    #[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot pixel/coord path or to avoid churning call sites for a perf-neutral change)
    const fn colors(&self) -> (ColorU, ColorU) {
        const WHITE: ColorU = ColorU { r: 255, g: 255, b: 255, a: 255 };
        const DARK: ColorU = ColorU { r: 33, g: 37, b: 41, a: 255 };
        match self {
            // The default chip is a light neutral pill with dark text (the
            // common "tag" look), unlike Badge's solid grey.
            Self::Default => (ColorU { r: 233, g: 236, b: 239, a: 255 }, DARK),
            Self::Primary => (ColorU { r: 13, g: 110, b: 253, a: 255 }, WHITE),
            Self::Success => (ColorU { r: 25, g: 135, b: 84, a: 255 }, WHITE),
            Self::Danger => (ColorU { r: 220, g: 53, b: 69, a: 255 }, WHITE),
            Self::Warning => (ColorU { r: 255, g: 193, b: 7, a: 255 }, DARK),
            Self::Info => (ColorU { r: 13, g: 202, b: 240, a: 255 }, DARK),
        }
    }

    /// CSS class name for this chip kind (mirrors `BadgeKind::class_name`).
    #[must_use] pub const fn class_name(&self) -> &'static str {
        match self {
            Self::Default => "__azul-chip-default",
            Self::Primary => "__azul-chip-primary",
            Self::Success => "__azul-chip-success",
            Self::Danger => "__azul-chip-danger",
            Self::Warning => "__azul-chip-warning",
            Self::Info => "__azul-chip-info",
        }
    }
}

/// A compact rounded pill holding a label plus an optional removable "x".
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct Chip {
    /// Runtime state (`visible`) plus the optional remove callback.
    pub chip_state: ChipStateWrapper,
    /// The text shown inside the pill.
    pub label: AzString,
    /// The colour variant.
    pub kind: ChipKind,
    /// Whether to render the "x" remove affordance (hides the chip on click).
    pub removable: bool,
    /// The computed inline style for the pill container.
    pub container_style: CssPropertyWithConditionsVec,
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct ChipStateWrapper {
    /// Whether the chip is currently visible.
    pub inner: ChipState,
    /// Optional: function to call when the chip is removed.
    pub on_remove: OptionChipOnRemove,
    /// Optional: function to call when the chip's label area is clicked.
    pub on_click: OptionChipOnClick,
}

/// The visible/hidden state of a [`Chip`].
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct ChipState {
    /// `true` (default) = shown, `false` = removed/hidden.
    pub visible: bool,
}

impl Default for ChipState {
    fn default() -> Self {
        Self { visible: true }
    }
}

/// Builds the pill container style for a given [`ChipKind`]. The colours are the
/// only kind-dependent properties, so the style is built at runtime per the
/// recipe's "runtime vec when param-dependent" path (see `badge::build_badge_style`).
fn build_chip_style(kind: ChipKind) -> CssPropertyWithConditionsVec {
    let (bg, text) = kind.colors();
    let bg_vec =
        StyleBackgroundContentVec::from_vec(alloc::vec![StyleBackgroundContent::Color(bg)]);
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
            LayoutFlexDirection::Row,
        )),
        CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
        // Hug the content rather than stretch across a flex parent's cross axis.
        CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Start)),
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
            0,
        ))),
        // padding: 4px 10px
        CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
            4,
        ))),
        CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
            LayoutPaddingBottom::const_px(4),
        )),
        CssPropertyWithConditions::simple(CssProperty::const_padding_left(
            LayoutPaddingLeft::const_px(10),
        )),
        CssPropertyWithConditions::simple(CssProperty::const_padding_right(
            LayoutPaddingRight::const_px(10),
        )),
        // border-radius: 12px (pill)
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
            StyleBorderTopLeftRadius::const_px(12),
        )),
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
            StyleBorderTopRightRadius::const_px(12),
        )),
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
            StyleBorderBottomLeftRadius::const_px(12),
        )),
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
            StyleBorderBottomRightRadius::const_px(12),
        )),
        CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(13))),
        CssPropertyWithConditions::simple(CssProperty::const_font_family(SYSTEM_UI_FAMILY)),
        // Text colour is inherited by the label + "x" children.
        CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
            inner: text,
        })),
        CssPropertyWithConditions::simple(CssProperty::const_background_content(bg_vec)),
    ])
}

/// Label style: left-aligned, hugs its content.
static CHIP_LABEL_STYLE: &[CssPropertyWithConditions] = &[
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Left)),
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
];

/// "x" remove-affordance style: a small pointer-cursor box on the right.
static CHIP_REMOVE_STYLE: &[CssPropertyWithConditions] = &[
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(14))),
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
    CssPropertyWithConditions::simple(CssProperty::const_margin_left(LayoutMarginLeft::const_px(
        6,
    ))),
];

impl Chip {
    /// Creates a new chip with the given label and the default (light-grey) kind.
    #[inline]
    #[must_use] pub fn create(label: AzString) -> Self {
        Self::with_kind(label, ChipKind::Default)
    }

    /// Creates a new chip with the given label and colour variant.
    #[inline]
    #[must_use] pub fn with_kind(label: AzString, kind: ChipKind) -> Self {
        Self {
            chip_state: ChipStateWrapper::default(),
            label,
            kind,
            removable: false,
            container_style: build_chip_style(kind),
        }
    }

    /// Sets the colour variant, recomputing the container style.
    #[inline]
    pub fn set_kind(&mut self, kind: ChipKind) {
        self.kind = kind;
        self.container_style = build_chip_style(kind);
    }

    /// Builder-style setter for the colour variant.
    #[inline]
    #[must_use] pub fn with_chip_kind(mut self, kind: ChipKind) -> Self {
        self.set_kind(kind);
        self
    }

    /// Sets whether the chip shows a "x" remove affordance.
    #[inline]
    pub const fn set_removable(&mut self, removable: bool) {
        self.removable = removable;
    }

    /// Builder-style setter for the removable flag.
    #[inline]
    #[must_use] pub const fn with_removable(mut self, removable: bool) -> Self {
        self.set_removable(removable);
        self
    }

    /// Sets the remove callback. Implies `removable = true` so the "x" is rendered.
    #[inline]
    pub fn set_on_remove<C: Into<ChipOnRemoveCallback>>(&mut self, data: RefAny, on_remove: C) {
        self.removable = true;
        self.chip_state.on_remove = Some(ChipOnRemove {
            callback: on_remove.into(),
            refany: data,
        })
        .into();
    }

    /// Builder-style setter for the remove callback (implies removable).
    #[inline]
    #[must_use] pub fn with_on_remove<C: Into<ChipOnRemoveCallback>>(
        mut self,
        data: RefAny,
        on_remove: C,
    ) -> Self {
        self.set_on_remove(data, on_remove);
        self
    }

    /// Sets the click callback, invoked when the chip's label area is clicked.
    #[inline]
    pub fn set_on_click<C: Into<ChipOnClickCallback>>(&mut self, data: RefAny, on_click: C) {
        self.chip_state.on_click = Some(ChipOnClick {
            callback: on_click.into(),
            refany: data,
        })
        .into();
    }

    /// Builder-style setter for the click callback.
    #[inline]
    #[must_use] pub fn with_on_click<C: Into<ChipOnClickCallback>>(
        mut self,
        data: RefAny,
        on_click: C,
    ) -> Self {
        self.set_on_click(data, on_click);
        self
    }

    /// Replaces `self` with an empty default chip and returns the original.
    #[inline]
    #[must_use] pub fn swap_with_default(&mut self) -> Self {
        let mut s = Self::create(AzString::from_const_str(""));
        core::mem::swap(&mut s, self);
        s
    }

    /// Converts this chip into a DOM subtree with the `__azul-native-chip` class.
    #[inline]
    #[must_use] pub fn dom(self) -> Dom {
        use azul_core::{
            callbacks::CoreCallback,
            dom::{EventFilter, HoverEventFilter},
            refany::OptionRefAny,
        };

        let has_on_click = matches!(self.chip_state.on_click, OptionChipOnClick::Some(_));

        // The remove ("x") and the label-click callbacks share the same state
        // RefAny so both handlers observe the same ChipState.
        let state_ref = RefAny::new(self.chip_state);

        let mut label = Dom::create_text(self.label)
            .with_ids_and_classes(IdOrClassVec::from_const_slice(CHIP_LABEL_CLASS))
            .with_css_props(CssPropertyWithConditionsVec::from_const_slice(CHIP_LABEL_STYLE));

        // The click callback is attached to the LABEL node rather than the
        // pill container: a container-level MouseUp would also fire when the
        // remove "x" (a child of the container) is clicked, double-firing
        // alongside on_remove. Attaching per-child sidesteps that (same
        // wiring as list_view's row/column callbacks); clicks on the pill's
        // padding therefore do not trigger on_click.
        if has_on_click {
            label = label.with_tab_index(TabIndex::Auto).with_callbacks(
                alloc::vec![CoreCallbackData {
                    event: EventFilter::Hover(HoverEventFilter::MouseUp),
                    callback: CoreCallback {
                        cb: default_on_chip_click as usize,
                        ctx: OptionRefAny::None,
                    },
                    refany: state_ref.clone(),
                }]
                .into(),
            );
        }

        let mut children = alloc::vec![label];

        if self.removable {
            let remove = Dom::create_text(AzString::from_const_str("\u{00D7}"))
                .with_ids_and_classes(IdOrClassVec::from_const_slice(CHIP_REMOVE_CLASS))
                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(CHIP_REMOVE_STYLE))
                .with_tab_index(TabIndex::Auto)
                .with_callbacks(
                    alloc::vec![CoreCallbackData {
                        event: EventFilter::Hover(HoverEventFilter::MouseUp),
                        callback: CoreCallback {
                            cb: default_on_chip_remove as usize,
                            ctx: OptionRefAny::None,
                        },
                        refany: state_ref,
                    }]
                    .into(),
                );
            children.push(remove);
        }

        Dom::create_div()
            .with_ids_and_classes(IdOrClassVec::from_const_slice(CHIP_CONTAINER_CLASS))
            .with_css_props(self.container_style)
            .with_children(children.into())
    }
}

impl Default for Chip {
    fn default() -> Self {
        Self::create(AzString::from_const_str(""))
    }
}

/// "x" click handler. The hit node is the "x" (the callback-bearing node, per
/// `currentTarget` semantics — see `radio_group`); its parent is the chip
/// container. Flips `visible` to `false`, invokes the optional user callback,
/// then hides the whole chip via `display: none`.
extern "C" fn default_on_chip_remove(mut data: RefAny, mut info: CallbackInfo) -> Update {
    let remove_node = info.get_hit_node();
    let Some(container) = info.get_parent(remove_node) else {
        return Update::DoNothing;
    };

    let result = {
        let Some(mut chip) = data.downcast_mut::<ChipStateWrapper>() else {
            return Update::DoNothing;
        };
        chip.inner.visible = false;
        let inner = chip.inner;
        let chip = &mut *chip;
        match chip.on_remove.as_mut() {
            Some(ChipOnRemove { callback, refany }) => (callback.cb)(refany.clone(), info, inner),
            None => Update::DoNothing,
        }
    };

    // TODO2: hides the chip by toggling `display: none` via set_css_property.
    // This follows the proven live-restyle pattern of alert/check_box/radio_group
    // (which toggle display/opacity/background); the display:none relayout itself
    // is not GUI-verified in this build.
    info.set_css_property(container, CssProperty::const_display(LayoutDisplay::None));

    result
}

/// Label click handler. Invokes the optional user `on_click` with the current
/// [`ChipState`] (mirrors `default_on_chip_remove`, minus the state flip/hide).
extern "C" fn default_on_chip_click(mut data: RefAny, info: CallbackInfo) -> Update {
    let Some(mut chip) = data.downcast_mut::<ChipStateWrapper>() else {
        return Update::DoNothing;
    };
    let inner = chip.inner;
    let chip = &mut *chip;
    match chip.on_click.as_mut() {
        Some(ChipOnClick { callback, refany }) => (callback.cb)(refany.clone(), info, inner),
        None => Update::DoNothing,
    }
}

impl From<Chip> for Dom {
    fn from(c: Chip) -> Self {
        c.dom()
    }
}