lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
//! A row of a list that a finger swipes aside for what can be done with it, as a phone's lists have.
//!
//! [`SwipeRow`] goes around a row's content. Swiped towards the leading edge it shows its trailing actions,
//! and the other way its leading ones; let go far enough it stays open, a press on an action does it and
//! closes the row, and a swipe all the way does the first action at once.

use std::{sync::Arc, time::Duration};

use parking_lot::Mutex;

use crate::{
  animation::{Easing, Transition},
  app::{
    component::Component,
    ctx::Ctx,
    events::{GesturePhase, PanEvent},
    window::Haptic,
  },
  components::{Row, Stack, Text},
  core::{ElementRef, Signal},
  layout::{
    Alignment,
    layout_kind::Justify,
    text_style::{FontWeight, TextStyle},
  },
  node::{Element, color::Color, dimension::Dimension, transform::Transform2D},
  ui::{Recipe, Themed, engine_look::EngineLook, names},
};

const FILL: Dimension = Dimension::Pct(100.0);
/// No finger has the row.
const NO_DRAG: f32 = f32::MIN;

/// Something to do with a row, shown beside it when it is swiped. Its colors come from the theme, through the
/// recipe of [`SwipeRowStyle`] ([`SwipeRowPart`]), where it is made.
#[derive(Clone)]
pub struct SwipeAction {
  pub title: String,
  /// What stands over the title, or in its place when there is no title.
  pub icon: Option<Element>,
  pub background: Color,
  pub color: Color,
  pub on_press: Arc<dyn Fn() + Send + Sync>,
}

impl SwipeAction {
  pub fn new(title: impl Into<String>, on_press: impl Fn() + Send + Sync + 'static) -> Self {
    Self::of(SwipeRowPart::Action, title.into(), Arc::new(on_press))
  }

  /// An action that takes the row away, in the theme's destructive colors.
  pub fn destructive(title: impl Into<String>, on_press: impl Fn() + Send + Sync + 'static) -> Self {
    Self::of(SwipeRowPart::DestructiveAction, title.into(), Arc::new(on_press))
  }

  fn of(part: SwipeRowPart, title: String, on_press: Arc<dyn Fn() + Send + Sync>) -> Self {
    let look = EngineLook::of::<SwipeRowStyle>(&[]);
    let (background, color) = legacy_colors(part);
    Self {
      title,
      icon: None,
      background: look.background(part, background),
      color: look.foreground(part, color),
      on_press,
    }
  }

  pub fn background(mut self, color: Color) -> Self {
    self.background = color;
    self
  }

  pub fn color(mut self, color: Color) -> Self {
    self.color = color;
    self
  }

  pub fn icon(mut self, icon: impl Into<Element>) -> Self {
    self.icon = Some(icon.into());
    self
  }
}

/// The parts of the recipe that colors a [`SwipeAction`], kept under the name `phone_swipe_row` with
/// [`SwipeRowStyle`]: each has a fill and an ink.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SwipeRowPart {
  /// An action made with [`SwipeAction::new`].
  Action,
  /// An action made with [`SwipeAction::destructive`].
  DestructiveAction,
}

names!(SwipeRowPart {
  Action => "action",
  DestructiveAction => "destructive_action",
});

/// The colors of 0.62's actions, fill and ink: what the legacy theme gives, and what a theme with no recipe keeps.
fn legacy_colors(part: SwipeRowPart) -> (Color, Color) {
  let white = Color::new(255, 255, 255, 255);
  match part {
    SwipeRowPart::Action => (Color::new(0x8E, 0x8E, 0x93, 255), white),
    SwipeRowPart::DestructiveAction => (Color::new(0xFF, 0x3B, 0x30, 255), white),
  }
}

/// How a [`SwipeRow`] looks and moves. The colors of its actions come from the theme, through the recipe it
/// keeps under the name `phone_swipe_row` ([`SwipeRowPart`]): the design's roles, light or dark as the theme is,
/// and the colors of 0.62 in [`ThemeDefinition::legacy`](crate::app::theme::ThemeDefinition::legacy).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SwipeRowStyle {
  /// How wide each action is.
  pub action_width: f32,
  pub title_size: f32,
  /// A row swiped this share of its width does its first action at once; more than 1 never does.
  pub full_swipe: f32,
  /// How far ahead of where a finger let the row go it is taken to be going, in seconds of its speed.
  pub throw: f32,
  /// How long the row takes to open, close or go back. It follows a spring.
  pub duration: Duration,
  /// Whether the device ticks when a swipe goes far enough to do the first action.
  pub haptic: bool,
}

