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
use std::fmt::Debug;

use dyn_clone::DynClone;
use floating_ui_utils::{clamp, get_opposite_axis, get_side_axis, Axis, Coords, Side};
use serde::{Deserialize, Serialize};

use crate::{
    detect_overflow::{detect_overflow, DetectOverflowOptions},
    middleware::{OffsetData, OFFSET_NAME},
    types::{
        Derivable, DerivableFn, Middleware, MiddlewareReturn, MiddlewareState,
        MiddlewareWithOptions,
    },
};

/// Name of the [`Shift`] middleware.
pub const SHIFT_NAME: &str = "shift";

/// Limiter used by [`Shift`] middleware. Limits the shifting done in order to prevent detachment.
pub trait Limiter<Element: Clone, Window: Clone>: DynClone {
    fn compute(&self, state: MiddlewareState<Element, Window>) -> Coords;
}

dyn_clone::clone_trait_object!(<Element, Window> Limiter<Element, Window>);

/// Options for [`Shift`] middleware.
#[derive(Clone)]
pub struct ShiftOptions<Element: Clone, Window: Clone> {
    /// Options for [`detect_overflow`].
    ///
    /// Defaults to [`DetectOverflowOptions::default`].
    pub detect_overflow: Option<DetectOverflowOptions<Element>>,

    /// The axis that runs along the alignment of the floating element. Determines whether overflow along this axis is checked to perform shifting.
    ///
    /// Defaults to `true`.
    pub main_axis: Option<bool>,

    /// The axis that runs along the side of the floating element. Determines whether overflow along this axis is checked to perform shifting.
    ///
    /// Defaults to `false`.
    pub cross_axis: Option<bool>,

    /// Accepts a limiter that limits the shifting done in order to prevent detachment.
    ///
    /// Defaults to [`DefaultLimiter`].
    pub limiter: Option<Box<dyn Limiter<Element, Window>>>,
}

impl<Element: Clone, Window: Clone> ShiftOptions<Element, Window> {
    /// Set `detect_overflow` option.
    pub fn detect_overflow(mut self, value: DetectOverflowOptions<Element>) -> Self {
        self.detect_overflow = Some(value);
        self
    }

    /// Set `main_axis` option.
    pub fn main_axis(mut self, value: bool) -> Self {
        self.main_axis = Some(value);
        self
    }

    /// Set `cross_axis` option.
    pub fn cross_axis(mut self, value: bool) -> Self {
        self.cross_axis = Some(value);
        self
    }

    /// Set `limiter` option.
    pub fn limiter(mut self, value: Box<dyn Limiter<Element, Window>>) -> Self {
        self.limiter = Some(value);
        self
    }
}

impl<Element: Clone, Window: Clone> Default for ShiftOptions<Element, Window> {
    fn default() -> Self {
        Self {
            detect_overflow: Default::default(),
            main_axis: Default::default(),
            cross_axis: Default::default(),
            limiter: Default::default(),
        }
    }
}

/// Data stored by [`Shift`] middleware.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ShiftData {
    pub x: f64,
    pub y: f64,
}

/// Optimizes the visibility of the floating element by shifting it in order to keep it in view when it will overflow the clipping boundary.
///
/// See <https://floating-ui.com/docs/shift> for the original documentation.
pub struct Shift<'a, Element: Clone, Window: Clone> {
    options: Derivable<'a, Element, Window, ShiftOptions<Element, Window>>,
}

impl<'a, Element: Clone, Window: Clone> Shift<'a, Element, Window> {
    /// Constructs a new instance of this middleware.
    pub fn new(options: ShiftOptions<Element, Window>) -> Self {
        Shift {
            options: options.into(),
        }
    }

    /// Constructs a new instance of this middleware with derivable options.
    pub fn new_derivable(
        options: Derivable<'a, Element, Window, ShiftOptions<Element, Window>>,
    ) -> Self {
        Shift { options }
    }

    /// Constructs a new instance of this middleware with derivable options function.
    pub fn new_derivable_fn(
        options: DerivableFn<'a, Element, Window, ShiftOptions<Element, Window>>,
    ) -> Self {
        Shift {
            options: options.into(),
        }
    }
}

impl<'a, Element: Clone, Window: Clone> Clone for Shift<'a, Element, Window> {
    fn clone(&self) -> Self {
        Self {
            options: self.options.clone(),
        }
    }
}

