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
use dioxus::prelude::*;
use freya_common::NodeReferenceLayout;
use freya_elements::{
    elements as dioxus_elements,
    events::MouseEvent,
};
use freya_hooks::{
    use_applied_theme,
    use_node_signal,
    use_platform,
    ResizableHandleTheme,
    ResizableHandleThemeWith,
};
use winit::window::CursorIcon;

struct Panel {
    pub size: f32,
    pub min_size: f32,
}

enum ResizableItem {
    Panel(Panel),
    Handle,
}

impl ResizableItem {
    /// Get the [Panel] of the [ResizableItem]. Will panic if called in a [ResizableItem::Handle].
    fn panel(&self) -> &Panel {
        match self {
            Self::Panel(panel) => panel,
            Self::Handle => panic!("Not a Panel"),
        }
    }

    /// Try to get the mutable [Panel] of the [ResizableItem]. Will return [None] if called in a [ResizableItem::Handle].
    fn try_panel_mut(&mut self) -> Option<&mut Panel> {
        match self {
            Self::Panel(panel) => Some(panel),
            Self::Handle => None,
        }
    }
}

#[derive(Default)]
struct ResizableContext {
    pub registry: Vec<ResizableItem>,
    pub direction: String,
}

/// Resizable container, used in combination with [ResizablePanel] and [ResizableHandle].
///
/// Example:
///
/// ```no_run
/// # use freya::prelude::*;
/// fn app() -> Element {
///     rsx!(
///         ResizableContainer {
///             direction: "vertical",
///             ResizablePanel {
///                 initial_size: 50.0,
///                 label {
///                     "Panel 1"
///                 }
///             }
///             ResizableHandle { }
///             ResizablePanel {
///                 initial_size: 50.0,
///                 min_size: 30.0,
///                 label {
///                     "Panel 2"
///                 }
///             }
///         }
///     )
/// }
/// ```
#[component]
pub fn ResizableContainer(
    /// Direction of the container, `vertical`/`horizontal`.
    /// Default to `vertical`.
    #[props(default = "vertical".to_string())]
    direction: String,
    /// Inner children for the [ResizableContainer].
    children: Element,
) -> Element {
    let (node_reference, size) = use_node_signal();
    use_context_provider(|| size);

    use_context_provider(|| {
        Signal::new(ResizableContext {
            direction: direction.clone(),
            ..Default::default()
        })
    });

    rsx!(
        rect {
            reference: node_reference,
            direction: "{direction}",
            width: "fill",
            height: "fill",
            content: "flex",
            {children}
        }
    )
}

/// Resizable panel to be used in combination with [ResizableContainer] and [ResizableHandle].
#[component]
pub fn ResizablePanel(
    /// Initial size in % for this panel. Default to `10`.
    #[props(default = 10.)]
    initial_size: f32, // TODO: Automatically assign the remaining space in the last element with unspecified size?
    /// Minimum size in % for this panel. Default to `4`.
    #[props(default = 4.)]
    min_size: f32,
    /// Inner children for the [ResizablePanel].
    children: Element,
) -> Element {
    let mut registry = use_context::<Signal<ResizableContext>>();

    let index = use_hook(move || {
        registry.write().registry.push(ResizableItem::Panel(Panel {
            size: initial_size,
            min_size,
        }));
        registry.peek().registry.len() - 1
    });

    let registry = registry.read();

    let Panel { size, .. } = registry.registry[index].panel();

    let (width, height) = match registry.direction.as_str() {
        "horizontal" => (format!("flex({size})"), "fill".to_owned()),
        _ => ("fill".to_owned(), format!("flex({size}")),
    };

    rsx!(
        rect {
            width: "{width}",
            height: "{height}",
            overflow: "clip",
            {children}
        }
    )
}

/// Describes the current status of the Handle.
#[derive(Debug, Default, PartialEq, Clone, Copy)]
pub enum HandleStatus {
    /// Default state.
    #[default]
    Idle,
    /// Mouse is hovering the handle.
    Hovering,
}

