fret-ui 0.1.0

Mechanism-layer UI engine for Fret with tree, layout, focus, routing, and interaction contracts.
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
use super::*;

impl<H: UiHost> UiTree<H> {
    pub fn platform_text_input_query(
        &mut self,
        app: &mut H,
        services: &mut dyn UiServices,
        scale_factor: f32,
        query: &fret_runtime::PlatformTextInputQuery,
    ) -> fret_runtime::PlatformTextInputQueryResult {
        let focus_is_text_input = self.focus_is_text_input(app);
        if !focus_is_text_input {
            return match query {
                fret_runtime::PlatformTextInputQuery::SelectedTextRange
                | fret_runtime::PlatformTextInputQuery::MarkedTextRange => {
                    fret_runtime::PlatformTextInputQueryResult::Range(None)
                }
                fret_runtime::PlatformTextInputQuery::TextForRange { .. } => {
                    fret_runtime::PlatformTextInputQueryResult::Text(None)
                }
                fret_runtime::PlatformTextInputQuery::BoundsForRange { .. } => {
                    fret_runtime::PlatformTextInputQueryResult::Bounds(None)
                }
                fret_runtime::PlatformTextInputQuery::CharacterIndexForPoint { .. } => {
                    fret_runtime::PlatformTextInputQueryResult::Index(None)
                }
            };
        }

        let Some(focus) = self.focus else {
            return match query {
                fret_runtime::PlatformTextInputQuery::SelectedTextRange
                | fret_runtime::PlatformTextInputQuery::MarkedTextRange => {
                    fret_runtime::PlatformTextInputQueryResult::Range(None)
                }
                fret_runtime::PlatformTextInputQuery::TextForRange { .. } => {
                    fret_runtime::PlatformTextInputQueryResult::Text(None)
                }
                fret_runtime::PlatformTextInputQuery::BoundsForRange { .. } => {
                    fret_runtime::PlatformTextInputQueryResult::Bounds(None)
                }
                fret_runtime::PlatformTextInputQuery::CharacterIndexForPoint { .. } => {
                    fret_runtime::PlatformTextInputQueryResult::Index(None)
                }
            };
        };

        let bounds = self.nodes.get(focus).map(|n| n.bounds).unwrap_or_default();

        if let Some(window) = self.window
            && let Some(record) = crate::declarative::element_record_for_node(app, window, focus)
        {
            let element = record.element;
            if let crate::declarative::ElementInstance::TextInputRegion(props) = record.instance {
                let ctx = TextInputRegionPlatformCtx {
                    window,
                    element,
                    bounds,
                    scale_factor,
                    props: &props,
                };
                return text_input_region_platform_text_input_query_with_hooks(
                    app, services, ctx, query,
                );
            }
        }

        match query {
            fret_runtime::PlatformTextInputQuery::SelectedTextRange => {
                let range = self
                    .nodes
                    .get(focus)
                    .and_then(|n| n.widget.as_ref())
                    .and_then(|w| w.platform_text_input_selected_range_utf16());
                fret_runtime::PlatformTextInputQueryResult::Range(range)
            }
            fret_runtime::PlatformTextInputQuery::MarkedTextRange => {
                let range = self
                    .nodes
                    .get(focus)
                    .and_then(|n| n.widget.as_ref())
                    .and_then(|w| w.platform_text_input_marked_range_utf16());
                fret_runtime::PlatformTextInputQueryResult::Range(range)
            }
            fret_runtime::PlatformTextInputQuery::TextForRange { range } => {
                let text = self
                    .nodes
                    .get(focus)
                    .and_then(|n| n.widget.as_ref())
                    .and_then(|w| w.platform_text_input_text_for_range_utf16(*range));
                fret_runtime::PlatformTextInputQueryResult::Text(text)
            }
            fret_runtime::PlatformTextInputQuery::BoundsForRange { range } => {
                let out = self.with_widget_mut(focus, |w, _tree| {
                    let mut cx = PlatformTextInputCx {
                        app,
                        services,
                        window: _tree.window,
                        node: focus,
                        bounds,
                        scale_factor,
                    };
                    w.platform_text_input_bounds_for_range_utf16(&mut cx, *range)
                });
                fret_runtime::PlatformTextInputQueryResult::Bounds(out)
            }
            fret_runtime::PlatformTextInputQuery::CharacterIndexForPoint { point } => {
                let out = self.with_widget_mut(focus, |w, _tree| {
                    let mut cx = PlatformTextInputCx {
                        app,
                        services,
                        window: _tree.window,
                        node: focus,
                        bounds,
                        scale_factor,
                    };
                    w.platform_text_input_character_index_for_point_utf16(&mut cx, *point)
                });
                fret_runtime::PlatformTextInputQueryResult::Index(out)
            }
        }
    }

