fission-ir 0.3.0

Intermediate representation and display-list primitives for Fission rendering
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
//! Accessibility and interaction semantics.
//!
//! The [`Semantics`] struct describes what a node *means* to assistive technology
//! and to the event system. It carries a [`Role`] (button, text input, slider, ...),
//! an optional human-readable label, a set of [`ActionEntry`]s that map input
//! triggers to framework actions, and flags for focus, drag-and-drop, scrollability,
//! and more.
//!
//! Semantics nodes appear in the IR as `Op::Semantics(semantics)`.

use serde::{Deserialize, Serialize};

/// The accessibility role of a node.
///
/// Roles tell screen readers and other assistive technology what kind of control a
/// node represents. Choose the most specific role that applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Role {
    /// A clickable button that triggers an action.
    Button,
    /// A read-only text label.
    Text,
    /// An editable text field (single or multi-line).
    TextInput,
    /// A raster or vector image.
    Image,
    /// A toggle that is either checked or unchecked.
    Checkbox,
    /// A toggle switch (on/off).
    Switch,
    /// A modal or non-modal dialog overlay.
    Dialog,
    /// A continuous range input (e.g., volume control).
    Slider,
    /// A generic form input that does not fit the other roles.
    Input,
    /// A scrollable list container.
    List,
    /// An individual item inside a [`List`](Role::List).
    ListItem,
    /// A node with no specific semantic role. The default.
    Generic,
}

/// What user interaction triggers an action.
///
/// Each [`ActionEntry`] pairs an `ActionTrigger` with an action ID so the event
/// system knows which callback to invoke for a given input gesture.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ActionTrigger {
    /// Primary activation: tap, click, or Enter key.
    Default,
    /// The user began dragging this node.
    DragStart,
    /// The drag position changed (fires continuously).
    DragUpdate,
    /// The user released the drag.
    DragEnd,
    /// The pointer entered the node's hit area.
    HoverEnter,
    /// The pointer left the node's hit area.
    HoverExit,
    /// A semantic cursor request applied while the pointer hovers this node.
    ///
    /// This is metadata, not a dispatched reducer action.
    HoverCursor,
    /// The node received keyboard focus.
    Focus,
    /// The node lost keyboard focus.
    Blur,
    /// A pointer-down happened outside the active text field.
    TapOutside,
    /// The node's value changed (sliders, text inputs, etc.).
    Change,
    /// Text editing was explicitly completed by the current input method.
    EditingComplete,
    /// The user submitted a text field.
    Submit,
    /// The caret or selection anchor position changed in a text field.
    CursorChange,
    /// A dragged payload was dropped onto this node.
    Drop,
    /// A drag entered this node's hit area (for drop targets).
    DragEnter,
    /// A drag left this node's hit area (for drop targets).
    DragLeave,
    /// Right-click or secondary mouse button.
    SecondaryClick,
}

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

/// Semantic cursor requests that shells map onto platform cursor icons.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum MouseCursor {
    #[default]
    Default = 0,
    Pointer = 1,
    Text = 2,
    Crosshair = 3,
    Move = 4,
    NotAllowed = 5,
    Grab = 6,
    Grabbing = 7,
    Wait = 8,
    Help = 9,
    VerticalText = 10,
}

impl MouseCursor {
    pub fn from_repr(value: u128) -> Option<Self> {
        match value {
            0 => Some(Self::Default),
            1 => Some(Self::Pointer),
            2 => Some(Self::Text),
            3 => Some(Self::Crosshair),
            4 => Some(Self::Move),
            5 => Some(Self::NotAllowed),
            6 => Some(Self::Grab),
            7 => Some(Self::Grabbing),
            8 => Some(Self::Wait),
            9 => Some(Self::Help),
            10 => Some(Self::VerticalText),
            _ => None,
        }
    }
}

/// Preferred software keyboard / input modality for a text field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum TextInputType {
    #[default]
    Text,
    Multiline,
    Number,
    EmailAddress,
    Url,
    Phone,
    Name,
}

/// Preferred action for the return/submit key on software keyboards.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum TextInputAction {
    #[default]
    Done,
    Go,
    Search,
    Send,
    Next,
    Previous,
    Continue,
    Join,
    Route,
    EmergencyCall,
    Newline,
}

/// Automatic capitalization strategy for inserted text.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum TextCapitalization {
    #[default]
    None,
    Characters,
    Words,
    Sentences,
}

/// Whether the framework should enforce `max_length` during editing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum MaxLengthEnforcement {
    None,
    #[default]
    Enforced,
}

/// Structured formatter primitives applied to inserted text.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum InputFormatter {
    DigitsOnly,
    AsciiOnly,
    Lowercase,
    Uppercase,
    TrimWhitespace,
    SingleLine,
}

