fission-core 0.3.0

Core runtime, state, actions, effects, resources, input, and UI model for Fission
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use crate::lowering::{LoweringContext, NodeBuilder};
use crate::ui::traits::Lower;
use crate::ui::Node;
use crate::{ActionEnvelope, Env, InteractionStateMap};
use fission_ir::{
    op::{BoxShadow, Color as IrColor, Fill, LayoutOp, Op, PaintOp, Stroke},
    ActionEntry, ActionSet, NodeId, Role, Semantics,
};
use fission_theme::{ButtonHierarchy, ComponentSize, ComponentState};
use serde::{Deserialize, Serialize};

/// Visual style variant for a [`Button`].
///
/// - `Filled` -- solid background with the primary colour (default).
/// - `Outline` -- transparent background with a border stroke.
/// - `Ghost` -- no background or border; just text/icon.
///
/// # Example
///
/// ```rust,ignore
/// Button {
///     variant: ButtonVariant::Outline,
///     child: Some(Box::new(Text::new("Cancel").into_node())),
///     ..Default::default()
/// }
/// ```
#[derive(Debug, Default, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ButtonVariant {
    /// Solid primary-colour background.
    #[default]
    Filled,
    /// Transparent background with a border.
    Outline,
    /// No background, no border.
    Ghost,
    /// DSP primary hierarchy.
    Primary,
    /// DSP secondary colour hierarchy.
    SecondaryColor,
    /// DSP secondary gray hierarchy.
    SecondaryGray,
    /// DSP tertiary colour hierarchy.
    TertiaryColor,
    /// DSP tertiary gray hierarchy.
    TertiaryGray,
    /// DSP link colour hierarchy.
    LinkColor,
    /// DSP link gray hierarchy.
    LinkGray,
    /// DSP destructive hierarchy.
    Destructive,
}

impl ButtonVariant {
    fn hierarchy(self) -> ButtonHierarchy {
        match self {
            ButtonVariant::Filled | ButtonVariant::Primary => ButtonHierarchy::Primary,
            ButtonVariant::Outline | ButtonVariant::SecondaryGray => ButtonHierarchy::SecondaryGray,
            ButtonVariant::Ghost | ButtonVariant::TertiaryGray => ButtonHierarchy::TertiaryGray,
            ButtonVariant::SecondaryColor => ButtonHierarchy::SecondaryColor,
            ButtonVariant::TertiaryColor => ButtonHierarchy::TertiaryColor,
            ButtonVariant::LinkColor => ButtonHierarchy::LinkColor,
            ButtonVariant::LinkGray => ButtonHierarchy::LinkGray,
            ButtonVariant::Destructive => ButtonHierarchy::Destructive,
        }
    }
}

/// Horizontal alignment of a [`Button`]'s child content.
///
/// Defaults to `Center`.
#[derive(Debug, Default, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ButtonContentAlign {
    /// Center the child horizontally and vertically (default).
    #[default]
    Center,
    /// Align the child to the leading edge.
    Start,
    /// Align the child to the trailing edge.
    End,
}

