mirui 0.3.1

A lightweight, no_std ECS-driven UI framework for embedded, desktop, and WebAssembly
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
use crate::backend::InputEvent;
use crate::components::scroll::{ScrollAxis, ScrollConfig, ScrollOffset};
use crate::ecs::{Entity, World};
use crate::event::hit_test::hit_test;
use crate::types::Fixed;

/// Scroll drag state resource
pub struct ScrollDragState {
    pub active: bool,
    pub resolved: bool,
    pub target: Entity,
    pub hit_entity: Entity,
    pub start_x: Fixed,
    pub start_y: Fixed,
    pub last_x: Fixed,
    pub last_y: Fixed,
    pub vel_x: Fixed,
    pub vel_y: Fixed,
}

impl Default for ScrollDragState {
    fn default() -> Self {
        let null = Entity {
            id: 0,
            generation: 0,
        };
        Self {
            active: false,
            resolved: false,
            target: null,
            hit_entity: null,
            start_x: Fixed::ZERO,
            start_y: Fixed::ZERO,
            last_x: Fixed::ZERO,
            last_y: Fixed::ZERO,
            vel_x: Fixed::ZERO,
            vel_y: Fixed::ZERO,
        }
    }
}

const DIRECTION_THRESHOLD: Fixed = Fixed::from_int(5);

pub fn scroll_system(
    world: &mut World,
    root: Entity,
    event: &InputEvent,
    screen_w: u16,
    screen_h: u16,
) {
    match event {
        InputEvent::Touch { x, y } => {
            // Record start, don't resolve target yet
            let hit = hit_test(world, root, *x, *y, screen_w, screen_h);
            if let Some(state) = world.resource_mut::<ScrollDragState>() {
                state.active = true;
                state.resolved = false;
                state.hit_entity = hit.unwrap_or(Entity {
                    id: 0,
                    generation: 0,
                });
                state.start_x = *x;
                state.start_y = *y;
                state.last_x = *x;
                state.last_y = *y;
                state.vel_x = Fixed::ZERO;
                state.vel_y = Fixed::ZERO;
            }
        }
        InputEvent::TouchMove { x, y } => {
            let (active, resolved, _target, hit_entity, last_x, last_y, start_x, start_y) = {
                let Some(state) = world.resource::<ScrollDragState>() else {
                    return;
                };
                (
                    state.active,
                    state.resolved,
                    state.target,
                    state.hit_entity,
                    state.last_x,
                    state.last_y,
                    state.start_x,
                    state.start_y,
                )
            };

            if !active {
                return;
            }

            // If not resolved yet, check if we've moved enough to determine direction
            if !resolved {
                let total_dx = (*x - start_x).abs();
                let total_dy = (*y - start_y).abs();

                if total_dx < DIRECTION_THRESHOLD && total_dy < DIRECTION_THRESHOLD {
                    // Not enough movement to determine direction
                    if let Some(state) = world.resource_mut::<ScrollDragState>() {
                        state.last_x = *x;
                        state.last_y = *y;
                    }
                    return;
                }

                // Determine gesture direction
                let gesture_dir = if total_dy > total_dx {
                    ScrollAxis::Vertical
                } else {
                    ScrollAxis::Horizontal
                };

                // Find scroll target matching this direction
                // delta sign: positive = user dragging content up (wants to scroll down)
                let scroll_dx = -(*x - start_x);
                let scroll_dy = -(*y - start_y);
                let found = find_scroll_target_for_direction(
                    world,
                    hit_entity,
                    gesture_dir,
                    scroll_dx,
                    scroll_dy,
                );

                if let Some(state) = world.resource_mut::<ScrollDragState>() {
                    state.resolved = true;
                    if let Some(t) = found {
                        state.target = t;
                    } else {
                        // No matching scroll target — deactivate
                        state.active = false;
                        return;
                    }
                }
            }

            // Apply scroll delta — no mid-drag chaining (iOS behavior)
            // Chain decision was made at resolve time. During drag, always apply to target.
            let (target,) = {
                let Some(state) = world.resource::<ScrollDragState>() else {
                    return;
                };
                (state.target,)
            };

            let dx = *x - last_x;
            let dy = *y - last_y;

            // Read bounds for resistance calculation
            let config = world.get::<ScrollConfig>(target);
            let dir = config.map(|c| c.direction).unwrap_or(ScrollAxis::Vertical);
            let computed = world.get::<crate::widget::ComputedRect>(target);
            let container_h = computed.map(|c| c.0.h).unwrap_or(Fixed::ZERO);
            let container_w = computed.map(|c| c.0.w).unwrap_or(Fixed::ZERO);
            let content_h: Fixed = config.map(|c| c.content_height).unwrap_or(container_h);
            let content_w: Fixed = config.map(|c| c.content_width).unwrap_or(container_w);
            let max_y = (content_h - container_h).max(Fixed::ZERO);
            let max_x = (content_w - container_w).max(Fixed::ZERO);

            if let Some(scroll) = world.get_mut::<ScrollOffset>(target) {
                match dir {
                    ScrollAxis::Vertical => {
                        let eff_dy = elastic_resist(scroll.y, -dy, max_y);
                        scroll.y += eff_dy;
                    }
                    ScrollAxis::Horizontal => {
                        let eff_dx = elastic_resist(scroll.x, -dx, max_x);
                        scroll.x += eff_dx;
                    }
                    ScrollAxis::Both => {
                        let eff_dx = elastic_resist(scroll.x, -dx, max_x);
                        let eff_dy = elastic_resist(scroll.y, -dy, max_y);
                        scroll.x += eff_dx;
                        scroll.y += eff_dy;
                    }
                }
            }
            world.insert(target, crate::widget::dirty::Dirty);

            let dir = world
                .get::<ScrollConfig>(target)
                .map(|c| c.direction)
                .unwrap_or(ScrollAxis::Vertical);
            if let Some(state) = world.resource_mut::<ScrollDragState>() {
                match dir {
                    ScrollAxis::Vertical => {
                        state.vel_x = Fixed::ZERO;
                        state.vel_y = -dy;
                    }
                    ScrollAxis::Horizontal => {
                        state.vel_x = -dx;
                        state.vel_y = Fixed::ZERO;
                    }
                    ScrollAxis::Both => {
                        state.vel_x = -dx;
                        state.vel_y = -dy;
                    }
                }
                state.last_x = *x;
                state.last_y = *y;
            }
        }
        InputEvent::Release { .. } => {
            if let Some(state) = world.resource_mut::<ScrollDragState>() {
                state.active = false;
            }
        }
        _ => {}
    }
}