impl<'a, Element: Clone, Window: Clone> Middleware<Element, Window> for Shift<'a, Element, Window> {
    fn name(&self) -> &'static str {
        SHIFT_NAME
    }

    fn compute(&self, state: MiddlewareState<Element, Window>) -> MiddlewareReturn {
        let options = self.options.evaluate(state.clone());

        let MiddlewareState {
            x, y, placement, ..
        } = state;

        let check_main_axis = options.main_axis.unwrap_or(true);
        let check_cross_axis = options.cross_axis.unwrap_or(false);
        #[allow(clippy::unwrap_or_default)]
        let limiter = options.limiter.unwrap_or(Box::<DefaultLimiter>::default());

        let coords = Coords { x, y };
        let overflow = detect_overflow(
            MiddlewareState {
                elements: state.elements.clone(),
                ..state
            },
            options.detect_overflow.unwrap_or_default(),
        );
        let cross_axis = get_side_axis(placement);
        let main_axis = get_opposite_axis(cross_axis);

        let mut main_axis_coord = coords.axis(main_axis);
        let mut cross_axis_coord = coords.axis(cross_axis);

        if check_main_axis {
            let min_side = match main_axis {
                Axis::X => Side::Left,
                Axis::Y => Side::Top,
            };
            let max_side = match main_axis {
                Axis::X => Side::Right,
                Axis::Y => Side::Bottom,
            };
            let min = main_axis_coord + overflow.side(min_side);
            let max = main_axis_coord - overflow.side(max_side);

            main_axis_coord = clamp(min, main_axis_coord, max);
        }

        if check_cross_axis {
            let min_side = match cross_axis {
                Axis::X => Side::Left,
                Axis::Y => Side::Top,
            };
            let max_side = match cross_axis {
                Axis::X => Side::Right,
                Axis::Y => Side::Bottom,
            };
            let min = cross_axis_coord + overflow.side(min_side);
            let max = cross_axis_coord - overflow.side(max_side);

            cross_axis_coord = clamp(min, cross_axis_coord, max);
        }

        let limited_coords = limiter.compute(MiddlewareState {
            x: match main_axis {
                Axis::X => main_axis_coord,
                Axis::Y => cross_axis_coord,
            },
            y: match main_axis {
                Axis::X => cross_axis_coord,
                Axis::Y => main_axis_coord,
            },
            ..state
        });

        MiddlewareReturn {
            x: Some(limited_coords.x),
            y: Some(limited_coords.y),
            data: Some(
                serde_json::to_value(ShiftData {
                    x: limited_coords.x - x,
                    y: limited_coords.y - y,
                })
                .expect("Data should be valid JSON."),
            ),
            reset: None,
        }
    }
}

impl<'a, Element: Clone, Window: Clone>
    MiddlewareWithOptions<Element, Window, ShiftOptions<Element, Window>>
    for Shift<'a, Element, Window>
{
    fn options(&self) -> &Derivable<Element, Window, ShiftOptions<Element, Window>> {
        &self.options
    }
}

/// Default [`Limiter`], which doesn't limit shifting.
#[derive(Clone, Debug, Default)]
pub struct DefaultLimiter;

impl<Element: Clone, Window: Clone> Limiter<Element, Window> for DefaultLimiter {
    fn compute(&self, state: MiddlewareState<Element, Window>) -> Coords {
        Coords {
            x: state.x,
            y: state.y,
        }
    }
}

/// Axes configuration for [`LimitShiftOffset`].
#[derive(Clone, Default, Debug)]
pub struct LimitShiftOffsetValues {
    pub main_axis: Option<f64>,

    pub cross_axis: Option<f64>,
}

impl LimitShiftOffsetValues {
    /// Set `main_axis` option.
    pub fn main_axis(mut self, value: f64) -> Self {
        self.main_axis = Some(value);
        self
    }

    /// Set `cross_axis` option.
    pub fn cross_axis(mut self, value: f64) -> Self {
        self.cross_axis = Some(value);
        self
    }
}

/// Offset configuration for [`LimitShiftOptions`].
#[derive(Clone, Debug)]
pub enum LimitShiftOffset {
    Value(f64),
    Values(LimitShiftOffsetValues),
}

impl Default for LimitShiftOffset {
    fn default() -> Self {
        LimitShiftOffset::Value(0.0)
    }
}

/// Options for [`LimitShift`] limiter.
#[derive(Clone)]
pub struct LimitShiftOptions<'a, Element: Clone, Window: Clone> {
    pub offset: Option<Derivable<'a, Element, Window, LimitShiftOffset>>,

    pub main_axis: Option<bool>,

    pub cross_axis: Option<bool>,
}