/// A pressable button widget with built-in theming, hover/press states, and
/// focus ring.
///
/// Buttons come in three visual [`ButtonVariant`]s (Filled, Outline, Ghost)
/// and support flexible content alignment via [`ButtonContentAlign`].
///
/// # Example
///
/// ```rust,ignore
/// let on_press = ctx.bind(Submit, reduce_with!(handle_submit));
///
/// Button {
///     child: Some(Box::new(Text::new("Submit").into_node())),
///     on_press: Some(on_press),
///     variant: ButtonVariant::Filled,
///     content_align: ButtonContentAlign::Center,
///     ..Default::default()
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Button {
    /// Explicit node identity (auto-generated if `None`).
    pub id: Option<NodeId>,
    /// The button's content widget (typically [`Text`] or [`Icon`]).
    pub child: Option<Box<Node>>,
    /// Action dispatched when the button is pressed.
    pub on_press: Option<ActionEnvelope>,
    /// Custom semantics (overrides the default button semantics).
    pub semantics: Option<Semantics>,
    /// Fixed width in layout points.
    pub width: Option<f32>,
    /// Fixed height in layout points.
    pub height: Option<f32>,
    /// Minimum width constraint.
    pub min_width: Option<f32>,
    /// Maximum width constraint.
    pub max_width: Option<f32>,
    /// Flex grow factor for parent flex layouts.
    pub flex_grow: f32,
    /// Flex shrink factor for parent flex layouts.
    pub flex_shrink: f32,
    /// Custom padding `[left, right, top, bottom]` (overrides theme defaults).
    pub padding: Option<[f32; 4]>,
    /// Style overrides (reserved for future use).
    pub style: Option<ButtonStyleOverride>,
    /// Visual variant (Filled, Outline, or Ghost).
    pub variant: ButtonVariant,
    /// Design-system size slot.
    #[serde(default)]
    pub size: ComponentSize,
    /// Optional fill override for the button background.
    pub background_fill: Option<Fill>,
    /// Optional text color override for direct `Text` children.
    pub text_color: Option<IrColor>,
    /// Horizontal alignment of the child content.
    #[serde(default)]
    pub content_align: ButtonContentAlign,
    /// When `true`, the button is greyed out and its `on_press` action is not
    /// attached.
    pub disabled: bool,
}

impl Button {
    pub fn background_fill(mut self, fill: Fill) -> Self {
        self.background_fill = Some(fill);
        self
    }

    pub fn text_color(mut self, color: IrColor) -> Self {
        self.text_color = Some(color);
        self
    }

    pub fn flex_grow(mut self, grow: f32) -> Self {
        self.flex_grow = grow;
        self
    }

    pub fn flex_shrink(mut self, shrink: f32) -> Self {
        self.flex_shrink = shrink;
        self
    }

    pub fn min_width(mut self, width: f32) -> Self {
        self.min_width = Some(width);
        self
    }

    pub fn max_width(mut self, width: f32) -> Self {
        self.max_width = Some(width);
        self
    }

    pub fn into_node(self) -> crate::ui::Node {
        crate::ui::Node::Button(self)
    }
}

impl Default for Button {
    fn default() -> Self {
        Self {
            id: None,
            child: None,
            on_press: None,
            semantics: None,
            width: None,
            height: None,
            min_width: None,
            max_width: None,
            flex_grow: 0.0,
            flex_shrink: 1.0,
            padding: None,
            style: None,
            variant: ButtonVariant::Filled,
            size: ComponentSize::Md,
            background_fill: None,
            text_color: None,
            content_align: ButtonContentAlign::Center,
            disabled: false,
        }
    }
}

#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct ButtonStyleOverride {}

struct ButtonStyleResolved {
    background_fill: Option<Fill>,
    text_color: IrColor,
    padding_horizontal: f32,
    padding_vertical: f32,
    height: f32,
    corner_radius: f32,
    shadow: Option<BoxShadow>,
    shadows: Vec<BoxShadow>,
    stroke: Option<Stroke>,
    font_size: f32,
    font_weight: u16,
    line_height: Option<f32>,
}