    pub fn platform_text_input_replace_text_in_range_utf16(
        &mut self,
        app: &mut H,
        services: &mut dyn UiServices,
        scale_factor: f32,
        range: fret_runtime::Utf16Range,
        text: &str,
    ) -> bool {
        if !self.focus_is_text_input(app) {
            return false;
        }
        let Some(focus) = self.focus else {
            return false;
        };
        let bounds = self.nodes.get(focus).map(|n| n.bounds).unwrap_or_default();

        if let Some(window) = self.window
            && let Some(record) = crate::declarative::element_record_for_node(app, window, focus)
        {
            let element = record.element;
            if let crate::declarative::ElementInstance::TextInputRegion(props) = record.instance {
                let ctx = TextInputRegionPlatformCtx {
                    window,
                    element,
                    bounds,
                    scale_factor,
                    props: &props,
                };
                let changed =
                    text_input_region_platform_text_input_replace_text_in_range_utf16_with_hooks(
                        app, services, ctx, range, text,
                    );
                if changed {
                    self.invalidate(focus, Invalidation::Layout);
                    self.request_redraw_coalesced(app);
                }
                return changed;
            }
        }

        let changed = self.with_widget_mut(focus, |w, _tree| {
            let mut cx = PlatformTextInputCx {
                app,
                services,
                window: _tree.window,
                node: focus,
                bounds,
                scale_factor,
            };
            w.platform_text_input_replace_text_in_range_utf16(&mut cx, range, text)
        });
        if changed {
            self.invalidate(focus, Invalidation::Layout);
            self.request_redraw_coalesced(app);
        }
        changed
    }

    pub fn platform_text_input_replace_and_mark_text_in_range_utf16(
        &mut self,
        app: &mut H,
        services: &mut dyn UiServices,
        scale_factor: f32,
        range: fret_runtime::Utf16Range,
        text: &str,
        marked: Option<fret_runtime::Utf16Range>,
        selected: Option<fret_runtime::Utf16Range>,
    ) -> bool {
        if !self.focus_is_text_input(app) {
            return false;
        }
        let Some(focus) = self.focus else {
            return false;
        };
        let bounds = self.nodes.get(focus).map(|n| n.bounds).unwrap_or_default();

        if let Some(window) = self.window
            && let Some(record) = crate::declarative::element_record_for_node(app, window, focus)
        {
            let element = record.element;
            if let crate::declarative::ElementInstance::TextInputRegion(props) = record.instance {
                let ctx = TextInputRegionPlatformCtx {
                    window,
                    element,
                    bounds,
                    scale_factor,
                    props: &props,
                };
                let changed =
                    text_input_region_platform_text_input_replace_and_mark_text_in_range_utf16_with_hooks(
                        app, services, ctx, range, text, marked, selected,
                    );
                if changed {
                    self.invalidate(focus, Invalidation::Layout);
                    self.request_redraw_coalesced(app);
                }
                return changed;
            }
        }

        let changed = self.with_widget_mut(focus, |w, _tree| {
            let mut cx = PlatformTextInputCx {
                app,
                services,
                window: _tree.window,
                node: focus,
                bounds,
                scale_factor,
            };
            w.platform_text_input_replace_and_mark_text_in_range_utf16(
                &mut cx, range, text, marked, selected,
            )
        });
        if changed {
            self.invalidate(focus, Invalidation::Layout);
            self.request_redraw_coalesced(app);
        }
        changed
    }

    pub(in crate::tree) fn set_ime_allowed(&mut self, app: &mut H, enabled: bool) {
        if self.ime_allowed == enabled {
            return;
        }
        self.ime_allowed = enabled;
        let Some(window) = self.window else {
            return;
        };
        app.push_effect(Effect::ImeAllow { window, enabled });
    }
}