/// A single action binding: a trigger, an action ID, and optional payload.
///
/// When the event system detects the input described by `trigger`, it dispatches
/// the action identified by `action_id`. If the action carries data (e.g., drag
/// coordinates), `payload_data` holds the serialized payload.
///
/// # Example
///
/// ```rust
/// use fission_ir::semantics::{ActionEntry, ActionTrigger};
///
/// let entry = ActionEntry {
///     trigger: ActionTrigger::Default,
///     action_id: 42,
///     payload_data: None,
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ActionEntry {
    /// Which input gesture triggers this action.
    pub trigger: ActionTrigger,
    /// The raw 128-bit action ID dispatched to the widget's action handler.
    pub action_id: u128,
    /// Optional serialized payload. `None` for actions with no data.
    pub payload_data: Option<Vec<u8>>,
}

impl ActionEntry {
    /// Creates a non-dispatched cursor request consumed by hover handling.
    pub fn hover_cursor(cursor: MouseCursor) -> Self {
        Self {
            trigger: ActionTrigger::HoverCursor,
            action_id: cursor as u128,
            payload_data: None,
        }
    }

    /// Returns the semantic cursor encoded by this entry, if any.
    pub fn as_hover_cursor(&self) -> Option<MouseCursor> {
        (self.trigger == ActionTrigger::HoverCursor)
            .then(|| MouseCursor::from_repr(self.action_id))
            .flatten()
    }
}

/// Accessibility and interaction metadata for a node.
///
/// `Semantics` is the IR's way of describing *what a node means* rather than how it
/// looks or where it is positioned. It is consumed by:
///
/// * Assistive technology (screen readers, switch control) via the accessibility tree.
/// * The event/focus system, which uses `focusable`, `actions`, and `disabled` to
///   route input.
/// * The drag-and-drop subsystem, which reads `draggable` and `drag_payload`.
///
/// Most fields default to "inert" values (see [`Default`] impl), so you only need to
/// set the fields that matter for a given widget.
///
/// # Example
///
/// ```rust
/// use fission_ir::Semantics;
/// use fission_ir::semantics::Role;
///
/// let sem = Semantics {
///     role: Role::Button,
///     label: Some("Submit".into()),
///     focusable: true,
///     ..Semantics::default()
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Semantics {
    /// The accessibility role. Defaults to [`Role::Generic`].
    pub role: Role,
    /// A human-readable label for assistive technology (e.g., "Close" for a button).
    pub label: Option<String>,
    /// Stable semantic identifier for tooling and automation.
    pub identifier: Option<String>,
    /// The current value as a string (e.g., the text in an input field).
    pub value: Option<String>,
    /// The set of actions this node responds to.
    pub actions: ActionSet,
    /// Optional raw action dispatch scope inherited by descendant actions.
    #[serde(default)]
    pub action_scope_id: Option<u128>,
    /// Whether this node can receive keyboard focus.
    pub focusable: bool,
    /// Whether this text input supports multiple lines.
    pub multiline: bool,
    /// Whether the value should be obscured (password fields).
    pub masked: bool,
    /// An optional input mask that restricts which characters are accepted.
    pub input_mask: Option<InputMask>,
    /// The byte range of IME pre-edit (composition) text, if any.
    pub ime_preedit_range: Option<(usize, usize)>,
    /// For checkboxes and switches: `Some(true)` = checked, `Some(false)` = unchecked,
    /// `None` = not a toggle.
    pub checked: Option<bool>,
    /// Whether the node is disabled (grayed out, non-interactive).
    pub disabled: bool,
    /// Whether the node can be focused and selected but not edited.
    pub read_only: bool,
    /// Whether this node should receive focus automatically when mounted.
    pub autofocus: bool,
    /// Whether this node can be dragged.
    pub draggable: bool,
    /// Whether the node scrolls horizontally.
    pub scrollable_x: bool,
    /// Whether the node scrolls vertically.
    pub scrollable_y: bool,
    /// Minimum value for range inputs (sliders).
    pub min_value: Option<f32>,
    /// Maximum value for range inputs (sliders).
    pub max_value: Option<f32>,
    /// Current numeric value for range inputs (sliders).
    pub current_value: Option<f32>,
    /// When `true`, this node creates a new focus scope (like a dialog or panel).
    pub is_focus_scope: bool,
    /// When `true`, Tab traversal does not leave this subtree.
    pub is_focus_barrier: bool,
    /// Serialized payload attached to a drag operation.
    pub drag_payload: Option<Vec<u8>>,
    /// An identifier for hero/shared-element transitions.
    pub hero_tag: Option<String>,
    /// Explicit tab order index. Lower values receive focus first. `None` means
    /// the node follows document order.
    pub focus_index: Option<i32>,
    /// Preferred keyboard/input modality for text entry.
    pub text_input_type: TextInputType,
    /// Preferred submit/return key action.
    pub text_input_action: TextInputAction,
    /// Automatic capitalization strategy for inserted text.
    pub text_capitalization: TextCapitalization,
    /// Maximum number of Unicode scalar values allowed in the field.
    pub max_length: Option<usize>,
    /// Whether `max_length` should be enforced during editing.
    pub max_length_enforcement: MaxLengthEnforcement,
    /// Structured input formatters applied to inserted text.
    pub input_formatters: Vec<InputFormatter>,
    /// Hint to the platform IME whether autocorrect should be enabled.
    pub autocorrect: bool,
    /// Hint to the platform IME whether suggestions should be enabled.
    pub enable_suggestions: bool,
    /// Hint to the platform IME whether spell checking should be enabled.
    pub spell_check: bool,
    /// Hint to the platform IME whether smart dashes should be enabled.
    pub smart_dashes: bool,
    /// Hint to the platform IME whether smart quotes should be enabled.
    pub smart_quotes: bool,
    /// Platform autofill categories associated with this field.
    pub autofill_hints: Vec<String>,
    /// Extra padding to keep around the caret/selection when auto-scrolling `[left, right, top, bottom]`.
    pub scroll_padding: Option<[f32; 4]>,
    /// When true, Tab key inserts spaces instead of moving focus.
    pub capture_tab: bool,
    /// When true, Enter copies leading whitespace from the current line.
    pub auto_indent: bool,
}