impl Themed for SwipeRowStyle {
  const NAME: &'static str = "phone_swipe_row";
  type Renderer = ();

  /// The design's (`pencil/lurq-design-system.pen`, Mobile/Swipe Row): an action that takes the row away in the
  /// destructive colors; another, which the board draws in the info color, in the muted foreground's grey with
  /// the background's ink, as neutral as the platform's.
  fn recipe() -> Recipe {
    use crate::app::theme::PaletteColor::{Background, Destructive, DestructiveForeground, MutedForeground};
    Recipe::new()
      .base(SwipeRowPart::Action, |s| {
        s.background(MutedForeground).foreground(Background)
      })
      .base(SwipeRowPart::DestructiveAction, |s| {
        s.background(Destructive).foreground(DestructiveForeground)
      })
  }
}

impl SwipeRowStyle {
  /// 0.62's colors: the recipe [`UiDefinition::legacy`](crate::ui::UiDefinition::legacy) gives the swipe row.
  pub(crate) fn legacy_recipe() -> Recipe {
    let mut recipe = Recipe::new();
    for part in SwipeRowPart::all() {
      let (background, color) = legacy_colors(*part);
      recipe = recipe.base(*part, |s| s.background(background).foreground(color));
    }
    recipe
  }
}

impl Default for SwipeRowStyle {
  fn default() -> Self {
    Self {
      action_width: 74.0,
      title_size: 15.0,
      full_swipe: 0.6,
      throw: 0.15,
      duration: Duration::from_millis(350),
      haptic: true,
    }
  }
}

#[derive(Clone, Default)]
pub struct SwipeRowProps {
  leading: Vec<SwipeAction>,
  trailing: Vec<SwipeAction>,
  style: SwipeRowStyle,
  open: Option<Signal<i8>>,
}

impl PartialEq for SwipeRowProps {
  fn eq(&self, _other: &Self) -> bool {
    // The actions are closures: a row is made again with its parent.
    false
  }
}

#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for SwipeRowProps {
  fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}

impl SwipeRowProps {
  pub fn new() -> Self {
    Self::default()
  }

  /// The actions shown at the row's trailing edge, the first of them at the edge: the one a swipe all the
  /// way does.
  pub fn trailing(mut self, actions: impl IntoIterator<Item = SwipeAction>) -> Self {
    self.trailing = actions.into_iter().collect();
    self
  }

  /// The actions shown at the row's leading edge, the first of them at the edge.
  pub fn leading(mut self, actions: impl IntoIterator<Item = SwipeAction>) -> Self {
    self.leading = actions.into_iter().collect();
    self
  }

  pub fn style(mut self, style: SwipeRowStyle) -> Self {
    self.style = style;
    self
  }

  /// Which side of the row is open, to read and to set: 0 for neither, -1 for the trailing actions and 1 for
  /// the leading ones. A list that lets one row be open at a time closes the others with it.
  pub fn open(mut self, open: Signal<i8>) -> Self {
    self.open = Some(open);
    self
  }
}

struct Held {
  /// Where the fingers were when they took the row, and where the row was then.
  from: f32,
  base: f32,
}

/// A row of a list with actions a swipe shows: the phone's. The board draws a design system's one (Mobile/Swipe
/// Row) that `lurq::ui` does not have yet; this one takes the theme's colors through [`SwipeRowStyle`].
pub struct SwipeRow {
  /// Which side is open, for a row whose props name no signal.
  open: Signal<i8>,
  /// How far a finger has the row from where it rests, or [`NO_DRAG`].
  drag: Signal<f32>,
  held: Arc<Mutex<Option<Held>>>,
  /// The speed a finger let the row go with, towards where it is going.
  velocity: Arc<Mutex<f64>>,
  /// The row as it is laid out: how wide it is, and how high, which its actions are too.
  row: ElementRef,
  height: Signal<f32>,
  /// Whether the content was out of its place, or on its way, at the last render: the actions stay under it
  /// until [`SETTLE`] after it went back.
  moved: Arc<Mutex<bool>>,
  /// Ends the time the content takes to go back, and has the row rendered again without its actions.
  settle: crate::app::ctx::Timeout,
  settled: Signal<u32>,
}