impl Button {
    fn resolve_style(
        &self,
        env: &Env,
        interaction: &InteractionStateMap,
        self_id: NodeId,
    ) -> ButtonStyleResolved {
        let default_style = &env.theme.components.button;
        let tokens = &env.theme.tokens.colors;

        let is_hovered = interaction.is_hovered(self_id) && !self.disabled;
        let is_pressed = interaction.is_pressed(self_id) && !self.disabled;
        let is_focused = interaction.is_focused(self_id) && !self.disabled;
        let component_state = if self.disabled {
            ComponentState::Disabled
        } else if is_pressed {
            ComponentState::Active
        } else if is_focused {
            ComponentState::Focus
        } else if is_hovered {
            ComponentState::Hover
        } else {
            ComponentState::Default
        };
        let component_style =
            default_style.resolve(self.variant.hierarchy(), self.size, component_state);

        let stroke = component_style
            .border
            .clone()
            .or_else(|| component_style.inset_border())
            .map(|border| Stroke {
                fill: border.fill,
                width: border.width,
                dash_array: None,
                line_cap: fission_ir::op::LineCap::Butt,
                line_join: fission_ir::op::LineJoin::Miter,
            })
            .or_else(|| {
                if is_focused {
                    default_style.focus_stroke.clone()
                } else {
                    None
                }
            });
        let shadows = component_style.outer_shadows();
        let shadow = shadows.first().copied().or_else(|| {
            if matches!(self.variant, ButtonVariant::Filled | ButtonVariant::Primary) {
                if is_pressed {
                    default_style.elevation_pressed
                } else if is_hovered {
                    default_style.elevation_hover
                } else {
                    default_style.elevation_rest
                }
            } else {
                None
            }
        });

        ButtonStyleResolved {
            background_fill: self
                .background_fill
                .clone()
                .or_else(|| component_style.background.clone()),
            text_color: self
                .text_color
                .unwrap_or(component_style.text_color.unwrap_or(tokens.primary)),
            padding_horizontal: component_style
                .padding_x
                .unwrap_or(default_style.padding_horizontal),
            padding_vertical: component_style
                .padding_y
                .unwrap_or(default_style.padding_vertical),
            height: component_style.height.unwrap_or(default_style.height),
            corner_radius: component_style.radius.unwrap_or(default_style.radius),
            shadow,
            shadows,
            stroke,
            font_size: component_style.font_size.unwrap_or(default_style.text_size),
            font_weight: component_style
                .font_weight
                .unwrap_or(default_style.font_weight),
            line_height: component_style.line_height,
        }
    }

    fn should_attach_semantics(&self) -> bool {
        self.semantics.is_some() || self.on_press.is_some()
    }

    fn build_semantics(&self) -> Option<Semantics> {
        if !self.should_attach_semantics() {
            return None;
        }

        let mut semantics = self
            .semantics
            .clone()
            .unwrap_or_else(default_button_semantics);

        semantics.disabled = self.disabled;

        if let Some(action_envelope) = &self.on_press {
            if !self.disabled {
                semantics.actions.entries.push(ActionEntry {
                    trigger: fission_ir::semantics::ActionTrigger::Default,
                    action_id: action_envelope.id.as_u128(),
                    payload_data: Some(action_envelope.payload.clone()),
                });
            }
        }

        Some(semantics)
    }
}