impl<'a, Element: Clone, Window: Clone> LimitShiftOptions<'a, Element, Window> {
    /// Set `offset` option.
    pub fn offset(mut self, value: LimitShiftOffset) -> Self {
        self.offset = Some(value.into());
        self
    }

    /// Set `offset` option with derivable offset.
    pub fn offset_derivable(
        mut self,
        value: Derivable<'a, Element, Window, LimitShiftOffset>,
    ) -> Self {
        self.offset = Some(value);
        self
    }

    /// Set `offset` option with derivable offset function.
    pub fn offset_derivable_fn(
        mut self,
        value: DerivableFn<'a, Element, Window, LimitShiftOffset>,
    ) -> Self {
        self.offset = Some(value.into());
        self
    }

    /// Set `main_axis` option.
    pub fn main_axis(mut self, value: bool) -> Self {
        self.main_axis = Some(value);
        self
    }

    /// Set `cross_axis` option.
    pub fn cross_axis(mut self, value: bool) -> Self {
        self.cross_axis = Some(value);
        self
    }
}

impl<'a, Element: Clone, Window: Clone> Default for LimitShiftOptions<'a, Element, Window> {
    fn default() -> Self {
        Self {
            offset: Default::default(),
            main_axis: Default::default(),
            cross_axis: Default::default(),
        }
    }
}

/// Built-in [`Limiter`], that will stop [`Shift`] at a certain point.
#[derive(Clone, Default)]
pub struct LimitShift<'a, Element: Clone, Window: Clone> {
    options: LimitShiftOptions<'a, Element, Window>,
}

impl<'a, Element: Clone, Window: Clone> LimitShift<'a, Element, Window> {
    pub fn new(options: LimitShiftOptions<'a, Element, Window>) -> Self {
        LimitShift { options }
    }
}

impl<'a, Element: Clone, Window: Clone> Limiter<Element, Window>
    for LimitShift<'a, Element, Window>
{
    fn compute(&self, state: MiddlewareState<Element, Window>) -> Coords {
        let MiddlewareState {
            x,
            y,
            placement,
            rects,
            middleware_data,
            ..
        } = state;

        let offset = self
            .options
            .offset
            .clone()
            .unwrap_or(Derivable::Value(LimitShiftOffset::default()));
        let check_main_axis = self.options.main_axis.unwrap_or(true);
        let check_cross_axis = self.options.cross_axis.unwrap_or(true);

        let coords = Coords { x, y };
        let cross_axis = get_side_axis(placement);
        let main_axis = get_opposite_axis(cross_axis);

        let mut main_axis_coord = coords.axis(main_axis);
        let mut cross_axis_coord = coords.axis(cross_axis);

        let raw_offset = offset.evaluate(state.clone());
        let (computed_main_axis, computed_cross_axis) = match raw_offset {
            LimitShiftOffset::Value(value) => (value, 0.0),
            LimitShiftOffset::Values(values) => (
                values.main_axis.unwrap_or(0.0),
                values.cross_axis.unwrap_or(0.0),
            ),
        };

        if check_main_axis {
            let len = main_axis.length();
            let limit_min =
                rects.reference.axis(main_axis) - rects.floating.length(len) + computed_main_axis;
            let limit_max =
                rects.reference.axis(main_axis) + rects.reference.length(len) - computed_main_axis;

            main_axis_coord = clamp(limit_min, main_axis_coord, limit_max);
        }

        if check_cross_axis {
            let len = main_axis.length();
            let is_origin_side = match placement.side() {
                Side::Top | Side::Left => true,
                Side::Bottom | Side::Right => false,
            };

            let data: Option<OffsetData> = middleware_data.get_as(OFFSET_NAME);
            let data_cross_axis = data.map_or(0.0, |data| data.diff_coords.axis(cross_axis));

            let limit_min = rects.reference.axis(cross_axis) - rects.floating.length(len)
                + match is_origin_side {
                    true => data_cross_axis,
                    false => 0.0,
                }
                + match is_origin_side {
                    true => 0.0,
                    false => computed_cross_axis,
                };
            let limit_max = rects.reference.axis(cross_axis)
                + rects.reference.length(len)
                + match is_origin_side {
                    true => 0.0,
                    false => data_cross_axis,
                }
                - match is_origin_side {
                    true => computed_cross_axis,
                    false => 0.0,
                };

            cross_axis_coord = clamp(limit_min, cross_axis_coord, limit_max);
        }

        Coords {
            x: match main_axis {
                Axis::X => main_axis_coord,
                Axis::Y => cross_axis_coord,
            },
            y: match main_axis {
                Axis::X => cross_axis_coord,
                Axis::Y => main_axis_coord,
            },
        }
    }
}