/// Longer than the content takes to spring back to its place: the actions are taken away under it after that.
const SETTLE: Duration = Duration::from_millis(1000);

impl SwipeRow {
  /// Around `content`, which is as high as the row is and paints its own background.
  pub fn mount(ctx: &mut Ctx, props: SwipeRowProps, content: impl Into<Element>) -> Element {
    ctx.mount_with::<Self>(props, vec![content.into()])
  }

  /// The same, told apart from its siblings by `key`: a row of a list that changes.
  pub fn mount_keyed(ctx: &mut Ctx, key: &str, props: SwipeRowProps, content: impl Into<Element>) -> Element {
    ctx.mount_keyed_with::<Self>(key, props, vec![content.into()])
  }
}

impl Component for SwipeRow {
  type Props = SwipeRowProps;

  fn create(ctx: &mut Ctx) -> Self {
    let settled = Signal::new(0u32);
    let settle = ctx.create_timeout(SETTLE, {
      let settled = settled.clone();
      move || settled.update(|times| *times = times.wrapping_add(1))
    });
    Self {
      moved: Arc::default(),
      settle,
      settled,
      open: Signal::new(0),
      drag: Signal::new(NO_DRAG),
      held: Arc::default(),
      velocity: Arc::default(),
      row: ElementRef::default(),
      height: Signal::new(0.0),
    }
  }

  fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
    let props = ctx.props::<SwipeRowProps>().clone();
    let style = props.style;
    let open = props.open.clone().unwrap_or_else(|| self.open.clone());
    let side = open.get();
    let drag = self.drag.get();
    let height = self.height.get();
    let (leading, trailing) = (
      props.leading.len() as f32 * style.action_width,
      props.trailing.len() as f32 * style.action_width,
    );
    // Where the content rests, and where a finger has it: past the actions it gives way less.
    let rest = match side {
      1 => leading,
      -1 => -trailing,
      _ => 0.0,
    };
    let dragged = drag != NO_DRAG;
    let at = if dragged { drag } else { rest };
    let pace = if dragged { Duration::ZERO } else { style.duration };
    // A row at rest has nothing under its content: an action there would show through at an edge of the content
    // that falls between two pixels. Out of its place, and while it goes back, the actions are there.
    self.settled.get();
    let out = dragged || at != 0.0;
    {
      let mut moved = self.moved.lock();
      if *moved && !out {
        self.settle.restart();
      }
      *moved = out;
    }
    let bare = !out && !self.settle.is_active();
    let curve = Easing::Spring {
      velocity: *self.velocity.lock(),
    };

    let close = {
      let open = open.clone();
      move || {
        if open.get_untracked() != 0 {
          open.set(0);
        }
      }
    };
    // The actions of a side, the first at the edge, as wide together as the content is out of the way.
    let actions = |list: &[SwipeAction], at_end: bool, shown: f32| {
      let mut row = Row::new().height(FILL);
      let ordered: Vec<&SwipeAction> = if at_end {
        list.iter().rev().collect()
      } else {
        list.iter().collect()
      };
      let each = if list.is_empty() {
        0.0
      } else {
        (shown / list.len() as f32).max(style.action_width)
      };
      for action in ordered {
        let (press, close) = (action.on_press.clone(), close.clone());
        let mut inside = crate::components::Column::new()
          .align_items(Alignment::Center)
          .spacing(4.0);
        if let Some(icon) = &action.icon {
          inside = inside.child(icon.clone());
        }
        if !action.title.is_empty() {
          inside = inside.child(
            Text::styled(
              &action.title,
              TextStyle {
                font_size: style.title_size,
                weight: FontWeight::Medium,
                color: action.color,
                ..TextStyle::default()
              },
            )
            .nowrap(),
          );
        }
        row = row.child(
          Row::new()
            .width(each)
            .height(FILL)
            .align_items(Alignment::Center)
            .justify(Justify::Center)
            .background(action.background)
            .child(inside)
            .on_click(move |_| {
              close();
              press();
            }),
        );
      }
      row
    };