impl Lower for Button {
    fn lower(&self, cx: &mut LoweringContext) -> NodeId {
        let semantics_op = self.build_semantics();
        let outermost_id = self.id.unwrap_or_else(|| cx.next_node_id());

        let (layout_node_id, final_id) = if let Some(_) = semantics_op {
            (cx.next_node_id(), outermost_id)
        } else {
            (outermost_id, outermost_id)
        };

        let resolved_style = self.resolve_style(cx.env, &cx.runtime_state.interaction, final_id);

        cx.push_scope(layout_node_id);

        let mut button_builder = NodeBuilder::new(
            layout_node_id,
            Op::Layout(LayoutOp::Box {
                width: self.width,
                height: self.height,
                min_width: self.min_width,
                max_width: self.max_width,
                min_height: if self.height.is_some() {
                    None
                } else {
                    Some(resolved_style.height)
                },
                max_height: None,
                padding: self.padding.unwrap_or([
                    resolved_style.padding_horizontal,
                    resolved_style.padding_horizontal,
                    resolved_style.padding_vertical,
                    resolved_style.padding_vertical,
                ]),
                flex_grow: self.flex_grow,
                flex_shrink: self.flex_shrink,
                aspect_ratio: None,
            }),
        );

        for shadow in &resolved_style.shadows {
            let shadow_id = NodeBuilder::new(
                cx.next_node_id(),
                Op::Paint(PaintOp::DrawRect {
                    fill: None,
                    stroke: None,
                    corner_radius: resolved_style.corner_radius,
                    shadow: Some(*shadow),
                }),
            )
            .build(cx);
            button_builder.add_child(shadow_id);
        }

        let background_id = NodeBuilder::new(
            cx.next_node_id(),
            Op::Paint(PaintOp::DrawRect {
                fill: resolved_style.background_fill,
                stroke: resolved_style.stroke,
                corner_radius: resolved_style.corner_radius,
                shadow: if resolved_style.shadows.is_empty() {
                    resolved_style.shadow
                } else {
                    None
                },
            }),
        )
        .build(cx);
        button_builder.add_child(background_id);

        if let Some(child_widget) = &self.child {
            let child_id = if let Node::Text(mut text_widget) = *child_widget.clone() {
                text_widget.color = Some(resolved_style.text_color);
                text_widget.font_size = Some(resolved_style.font_size);
                text_widget.font_weight = Some(resolved_style.font_weight);
                text_widget.line_height = resolved_style.line_height;
                text_widget.lower(cx)
            } else {
                child_widget.lower(cx)
            };
            let aligned_id = match self.content_align {
                ButtonContentAlign::Center => {
                    // Center the content within the button's box (vertically + horizontally).
                    let mut align_builder =
                        NodeBuilder::new(cx.next_node_id(), Op::Layout(LayoutOp::Align));
                    align_builder.add_child(child_id);
                    align_builder.build(cx)
                }
                ButtonContentAlign::Start | ButtonContentAlign::End => {
                    let justify = match self.content_align {
                        ButtonContentAlign::Start => fission_ir::op::JustifyContent::Start,
                        ButtonContentAlign::End => fission_ir::op::JustifyContent::End,
                        ButtonContentAlign::Center => fission_ir::op::JustifyContent::Center,
                    };
                    let mut flex_builder = NodeBuilder::new(
                        cx.next_node_id(),
                        Op::Layout(LayoutOp::Flex {
                            direction: fission_ir::FlexDirection::Row,
                            wrap: fission_ir::FlexWrap::NoWrap,
                            flex_grow: 1.0,
                            flex_shrink: 0.0,
                            padding: [0.0; 4],
                            gap: None,
                            align_items: fission_ir::op::AlignItems::Center,
                            justify_content: justify,
                        }),
                    );
                    flex_builder.add_child(child_id);
                    flex_builder.build(cx)
                }
            };
            button_builder.add_child(aligned_id);
        }

        let button_node_id = button_builder.build(cx);

        if let Some(op) = semantics_op {
            let mut semantics_builder = NodeBuilder::new(final_id, Op::Semantics(op));
            semantics_builder.add_child(button_node_id);
            let res_id = semantics_builder.build(cx);
            cx.pop_scope();
            return res_id;
        }

        cx.pop_scope();
        button_node_id
    }
}

fn default_button_semantics() -> Semantics {
    Semantics {
        role: Role::Button,
        label: None,
        identifier: None,
        value: None,
        actions: ActionSet::default(),
        action_scope_id: None,
        focusable: true,
        multiline: false,
        masked: false,
        input_mask: None,
        ime_preedit_range: None,
        checked: None,
        disabled: false,
        read_only: false,
        autofocus: false,
        draggable: false,
        scrollable_x: false,
        scrollable_y: false,
        min_value: None,
        max_value: None,
        current_value: None,
        is_focus_scope: false,
        is_focus_barrier: false,
        drag_payload: None,
        hero_tag: None,
        focus_index: None,
        text_input_type: fission_ir::semantics::TextInputType::Text,
        text_input_action: fission_ir::semantics::TextInputAction::Done,
        text_capitalization: fission_ir::semantics::TextCapitalization::None,
        max_length: None,
        max_length_enforcement: fission_ir::semantics::MaxLengthEnforcement::Enforced,
        input_formatters: Vec::new(),
        autocorrect: true,
        enable_suggestions: true,
        spell_check: true,
        smart_dashes: true,
        smart_quotes: true,
        autofill_hints: Vec::new(),
        scroll_padding: None,
        capture_tab: false,
        auto_indent: false,
    }
}