/// Resizable panel to be used in combination with [ResizableContainer] and [ResizablePanel].
#[component]
pub fn ResizableHandle(
    /// Theme override.
    theme: Option<ResizableHandleThemeWith>,
) -> Element {
    let ResizableHandleTheme {
        background,
        hover_background,
    } = use_applied_theme!(&theme, resizable_handle);
    let (node_reference, size) = use_node_signal();
    let mut clicking = use_signal(|| false);
    let mut status = use_signal(HandleStatus::default);
    let mut registry = use_context::<Signal<ResizableContext>>();
    let container_size = use_context::<ReadOnlySignal<NodeReferenceLayout>>();
    let platform = use_platform();
    let mut allow_resizing = use_signal(|| false);

    use_memo(move || {
        size.read();
        allow_resizing.set(true);

        // Only allow more resizing after the node layout has updated
    });

    use_drop(move || {
        if *status.peek() == HandleStatus::Hovering {
            platform.set_cursor(CursorIcon::default());
        }
    });

    let index = use_hook(move || {
        registry.write().registry.push(ResizableItem::Handle);
        registry.peek().registry.len() - 1
    });

    let cursor = match registry.read().direction.as_str() {
        "horizontal" => CursorIcon::ColResize,
        _ => CursorIcon::RowResize,
    };

    let onmouseleave = move |_: MouseEvent| {
        *status.write() = HandleStatus::Idle;
        if !clicking() {
            platform.set_cursor(CursorIcon::default());
        }
    };

    let onmouseenter = move |e: MouseEvent| {
        e.stop_propagation();
        *status.write() = HandleStatus::Hovering;
        platform.set_cursor(cursor);
    };

    let onmousemove = move |e: MouseEvent| {
        if clicking() {
            if !allow_resizing() {
                return;
            }

            let coordinates = e.get_screen_coordinates();
            let mut registry = registry.write();

            let displacement_per: f32 = match registry.direction.as_str() {
                "horizontal" => {
                    let container_width = container_size.read().area.width();
                    let displacement = coordinates.x as f32 - size.read().area.min_x();
                    100. / container_width * displacement
                }
                _ => {
                    let container_height = container_size.read().area.height();
                    let displacement = coordinates.y as f32 - size.read().area.min_y();
                    100. / container_height * displacement
                }
            };

            let mut changed_panels = false;

            if displacement_per >= 0. {
                // Resizing to the right

                let mut acc_per = 0.0;

                // Resize panels to the right
                for next_item in &mut registry.registry[index..].iter_mut() {
                    if let Some(panel) = next_item.try_panel_mut() {
                        let old_size = panel.size;
                        let new_size = (panel.size - displacement_per).clamp(panel.min_size, 100.);

                        if panel.size != new_size {
                            changed_panels = true
                        }

                        panel.size = new_size;
                        acc_per -= new_size - old_size;

                        if old_size > panel.min_size {
                            break;
                        }
                    }
                }

                // Resize panels to the left
                for prev_item in &mut registry.registry[0..index].iter_mut().rev() {
                    if let Some(panel) = prev_item.try_panel_mut() {
                        let new_size = (panel.size + acc_per).clamp(panel.min_size, 100.);

                        if panel.size != new_size {
                            changed_panels = true
                        }

                        panel.size = new_size;
                        break;
                    }
                }
            } else {
                // Resizing to the left

                let mut acc_per = 0.0;

                // Resize panels to the left
                for prev_item in &mut registry.registry[0..index].iter_mut().rev() {
                    if let Some(panel) = prev_item.try_panel_mut() {
                        let old_size = panel.size;
                        let new_size = (panel.size + displacement_per).clamp(panel.min_size, 100.);

                        if panel.size != new_size {
                            changed_panels = true
                        }

                        panel.size = new_size;
                        acc_per += new_size - old_size;

                        if old_size > panel.min_size {
                            break;
                        }
                    }
                }

                // Resize panels to the right
                for next_item in &mut registry.registry[index..].iter_mut() {
                    if let Some(panel) = next_item.try_panel_mut() {
                        let new_size = (panel.size - acc_per).clamp(panel.min_size, 100.);

                        if panel.size != new_size {
                            changed_panels = true
                        }

                        panel.size = new_size;
                        break;
                    }
                }
            }

            if changed_panels {
                allow_resizing.set(false);
            }
        }
    };

    let onmousedown = move |e: MouseEvent| {
        e.stop_propagation();
        clicking.set(true);
    };

    let onclick = move |_: MouseEvent| {
        if clicking() {
            if *status.peek() != HandleStatus::Hovering {
                platform.set_cursor(CursorIcon::default());
            }
            clicking.set(false);
        }
    };

    let (width, height) = match registry.read().direction.as_str() {
        "horizontal" => ("4", "fill"),
        _ => ("fill", "4"),
    };

    let background = match status() {
        _ if clicking() => hover_background,
        HandleStatus::Hovering => hover_background,
        HandleStatus::Idle => background,
    };

    rsx!(rect {
        reference: node_reference,
        width: "{width}",
        height: "{height}",
        background: "{background}",
        onmousedown,
        onglobalclick: onclick,
        onmouseenter,
        onglobalmousemove: onmousemove,
        onmouseleave,
    })
}