/// Inertia system — call every frame to decelerate scroll after release
pub fn scroll_inertia_system(world: &mut World) {
    let (active, resolved, target, vel_x, vel_y) = {
        let Some(state) = world.resource::<ScrollDragState>() else {
            return;
        };
        (
            state.active,
            state.resolved,
            state.target,
            state.vel_x,
            state.vel_y,
        )
    };

    if active || !resolved {
        return;
    }

    // Get scroll bounds for elastic
    let (offset_x, offset_y, max_x, max_y, elastic, dir) = {
        let Some(scroll) = world.get::<ScrollOffset>(target) else {
            return;
        };
        let config = world.get::<crate::components::scroll::ScrollConfig>(target);
        let computed = world.get::<crate::widget::ComputedRect>(target);
        let container_h = computed.map(|c| c.0.h).unwrap_or(Fixed::ZERO);
        let container_w = computed.map(|c| c.0.w).unwrap_or(Fixed::ZERO);
        let content_h: Fixed = config.map(|c| c.content_height).unwrap_or(container_h);
        let content_w: Fixed = config.map(|c| c.content_width).unwrap_or(container_w);
        let max_y = (content_h - container_h).max(Fixed::ZERO);
        let max_x = (content_w - container_w).max(Fixed::ZERO);
        let elastic = config.map(|c| c.elastic).unwrap_or(true);
        let dir = config.map(|c| c.direction).unwrap_or(ScrollAxis::Vertical);
        (scroll.x, scroll.y, max_x, max_y, elastic, dir)
    };

    let mut new_vel_x = vel_x;
    let mut new_vel_y = vel_y;

    // Elastic bounce
    let mut bouncing = false;
    if elastic {
        match dir {
            ScrollAxis::Vertical | ScrollAxis::Both => {
                if offset_y < Fixed::ZERO {
                    let diff = -offset_y;
                    new_vel_y = if diff.abs() <= Fixed::from_int(3) {
                        diff
                    } else {
                        diff / 3
                    };
                    bouncing = true;
                } else if offset_y > max_y {
                    let diff = max_y - offset_y;
                    new_vel_y = if diff.abs() <= Fixed::from_int(3) {
                        diff
                    } else {
                        diff / 3
                    };
                    bouncing = true;
                }
            }
            _ => {}
        }
        match dir {
            ScrollAxis::Horizontal | ScrollAxis::Both => {
                if offset_x < Fixed::ZERO {
                    let diff = -offset_x;
                    new_vel_x = if diff.abs() <= Fixed::from_int(3) {
                        diff
                    } else {
                        diff / 3
                    };
                    bouncing = true;
                } else if offset_x > max_x {
                    let diff = max_x - offset_x;
                    new_vel_x = if diff.abs() <= Fixed::from_int(3) {
                        diff
                    } else {
                        diff / 3
                    };
                    bouncing = true;
                }
            }
            _ => {}
        }
    }

    if new_vel_x == Fixed::ZERO && new_vel_y == Fixed::ZERO {
        return;
    }

    // Apply velocity
    if let Some(scroll) = world.get_mut::<ScrollOffset>(target) {
        scroll.x += new_vel_x;
        scroll.y += new_vel_y;
    }
    world.insert(target, crate::widget::dirty::Dirty);

    // Decay velocity
    if let Some(state) = world.resource_mut::<ScrollDragState>() {
        if bouncing {
            state.vel_x = Fixed::ZERO;
            state.vel_y = Fixed::ZERO;
        } else {
            state.vel_x = new_vel_x * 9 / 10;
            state.vel_y = new_vel_y * 9 / 10;
            if state.vel_x.abs() < Fixed::ONE {
                state.vel_x = Fixed::ZERO;
            }
            if state.vel_y.abs() < Fixed::ONE {
                state.vel_y = Fixed::ZERO;
            }
        }
    }
}