pub(in crate::tree) fn text_input_region_platform_text_input_snapshot(
    props: &crate::element::TextInputRegionProps,
) -> fret_runtime::WindowTextInputSnapshot {
    let value = props.a11y_value.as_deref().unwrap_or("");

    let len_utf16_usize = fret_core::utf::utf8_byte_offset_to_utf16_offset(
        value,
        value.len(),
        fret_core::utf::UtfIndexClamp::Down,
    );
    let len_utf16 = u32::try_from(len_utf16_usize).unwrap_or(u32::MAX);

    let selection_utf16 = props.a11y_text_selection.map(|(anchor, focus)| {
        let anchor_u16 = fret_core::utf::utf8_byte_offset_to_utf16_offset(
            value,
            usize::try_from(anchor).unwrap_or(usize::MAX),
            fret_core::utf::UtfIndexClamp::Down,
        );
        let focus_u16 = fret_core::utf::utf8_byte_offset_to_utf16_offset(
            value,
            usize::try_from(focus).unwrap_or(usize::MAX),
            fret_core::utf::UtfIndexClamp::Down,
        );
        (
            u32::try_from(anchor_u16).unwrap_or(u32::MAX),
            u32::try_from(focus_u16).unwrap_or(u32::MAX),
        )
    });

    let marked_utf16 = props.a11y_text_composition.map(|(start, end)| {
        let (s, e) = fret_core::utf::utf8_byte_range_to_utf16_range(
            value,
            usize::try_from(start).unwrap_or(usize::MAX),
            usize::try_from(end).unwrap_or(usize::MAX),
        );
        (
            u32::try_from(s).unwrap_or(u32::MAX),
            u32::try_from(e).unwrap_or(u32::MAX),
        )
    });

    fret_runtime::WindowTextInputSnapshot {
        focus_is_text_input: true,
        is_composing: marked_utf16.is_some(),
        text_len_utf16: len_utf16,
        selection_utf16,
        marked_utf16,
        ime_cursor_area: props.ime_cursor_area,
        surrounding_text: props.ime_surrounding_text.clone(),
    }
}

fn text_input_region_platform_text_input_query(
    props: &crate::element::TextInputRegionProps,
    query: &fret_runtime::PlatformTextInputQuery,
) -> fret_runtime::PlatformTextInputQueryResult {
    let value = props.a11y_value.as_deref().unwrap_or("");

    match query {
        fret_runtime::PlatformTextInputQuery::SelectedTextRange => {
            let Some((anchor, focus)) = props.a11y_text_selection else {
                return fret_runtime::PlatformTextInputQueryResult::Range(None);
            };

            let anchor_u16 = fret_core::utf::utf8_byte_offset_to_utf16_offset(
                value,
                usize::try_from(anchor).unwrap_or(usize::MAX),
                fret_core::utf::UtfIndexClamp::Down,
            );
            let focus_u16 = fret_core::utf::utf8_byte_offset_to_utf16_offset(
                value,
                usize::try_from(focus).unwrap_or(usize::MAX),
                fret_core::utf::UtfIndexClamp::Down,
            );
            let range = fret_runtime::Utf16Range::new(
                u32::try_from(anchor_u16).unwrap_or(u32::MAX),
                u32::try_from(focus_u16).unwrap_or(u32::MAX),
            )
            .normalized();

            fret_runtime::PlatformTextInputQueryResult::Range(Some(range))
        }
        fret_runtime::PlatformTextInputQuery::MarkedTextRange => {
            let Some((start, end)) = props.a11y_text_composition else {
                return fret_runtime::PlatformTextInputQueryResult::Range(None);
            };

            let (s, e) = fret_core::utf::utf8_byte_range_to_utf16_range(
                value,
                usize::try_from(start).unwrap_or(usize::MAX),
                usize::try_from(end).unwrap_or(usize::MAX),
            );
            let range = fret_runtime::Utf16Range::new(
                u32::try_from(s).unwrap_or(u32::MAX),
                u32::try_from(e).unwrap_or(u32::MAX),
            )
            .normalized();

            fret_runtime::PlatformTextInputQueryResult::Range(Some(range))
        }
        fret_runtime::PlatformTextInputQuery::TextForRange { range } => {
            if value.is_empty() {
                return fret_runtime::PlatformTextInputQueryResult::Text(None);
            }

            let range = range.normalized();
            let (bs, be) = fret_core::utf::utf16_range_to_utf8_byte_range(
                value,
                usize::try_from(range.start).unwrap_or(usize::MAX),
                usize::try_from(range.end).unwrap_or(usize::MAX),
            );

            let out = value.get(bs..be).map(ToString::to_string);
            fret_runtime::PlatformTextInputQueryResult::Text(out)
        }
        fret_runtime::PlatformTextInputQuery::BoundsForRange { .. } => {
            fret_runtime::PlatformTextInputQueryResult::Bounds(None)
        }
        fret_runtime::PlatformTextInputQuery::CharacterIndexForPoint { .. } => {
            fret_runtime::PlatformTextInputQueryResult::Index(None)
        }
    }
}