#[cfg(test)]
mod test {
    use freya::prelude::*;
    use freya_testing::prelude::*;

    #[tokio::test]
    pub async fn resizable_container() {
        fn resizable_container_app() -> Element {
            rsx!(
                ResizableContainer {
                    ResizablePanel {
                        initial_size: 50.,
                        label {
                            "Panel 0"
                        }
                    }
                    ResizableHandle { }
                    ResizablePanel { // Panel 1
                        initial_size: 50.,
                        ResizableContainer {
                            direction: "horizontal",
                            ResizablePanel {
                                initial_size: 33.33,
                                label {
                                    "Panel 2"
                                }
                            }
                            ResizableHandle { }
                            ResizablePanel {
                                initial_size: 33.33,
                                label {
                                    "Panel 3"
                                }
                            }
                            ResizableHandle { }
                            ResizablePanel {
                                initial_size: 33.33,
                                label {
                                    "Panel 4"
                                }
                            }
                        }
                    }
                }
            )
        }

        let mut utils = launch_test(resizable_container_app);
        utils.wait_for_update().await;
        let root = utils.root();

        let container = root.get(0);
        let panel_0 = container.get(0);
        let panel_1 = container.get(2);
        let panel_2 = panel_1.get(0).get(0);
        let panel_3 = panel_1.get(0).get(2);
        let panel_4 = panel_1.get(0).get(4);

        assert_eq!(panel_0.layout().unwrap().area.height().round(), 248.0);
        assert_eq!(panel_1.layout().unwrap().area.height().round(), 248.0);
        assert_eq!(panel_2.layout().unwrap().area.width().round(), 164.0);
        assert_eq!(panel_3.layout().unwrap().area.width().round(), 164.0);
        assert_eq!(panel_4.layout().unwrap().area.width().round(), 164.0);

        // Vertical
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::MouseDown,
            cursor: (100.0, 250.0).into(),
            button: Some(MouseButton::Left),
        });
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::MouseMove,
            cursor: (100.0, 200.0).into(),
            button: Some(MouseButton::Left),
        });
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::MouseUp,
            cursor: (0.0, 0.0).into(),
            button: Some(MouseButton::Left),
        });
        utils.wait_for_update().await;

        assert_eq!(panel_0.layout().unwrap().area.height().round(), 200.0); // 250 - 50
        assert_eq!(panel_1.layout().unwrap().area.height().round(), 296.0); // 500 - 200 - 4

        // Horizontal
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::MouseDown,
            cursor: (167.0, 300.0).into(),
            button: Some(MouseButton::Left),
        });
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::MouseMove,
            cursor: (187.0, 300.0).into(),
            button: Some(MouseButton::Left),
        });
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::MouseUp,
            cursor: (0.0, 0.0).into(),
            button: Some(MouseButton::Left),
        });
        utils.wait_for_update().await;
        utils.wait_for_update().await;
        utils.wait_for_update().await;

        assert_eq!(panel_2.layout().unwrap().area.width().round(), 187.0); // 167 + 20
        assert_eq!(panel_3.layout().unwrap().area.width().round(), 141.0);
    }
}