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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! Rust port of [Floating UI](https://floating-ui.com/).
//!
//! Utility functions shared across Floating UI packages. You may use these functions in your own projects, but are subject to breaking changes.
//!
//! See [@floating-ui/utils](https://www.npmjs.com/package/@floating-ui/utils) for the original package.

#[cfg(feature = "dom")]
pub mod dom;

use dyn_clone::DynClone;
use serde::{Deserialize, Serialize};

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Alignment {
    Start,
    End,
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Side {
    Top,
    Right,
    Bottom,
    Left,
}

impl Side {
    pub fn opposite(&self) -> Side {
        match self {
            Side::Top => Side::Bottom,
            Side::Right => Side::Left,
            Side::Bottom => Side::Top,
            Side::Left => Side::Right,
        }
    }

    pub fn axis(&self) -> Axis {
        match self {
            Side::Top => Axis::Y,
            Side::Right => Axis::X,
            Side::Bottom => Axis::Y,
            Side::Left => Axis::X,
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum AlignedPlacement {
    TopStart,
    TopEnd,
    RightStart,
    RightEnd,
    BottomStart,
    BottomEnd,
    LeftStart,
    LeftEnd,
}

#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Placement {
    Top,
    TopStart,
    TopEnd,
    Right,
    RightStart,
    RightEnd,
    Bottom,
    BottomStart,
    BottomEnd,
    Left,
    LeftStart,
    LeftEnd,
}

impl Placement {
    pub fn alignment(&self) -> Option<Alignment> {
        match self {
            Placement::Top => None,
            Placement::TopStart => Some(Alignment::Start),
            Placement::TopEnd => Some(Alignment::End),
            Placement::Right => None,
            Placement::RightStart => Some(Alignment::Start),
            Placement::RightEnd => Some(Alignment::End),
            Placement::Bottom => None,
            Placement::BottomStart => Some(Alignment::Start),
            Placement::BottomEnd => Some(Alignment::End),
            Placement::Left => None,
            Placement::LeftStart => Some(Alignment::Start),
            Placement::LeftEnd => Some(Alignment::End),
        }
    }

    pub fn side(&self) -> Side {
        match self {
            Placement::Top => Side::Top,
            Placement::TopStart => Side::Top,
            Placement::TopEnd => Side::Top,
            Placement::Right => Side::Right,
            Placement::RightStart => Side::Right,
            Placement::RightEnd => Side::Right,
            Placement::Bottom => Side::Bottom,
            Placement::BottomStart => Side::Bottom,
            Placement::BottomEnd => Side::Bottom,
            Placement::Left => Side::Left,
            Placement::LeftStart => Side::Left,
            Placement::LeftEnd => Side::Left,
        }
    }

    pub fn opposite(&self) -> Placement {
        match self {
            Placement::Top => Placement::Bottom,
            Placement::TopStart => Placement::BottomStart,
            Placement::TopEnd => Placement::BottomEnd,
            Placement::Right => Placement::Left,
            Placement::RightStart => Placement::LeftStart,
            Placement::RightEnd => Placement::LeftEnd,
            Placement::Bottom => Placement::Top,
            Placement::BottomStart => Placement::TopStart,
            Placement::BottomEnd => Placement::TopEnd,
            Placement::Left => Placement::Right,
            Placement::LeftStart => Placement::RightStart,
            Placement::LeftEnd => Placement::RightEnd,
        }
    }

    pub fn opposite_alignment(&self) -> Placement {
        match self {
            Placement::Top => Placement::Top,
            Placement::TopStart => Placement::TopEnd,
            Placement::TopEnd => Placement::TopStart,
            Placement::Right => Placement::Right,
            Placement::RightStart => Placement::RightEnd,
            Placement::RightEnd => Placement::RightStart,
            Placement::Bottom => Placement::Bottom,
            Placement::BottomStart => Placement::BottomEnd,
            Placement::BottomEnd => Placement::BottomStart,
            Placement::Left => Placement::Left,
            Placement::LeftStart => Placement::LeftEnd,
            Placement::LeftEnd => Placement::LeftStart,
        }
    }
}

impl From<(Side, Option<Alignment>)> for Placement {
    fn from(value: (Side, Option<Alignment>)) -> Self {
        match value {
            (Side::Top, None) => Placement::Top,
            (Side::Top, Some(Alignment::Start)) => Placement::TopStart,
            (Side::Top, Some(Alignment::End)) => Placement::TopEnd,
            (Side::Right, None) => Placement::Right,
            (Side::Right, Some(Alignment::Start)) => Placement::RightStart,
            (Side::Right, Some(Alignment::End)) => Placement::RightEnd,
            (Side::Bottom, None) => Placement::Bottom,
            (Side::Bottom, Some(Alignment::Start)) => Placement::BottomStart,
            (Side::Bottom, Some(Alignment::End)) => Placement::BottomEnd,
            (Side::Left, None) => Placement::Left,
            (Side::Left, Some(Alignment::Start)) => Placement::LeftStart,
            (Side::Left, Some(Alignment::End)) => Placement::LeftEnd,
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Strategy {
    Absolute,
    Fixed,
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Axis {
    X,
    Y,
}

impl Axis {
    pub fn opposite(&self) -> Axis {
        match self {
            Axis::X => Axis::Y,
            Axis::Y => Axis::X,
        }
    }

    pub fn length(&self) -> Length {
        match self {
            Axis::X => Length::Width,
            Axis::Y => Length::Height,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Coords {
    pub x: f64,
    pub y: f64,
}

impl Coords {
    pub fn new(value: f64) -> Self {
        Self { x: value, y: value }
    }

    pub fn axis(&self, axis: Axis) -> f64 {
        match axis {
            Axis::X => self.x,
            Axis::Y => self.y,
        }
    }

    pub fn update_axis<F>(&mut self, axis: Axis, update: F)
    where
        F: Fn(f64) -> f64,
    {
        match axis {
            Axis::X => {
                self.x = update(self.x);
            }
            Axis::Y => {
                self.y = update(self.y);
            }
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Length {
    Width,
    Height,
}

#[derive(Clone, Debug)]
pub struct Dimensions {
    pub width: f64,
    pub height: f64,
}

impl Dimensions {
    pub fn length(&self, length: Length) -> f64 {
        match length {
            Length::Width => self.width,
            Length::Height => self.height,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SideObject {
    pub top: f64,
    pub right: f64,
    pub bottom: f64,
    pub left: f64,
}

impl SideObject {
    pub fn side(&self, side: Side) -> f64 {
        match side {
            Side::Top => self.top,
            Side::Right => self.right,
            Side::Bottom => self.bottom,
            Side::Left => self.left,
        }
    }
}

#[derive(Clone, Debug)]
pub struct PartialSideObject {
    pub top: Option<f64>,
    pub right: Option<f64>,
    pub bottom: Option<f64>,
    pub left: Option<f64>,
}

#[derive(Clone, Debug)]
pub struct Rect {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

impl Rect {
    pub fn axis(&self, axis: Axis) -> f64 {
        match axis {
            Axis::X => self.x,
            Axis::Y => self.y,
        }
    }

    pub fn length(&self, length: Length) -> f64 {
        match length {
            Length::Width => self.width,
            Length::Height => self.height,
        }
    }
}

#[derive(Clone, Debug)]
pub enum Padding {
    All(f64),
    PerSide(PartialSideObject),
}

#[derive(Clone, Debug)]
pub struct ClientRectObject {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    pub top: f64,
    pub right: f64,
    pub bottom: f64,
    pub left: f64,
}

impl From<Rect> for ClientRectObject {
    fn from(value: Rect) -> Self {
        ClientRectObject {
            x: value.x,
            y: value.y,
            width: value.width,
            height: value.height,
            top: value.y,
            right: value.x + value.width,
            bottom: value.y + value.height,
            left: value.x,
        }
    }
}

cfg_if::cfg_if! {
    if #[cfg(feature = "dom")] {
        impl ClientRectObject {
            pub fn from_dom_rect_list(value: web_sys::DomRectList) -> Vec<Self> {
                (0..value.length())
                    .filter_map(|i| value.item(i).map(ClientRectObject::from))
                    .collect()
            }
        }

        impl From<web_sys::DomRect> for ClientRectObject {
            fn from(value: web_sys::DomRect) -> Self {
                Self {
                    x: value.x(),
                    y: value.y(),
                    width: value.width(),
                    height: value.height(),
                    top: value.top(),
                    right: value.right(),
                    bottom: value.bottom(),
                    left: value.left(),
                }
            }
        }
    }
}

#[derive(Clone, Debug)]
pub struct ElementRects {
    pub reference: Rect,
    pub floating: Rect,
}

/// Custom positioning reference element.
///
/// See <https://floating-ui.com/docs/virtual-elements> for the original documentation.
pub trait VirtualElement<Element>: DynClone {
    fn get_bounding_client_rect(&self) -> ClientRectObject;

    fn get_client_rects(&self) -> Option<Vec<ClientRectObject>>;

    fn context_element(&self) -> Option<Element>;
}

dyn_clone::clone_trait_object!(<Element> VirtualElement<Element>);

pub trait GetBoundingClientRectCloneable: DynClone {
    fn call(&self) -> ClientRectObject;
}

impl<F> GetBoundingClientRectCloneable for F
where
    F: Fn() -> ClientRectObject + Clone,
{
    fn call(&self) -> ClientRectObject {
        self()
    }
}

dyn_clone::clone_trait_object!(GetBoundingClientRectCloneable);

pub trait GetClientRectsCloneable: DynClone {
    fn call(&self) -> Vec<ClientRectObject>;
}

impl<F> GetClientRectsCloneable for F
where
    F: Fn() -> Vec<ClientRectObject> + Clone,
{
    fn call(&self) -> Vec<ClientRectObject> {
        self()
    }
}

dyn_clone::clone_trait_object!(GetClientRectsCloneable);

#[derive(Clone)]
pub struct DefaultVirtualElement<Element: Clone> {
    pub get_bounding_client_rect: Box<dyn GetBoundingClientRectCloneable>,
    pub get_client_rects: Option<Box<dyn GetClientRectsCloneable>>,
    pub context_element: Option<Element>,
}

impl<Element: Clone> DefaultVirtualElement<Element> {
    pub fn new(get_bounding_client_rect: Box<dyn GetBoundingClientRectCloneable>) -> Self {
        DefaultVirtualElement {
            get_bounding_client_rect,
            get_client_rects: None,
            context_element: None,
        }
    }

    pub fn get_bounding_client_rect(
        mut self,
        get_bounding_client_rect: Box<dyn GetBoundingClientRectCloneable>,
    ) -> Self {
        self.get_bounding_client_rect = get_bounding_client_rect;
        self
    }

    pub fn get_client_rects(mut self, get_client_rects: Box<dyn GetClientRectsCloneable>) -> Self {
        self.get_client_rects = Some(get_client_rects);
        self
    }

    pub fn context_element(mut self, context_element: Element) -> Self {
        self.context_element = Some(context_element);
        self
    }
}

// impl<Element: Clone> Clone for DefaultVirtualElement<Element> {
//     fn clone(&self) -> Self {
//         Self {
//             get_bounding_client_rect: dyn_clone::clone_box(&*self.get_bounding_client_rect),
//             context_element: self.context_element.clone(),
//         }
//     }
// }

impl<Element: Clone> VirtualElement<Element> for DefaultVirtualElement<Element> {
    fn get_bounding_client_rect(&self) -> ClientRectObject {
        (self.get_bounding_client_rect).call()
    }

    fn get_client_rects(&self) -> Option<Vec<ClientRectObject>> {
        self.get_client_rects
            .as_ref()
            .map(|get_client_rects| get_client_rects.call())
    }

    fn context_element(&self) -> Option<Element> {
        self.context_element.clone()
    }
}

#[derive(Clone)]
pub enum ElementOrVirtual<'a, Element: Clone> {
    Element(&'a Element),
    VirtualElement(Box<dyn VirtualElement<Element>>),
}

impl<'a, Element: Clone> ElementOrVirtual<'a, Element> {
    pub fn resolve(self) -> Option<Element> {
        match self {
            ElementOrVirtual::Element(element) => Some(element.clone()),
            ElementOrVirtual::VirtualElement(virtal_element) => virtal_element.context_element(),
        }
    }
}

impl<'a, Element: Clone> From<&'a Element> for ElementOrVirtual<'a, Element> {
    fn from(value: &'a Element) -> Self {
        ElementOrVirtual::Element(value)
    }
}

impl<'a, Element: Clone> From<Box<dyn VirtualElement<Element>>> for ElementOrVirtual<'a, Element> {
    fn from(value: Box<dyn VirtualElement<Element>>) -> Self {
        ElementOrVirtual::VirtualElement(value)
    }
}

impl<'a, Element: Clone> From<&'a OwnedElementOrVirtual<Element>>
    for ElementOrVirtual<'a, Element>
{
    fn from(value: &'a OwnedElementOrVirtual<Element>) -> Self {
        match value {
            OwnedElementOrVirtual::Element(element) => ElementOrVirtual::Element(element),
            OwnedElementOrVirtual::VirtualElement(virtual_element) => {
                ElementOrVirtual::VirtualElement(virtual_element.clone())
            }
        }
    }
}

#[derive(Clone)]
pub enum OwnedElementOrVirtual<Element> {
    Element(Element),
    VirtualElement(Box<dyn VirtualElement<Element>>),
}

impl<Element> OwnedElementOrVirtual<Element> {
    pub fn resolve(self) -> Option<Element> {
        match self {
            OwnedElementOrVirtual::Element(element) => Some(element),
            OwnedElementOrVirtual::VirtualElement(virtal_element) => {
                virtal_element.context_element()
            }
        }
    }
}

impl<Element> From<Element> for OwnedElementOrVirtual<Element> {
    fn from(value: Element) -> Self {
        OwnedElementOrVirtual::Element(value)
    }
}

impl<Element> From<Box<dyn VirtualElement<Element>>> for OwnedElementOrVirtual<Element> {
    fn from(value: Box<dyn VirtualElement<Element>>) -> Self {
        OwnedElementOrVirtual::VirtualElement(value)
    }
}

#[derive(Clone, Debug)]
pub enum ElementOrWindow<'a, Element, Window> {
    Element(&'a Element),
    Window(&'a Window),
}

impl<'a, Element, Window> From<&'a OwnedElementOrWindow<Element, Window>>
    for ElementOrWindow<'a, Element, Window>
{
    fn from(value: &'a OwnedElementOrWindow<Element, Window>) -> Self {
        match value {
            OwnedElementOrWindow::Element(element) => ElementOrWindow::Element(element),
            OwnedElementOrWindow::Window(window) => ElementOrWindow::Window(window),
        }
    }
}

#[derive(Clone, Debug)]
pub enum OwnedElementOrWindow<Element, Window> {
    Element(Element),
    Window(Window),
}

pub const ALL_PLACEMENTS: [Placement; 12] = [
    Placement::Top,
    Placement::TopStart,
    Placement::TopEnd,
    Placement::Right,
    Placement::RightStart,
    Placement::RightEnd,
    Placement::Bottom,
    Placement::BottomStart,
    Placement::BottomEnd,
    Placement::Left,
    Placement::LeftStart,
    Placement::LeftEnd,
];

pub const ALL_SIDES: [Side; 4] = [Side::Top, Side::Right, Side::Bottom, Side::Left];

pub fn clamp(start: f64, value: f64, end: f64) -> f64 {
    value.min(end).max(start)
}

pub fn get_side(placement: Placement) -> Side {
    placement.side()
}

pub fn get_alignment(placement: Placement) -> Option<Alignment> {
    placement.alignment()
}

pub fn get_placement(side: Side, alignment: Option<Alignment>) -> Placement {
    (side, alignment).into()
}

pub fn get_opposite_axis(axis: Axis) -> Axis {
    axis.opposite()
}

pub fn get_axis_length(axis: Axis) -> Length {
    axis.length()
}

pub fn get_side_axis(placement: Placement) -> Axis {
    placement.side().axis()
}

pub fn get_alignment_axis(placement: Placement) -> Axis {
    get_opposite_axis(get_side_axis(placement))
}

pub fn get_alignment_sides(
    placement: Placement,
    rects: &ElementRects,
    rtl: Option<bool>,
) -> (Side, Side) {
    let alignment = get_alignment(placement);
    let alignment_axis = get_alignment_axis(placement);
    let length = get_axis_length(alignment_axis);

    let mut main_alignment_side = match (alignment_axis, alignment) {
        (Axis::X, Some(Alignment::Start)) => match rtl {
            Some(true) => Side::Left,
            _ => Side::Right,
        },
        (Axis::X, _) => match rtl {
            Some(true) => Side::Right,
            _ => Side::Left,
        },
        (Axis::Y, Some(Alignment::Start)) => Side::Bottom,
        (Axis::Y, _) => Side::Top,
    };

    if rects.reference.length(length) > rects.floating.length(length) {
        main_alignment_side = get_opposite_side(main_alignment_side);
    }

    (main_alignment_side, get_opposite_side(main_alignment_side))
}

pub fn get_expanded_placements(placement: Placement) -> Vec<Placement> {
    let opposite_placement = get_opposite_placement(placement);

    vec![
        get_opposite_alignment_placement(placement),
        opposite_placement,
        get_opposite_alignment_placement(opposite_placement),
    ]
}

pub fn get_opposite_alignment_placement(placement: Placement) -> Placement {
    placement.opposite_alignment()
}

pub fn get_side_list(side: Side, is_start: bool, rtl: Option<bool>) -> Vec<Side> {
    match side {
        Side::Top | Side::Bottom => match rtl {
            Some(true) => match is_start {
                true => vec![Side::Right, Side::Left],
                false => vec![Side::Left, Side::Right],
            },
            _ => match is_start {
                true => vec![Side::Left, Side::Right],
                false => vec![Side::Right, Side::Left],
            },
        },
        Side::Right | Side::Left => match is_start {
            true => vec![Side::Top, Side::Bottom],
            false => vec![Side::Bottom, Side::Top],
        },
    }
}

pub fn get_opposite_side(side: Side) -> Side {
    side.opposite()
}

pub fn get_opposite_axis_placements(
    placement: Placement,
    flip_alignment: bool,
    direction: Option<Alignment>,
    rtl: Option<bool>,
) -> Vec<Placement> {
    let alignment = get_alignment(placement);
    let side_list = get_side_list(
        get_side(placement),
        direction.is_some_and(|d| d == Alignment::Start),
        rtl,
    );

    let mut list: Vec<Placement> = side_list
        .into_iter()
        .map(|side| get_placement(side, alignment))
        .collect();

    if flip_alignment {
        let mut opposite_list: Vec<Placement> = list
            .clone()
            .into_iter()
            .map(get_opposite_alignment_placement)
            .collect();

        list.append(&mut opposite_list);
    }

    list
}

pub fn get_opposite_placement(placement: Placement) -> Placement {
    placement.opposite()
}

pub fn expand_padding_object(padding: PartialSideObject) -> SideObject {
    SideObject {
        top: padding.top.unwrap_or(0.0),
        right: padding.right.unwrap_or(0.0),
        bottom: padding.bottom.unwrap_or(0.0),
        left: padding.left.unwrap_or(0.0),
    }
}

pub fn get_padding_object(padding: Padding) -> SideObject {
    match padding {
        Padding::All(padding) => SideObject {
            top: padding,
            right: padding,
            bottom: padding,
            left: padding,
        },
        Padding::PerSide(padding) => expand_padding_object(padding),
    }
}

pub fn rect_to_client_rect(rect: Rect) -> ClientRectObject {
    ClientRectObject {
        x: rect.x,
        y: rect.y,
        width: rect.width,
        height: rect.height,
        top: rect.y,
        right: rect.x + rect.width,
        bottom: rect.y + rect.height,
        left: rect.x,
    }
}