#[derive(Clone, Copy)]
pub(in crate::tree) struct TextInputRegionPlatformCtx<'a> {
    window: fret_core::AppWindowId,
    element: crate::GlobalElementId,
    bounds: Rect,
    scale_factor: f32,
    props: &'a crate::element::TextInputRegionProps,
}

pub(in crate::tree) fn text_input_region_platform_text_input_query_with_hooks<H: UiHost>(
    app: &mut H,
    services: &mut dyn UiServices,
    ctx: TextInputRegionPlatformCtx<'_>,
    query: &fret_runtime::PlatformTextInputQuery,
) -> fret_runtime::PlatformTextInputQueryResult {
    match query {
        fret_runtime::PlatformTextInputQuery::BoundsForRange { .. }
        | fret_runtime::PlatformTextInputQuery::CharacterIndexForPoint { .. } => {
            let hook = crate::elements::with_element_state(
                app,
                ctx.window,
                ctx.element,
                crate::action::TextInputRegionActionHooks::default,
                |hooks| hooks.on_platform_text_input_query.clone(),
            );

            if let Some(hook) = hook {
                struct TextInputRegionPlatformQueryHost<'a, H: UiHost> {
                    app: &'a mut H,
                }

                impl<H: UiHost> crate::action::UiActionHost for TextInputRegionPlatformQueryHost<'_, H> {
                    fn models_mut(&mut self) -> &mut fret_runtime::ModelStore {
                        self.app.models_mut()
                    }

                    fn push_effect(&mut self, effect: fret_runtime::Effect) {
                        self.app.push_effect(effect);
                    }

                    fn request_redraw(&mut self, window: fret_core::AppWindowId) {
                        self.app.request_redraw(window);
                    }

                    fn next_timer_token(&mut self) -> fret_runtime::TimerToken {
                        self.app.next_timer_token()
                    }

                    fn next_clipboard_token(&mut self) -> fret_runtime::ClipboardToken {
                        self.app.next_clipboard_token()
                    }

                    fn next_share_sheet_token(&mut self) -> fret_runtime::ShareSheetToken {
                        self.app.next_share_sheet_token()
                    }

                    fn notify(&mut self, _cx: crate::action::ActionCx) {}
                }

                let mut host = TextInputRegionPlatformQueryHost { app };
                let action_cx = crate::action::ActionCx {
                    window: ctx.window,
                    target: ctx.element,
                };
                if let Some(out) = hook(
                    &mut host,
                    action_cx,
                    services,
                    ctx.bounds,
                    ctx.scale_factor,
                    ctx.props,
                    query,
                ) {
                    return out;
                }
            }

            match query {
                fret_runtime::PlatformTextInputQuery::BoundsForRange { .. } => {
                    fret_runtime::PlatformTextInputQueryResult::Bounds(None)
                }
                fret_runtime::PlatformTextInputQuery::CharacterIndexForPoint { .. } => {
                    fret_runtime::PlatformTextInputQueryResult::Index(None)
                }
                _ => unreachable!(),
            }
        }
        _ => text_input_region_platform_text_input_query(ctx.props, query),
    }
}

pub(in crate::tree) fn text_input_region_platform_text_input_replace_text_in_range_utf16_with_hooks<
    H: UiHost,