    let mut content = Stack::new()
      .width(FILL)
      .transform(Transform2D::translate(at, 0.0))
      .transition(Transition::transform().duration(pace).easing(curve));
    for child in ctx.children() {
      content = content.child(child.clone());
    }
    let content = content
      // A press on an open row closes it, and is not the row's own.
      .on_click({
        let close = close.clone();
        let open = open.clone();
        move |event: crate::app::events::MouseEvent| {
          if open.get_untracked() != 0 {
            event.stop_propagation();
            close();
          }
        }
      })
      .on_pan({
        let (held, drag, velocity) = (self.held.clone(), self.drag.clone(), self.velocity.clone());
        let (open, row) = (open.clone(), self.row.clone());
        let (first_leading, first_trailing) = (
          props.leading.first().map(|action| action.on_press.clone()),
          props.trailing.first().map(|action| action.on_press.clone()),
        );
        let window = ctx.window();
        move |event: PanEvent| match event.phase {
          GesturePhase::Start => {
            if event.fingers != 1 || event.translation_x.abs() <= event.translation_y.abs() {
              return;
            }
            // A row with nothing on the side it is swiped to is not the row's to take.
            let towards = if event.translation_x < 0.0 { trailing } else { leading };
            if towards <= 0.0 && rest == 0.0 {
              return;
            }
            // The row's: the finger does not scroll the list, nor click.
            event.prevent_default();
            event.stop_propagation();
            *held.lock() = Some(Held {
              from: event.translation_x,
              base: rest,
            });
            drag.set(rest);
          }
          GesturePhase::Change => {
            let held = held.lock();
            if let Some(held) = &*held {
              event.stop_propagation();
              let x = held.base + event.translation_x - held.from;
              // Past its actions the row gives way less; with none on that side, hardly at all.
              let limit = if x < 0.0 { trailing } else { leading };
              let over = (x.abs() - limit).max(0.0);
              let give = if limit > 0.0 { 1.0 } else { 0.15 };
              drag.set(x.signum() * (x.abs().min(limit) + over * give));
            }
          }
          GesturePhase::End => {
            let Some(held) = held.lock().take() else {
              return;
            };
            event.stop_propagation();
            let x = held.base + event.translation_x - held.from;
            let width = row.width().max(1.0);
            let thrown = x + event.velocity_x * style.throw;
            // All the way: the first action of that side, at once.
            let all_the_way = x.abs() > width * style.full_swipe;
            let goes: i8 = if thrown < -trailing / 2.0 && trailing > 0.0 {
              -1
            } else if thrown > leading / 2.0 && leading > 0.0 {
              1
            } else {
              0
            };
            let target = match goes {
              1 => leading,
              -1 => -trailing,
              _ => 0.0,
            };
            let left = target - x;
            *velocity.lock() = if left.abs() > 1.0 {
              f64::from((event.velocity_x * style.duration.as_secs_f32() / left).max(0.0))
            } else {
              0.0
            };
            drag.set(NO_DRAG);
            if all_the_way && goes != 0 {
              let first = if goes < 0 { &first_trailing } else { &first_leading };
              if open.get_untracked() != 0 {
                open.set(0);
              }
              if style.haptic {
                window.haptic(Haptic::Medium);
              }
              if let Some(first) = first {
                first();
              }
            } else if open.get_untracked() != goes {
              open.set(goes);
            }
          }
        }
      });

    Stack::new()
      .ref_element(self.row.clone())
      .width(FILL)
      .clip()
      .child(
        // As high as the content was last laid out: the row is as high as its content, and its actions
        // fill it.
        if bare {
          Row::new().width(FILL).height(height)
        } else {
          Row::new()
            .width(FILL)
            .height(height)
            .child(actions(&props.leading, false, at.max(0.0)))
            .child(Row::new().flex(1.0))
            .child(actions(&props.trailing, true, (-at).max(0.0)))
        },
      )
      .child(content)
  }
  fn after_layout(&self) {
    if self.row.is_attached() {
      let height = self.row.rect().3;
      if (self.height.get_untracked() - height).abs() > 0.25 {
        self.height.set(height);
      }
    }
  }
}