impl std::hash::Hash for Semantics {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.role.hash(state);
        self.label.hash(state);
        self.identifier.hash(state);
        self.value.hash(state);
        self.actions.hash(state);
        self.action_scope_id.hash(state);
        self.focusable.hash(state);
        self.multiline.hash(state);
        self.masked.hash(state);
        self.input_mask.hash(state);
        self.ime_preedit_range.hash(state);
        self.checked.hash(state);
        self.disabled.hash(state);
        self.read_only.hash(state);
        self.autofocus.hash(state);
        self.draggable.hash(state);
        self.scrollable_x.hash(state);
        self.scrollable_y.hash(state);
        self.min_value.map(|f| f.to_bits()).hash(state);
        self.max_value.map(|f| f.to_bits()).hash(state);
        self.current_value.map(|f| f.to_bits()).hash(state);
        self.is_focus_scope.hash(state);
        self.is_focus_barrier.hash(state);
        self.drag_payload.hash(state);
        self.hero_tag.hash(state);
        self.focus_index.hash(state);
        self.text_input_type.hash(state);
        self.text_input_action.hash(state);
        self.text_capitalization.hash(state);
        self.max_length.hash(state);
        self.max_length_enforcement.hash(state);
        self.input_formatters.hash(state);
        self.autocorrect.hash(state);
        self.enable_suggestions.hash(state);
        self.spell_check.hash(state);
        self.smart_dashes.hash(state);
        self.smart_quotes.hash(state);
        self.autofill_hints.hash(state);
        self.scroll_padding
            .map(|padding| padding.map(f32::to_bits))
            .hash(state);
        self.capture_tab.hash(state);
        self.auto_indent.hash(state);
    }
}

impl Default for Semantics {
    fn default() -> Self {
        Self {
            role: Role::Generic,
            label: None,
            identifier: None,
            value: None,
            actions: ActionSet::default(),
            action_scope_id: None,
            focusable: false,
            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: TextInputType::Text,
            text_input_action: TextInputAction::Done,
            text_capitalization: TextCapitalization::None,
            max_length: None,
            max_length_enforcement: 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,
        }
    }
}

/// A collection of [`ActionEntry`]s attached to a semantics node.
///
/// `ActionSet` is a simple wrapper around a `Vec<ActionEntry>`. It exists as a
/// named type so that serialization and hashing are straightforward.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct ActionSet {
    /// The action entries. Order does not matter for dispatch; the event system
    /// matches on [`ActionTrigger`].
    pub entries: Vec<ActionEntry>,
}

/// Restricts which characters a text input accepts.
///
/// Apply an `InputMask` to a [`Semantics`] node to filter keystrokes before they
/// reach the text editing logic.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum InputMask {
    /// Accept only ASCII digits (`0`-`9`).
    Numeric,
    /// Accept only ASCII letters and digits (`a`-`z`, `A`-`Z`, `0`-`9`).
    Alphanumeric,
}

impl InputMask {
    /// Returns `true` if `ch` is accepted by this mask.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fission_ir::semantics::InputMask;
    /// assert!(InputMask::Numeric.is_valid_char('5'));
    /// assert!(!InputMask::Numeric.is_valid_char('a'));
    /// ```
    pub fn is_valid_char(&self, ch: char) -> bool {
        match self {
            InputMask::Numeric => ch.is_ascii_digit(),
            InputMask::Alphanumeric => ch.is_ascii_alphanumeric(),
        }
    }
}