>(
    app: &mut H,
    services: &mut dyn UiServices,
    ctx: TextInputRegionPlatformCtx<'_>,
    range: fret_runtime::Utf16Range,
    text: &str,
) -> bool {
    let hook = crate::elements::with_element_state(
        app,
        ctx.window,
        ctx.element,
        crate::action::TextInputRegionActionHooks::default,
        |hooks| {
            hooks
                .on_platform_text_input_replace_text_in_range_utf16
                .clone()
        },
    );

    let Some(hook) = hook else {
        return false;
    };

    struct TextInputRegionPlatformReplaceHost<'a, H: UiHost> {
        app: &'a mut H,
    }

    impl<H: UiHost> crate::action::UiActionHost for TextInputRegionPlatformReplaceHost<'_, H> {
        fn models_mut(&mut self) -> &mut fret_runtime::ModelStore {
            self.app.models_mut()
        }

        fn push_effect(&mut self, effect: fret_runtime::Effect) {
            self.app.push_effect(effect);
        }

        fn request_redraw(&mut self, window: fret_core::AppWindowId) {
            self.app.request_redraw(window);
        }

        fn next_timer_token(&mut self) -> fret_runtime::TimerToken {
            self.app.next_timer_token()
        }

        fn next_clipboard_token(&mut self) -> fret_runtime::ClipboardToken {
            self.app.next_clipboard_token()
        }

        fn next_share_sheet_token(&mut self) -> fret_runtime::ShareSheetToken {
            self.app.next_share_sheet_token()
        }

        fn notify(&mut self, _cx: crate::action::ActionCx) {}
    }

    let mut host = TextInputRegionPlatformReplaceHost { app };
    let action_cx = crate::action::ActionCx {
        window: ctx.window,
        target: ctx.element,
    };
    hook(
        &mut host,
        action_cx,
        services,
        ctx.bounds,
        ctx.scale_factor,
        ctx.props,
        range,
        text,
    )
}

pub(in crate::tree) fn text_input_region_platform_text_input_replace_and_mark_text_in_range_utf16_with_hooks<
    H: UiHost,
>(
    app: &mut H,
    services: &mut dyn UiServices,
    ctx: TextInputRegionPlatformCtx<'_>,
    range: fret_runtime::Utf16Range,
    text: &str,
    marked: Option<fret_runtime::Utf16Range>,
    selected: Option<fret_runtime::Utf16Range>,
) -> bool {
    let hook = crate::elements::with_element_state(
        app,
        ctx.window,
        ctx.element,
        crate::action::TextInputRegionActionHooks::default,
        |hooks| {
            hooks
                .on_platform_text_input_replace_and_mark_text_in_range_utf16
                .clone()
        },
    );

    let Some(hook) = hook else {
        return false;
    };

    struct TextInputRegionPlatformReplaceHost<'a, H: UiHost> {
        app: &'a mut H,
    }

    impl<H: UiHost> crate::action::UiActionHost for TextInputRegionPlatformReplaceHost<'_, H> {
        fn models_mut(&mut self) -> &mut fret_runtime::ModelStore {
            self.app.models_mut()
        }

        fn push_effect(&mut self, effect: fret_runtime::Effect) {
            self.app.push_effect(effect);
        }

        fn request_redraw(&mut self, window: fret_core::AppWindowId) {
            self.app.request_redraw(window);
        }

        fn next_timer_token(&mut self) -> fret_runtime::TimerToken {
            self.app.next_timer_token()
        }

        fn next_clipboard_token(&mut self) -> fret_runtime::ClipboardToken {
            self.app.next_clipboard_token()
        }

        fn next_share_sheet_token(&mut self) -> fret_runtime::ShareSheetToken {
            self.app.next_share_sheet_token()
        }

        fn notify(&mut self, _cx: crate::action::ActionCx) {}
    }

    let mut host = TextInputRegionPlatformReplaceHost { app };
    let action_cx = crate::action::ActionCx {
        window: ctx.window,
        target: ctx.element,
    };
    hook(
        &mut host,
        action_cx,
        services,
        ctx.bounds,
        ctx.scale_factor,
        ctx.props,
        range,
        text,
        marked,
        selected,
    )
}