fn find_scroll_target_for_direction(
    world: &World,
    start: Entity,
    gesture_dir: ScrollAxis,
    delta_x: Fixed,
    delta_y: Fixed,
) -> Option<Entity> {
    let mut current = start;
    let mut last_matching: Option<Entity> = None;
    loop {
        if world.get::<ScrollOffset>(current).is_some() {
            let config = world.get::<ScrollConfig>(current);
            let scroll_dir = config.map(|c| c.direction).unwrap_or(ScrollAxis::Vertical);

            let dir_matches = matches!(
                (scroll_dir, gesture_dir),
                (ScrollAxis::Both, _)
                    | (ScrollAxis::Vertical, ScrollAxis::Vertical)
                    | (ScrollAxis::Horizontal, ScrollAxis::Horizontal)
            );

            if dir_matches {
                last_matching = Some(current);
                let at_boundary = is_at_boundary(world, current, delta_x, delta_y);
                if !at_boundary {
                    return Some(current);
                }
            }
        }
        if let Some(parent) = world.get::<crate::widget::Parent>(current) {
            current = parent.0;
        } else {
            break;
        }
    }
    // All matching scrolls are at boundary — return outermost for elastic
    last_matching
}

/// Apply elastic resistance when overscrolling.
/// `offset`: current scroll offset, `delta`: requested change, `max`: max allowed offset.
/// Returns the effective delta to apply (reduced when out of bounds).
fn elastic_resist(offset: Fixed, delta: Fixed, max: Fixed) -> Fixed {
    const DAMPING: i32 = 200;

    let new_offset = offset + delta;

    // If staying in bounds, no resistance
    if new_offset >= Fixed::ZERO && new_offset <= max {
        return delta;
    }

    // Calculate how far out of bounds we are (or will be)
    let overscroll = if new_offset < Fixed::ZERO {
        -new_offset
    } else {
        new_offset - max
    };

    // Resistance: damping / (damping + overscroll)
    // Use integer math on raw values
    let over_int = overscroll.to_int();
    let resistance_denom = DAMPING + over_int;
    if resistance_denom == 0 {
        return Fixed::ZERO;
    }
    delta * DAMPING / resistance_denom
}
fn is_at_boundary(world: &World, entity: Entity, delta_x: Fixed, delta_y: Fixed) -> bool {
    let Some(scroll) = world.get::<ScrollOffset>(entity) else {
        return false;
    };
    let config = world.get::<ScrollConfig>(entity);
    let computed = world.get::<crate::widget::ComputedRect>(entity);
    let container_h = computed.map(|c| c.0.h).unwrap_or(Fixed::ZERO);
    let container_w = computed.map(|c| c.0.w).unwrap_or(Fixed::ZERO);
    let content_h = config.map(|c| c.content_height).unwrap_or(container_h);
    let content_w = config.map(|c| c.content_width).unwrap_or(container_w);
    let max_y = (content_h - container_h).max(Fixed::ZERO);
    let max_x = (content_w - container_w).max(Fixed::ZERO);

    let at_y = (scroll.y <= Fixed::ZERO && delta_y < Fixed::ZERO)
        || (scroll.y >= max_y && delta_y > Fixed::ZERO);
    let at_x = (scroll.x <= Fixed::ZERO && delta_x < Fixed::ZERO)
        || (scroll.x >= max_x && delta_x > Fixed::ZERO);

    let dir = config.map(|c| c.direction).unwrap_or(ScrollAxis::Vertical);
    match dir {
        ScrollAxis::Vertical => at_y,
        ScrollAxis::Horizontal => at_x,
        ScrollAxis::Both => at_y || at_x,
    }
}