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
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! The text forms of a data grid's values an app stores between runs: the arrangement of its columns, its sort and
//! its groups open. Each reads back to an equal value, through `parse` or `FromStr`, and is stored as that text by
//! the persistent storage, as a dock's state is.

use std::{fmt, str::FromStr, sync::Arc};

use super::{
  ColumnFilter, ColumnLayout, ColumnPin, ColumnPlace, GridQuery, GroupKey, SortDirection, TableFilters, TableSort,
  TextMatch,
};
use crate::core::Date;

/// What `FromStr` returns for text that is not the text form of a table's value: a [`ColumnLayout`], a
/// [`TableSort`], a [`GroupKey`] or a list of them.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TableTextError;

impl fmt::Display for TableTextError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str("not the text form of a table's value")
  }
}

impl std::error::Error for TableTextError {}

fn write_string(out: &mut String, text: &str) {
  out.push('"');
  for c in text.chars() {
    if c == '"' || c == '\\' {
      out.push('\\');
    }
    out.push(c);
  }
  out.push('"');
}

fn space(out: &mut String) {
  if !out.is_empty() && !out.ends_with('(') {
    out.push(' ');
  }
}

#[derive(Clone, Debug, PartialEq)]
enum Token {
  Open,
  Close,
  Colon,
  Text(String),
  Word(String),
}

fn tokenize(text: &str) -> Option<Vec<Token>> {
  let mut tokens = Vec::new();
  let mut chars = text.chars().peekable();
  while let Some(&c) = chars.peek() {
    match c {
      c if c.is_whitespace() => {
        chars.next();
      }
      '(' | ')' | ':' => {
        chars.next();
        tokens.push(match c {
          '(' => Token::Open,
          ')' => Token::Close,
          _ => Token::Colon,
        });
      }
      '"' => {
        chars.next();
        let mut string = String::new();
        loop {
          match chars.next()? {
            '"' => break,
            '\\' => match chars.next()? {
              escaped @ ('"' | '\\') => string.push(escaped),
              _ => return None,
            },
            c => string.push(c),
          }
        }
        tokens.push(Token::Text(string));
      }
      _ => {
        let mut word = String::new();
        while let Some(&c) = chars.peek() {
          if c.is_whitespace() || matches!(c, '(' | ')' | ':' | '"') {
            break;
          }
          word.push(c);
          chars.next();
        }
        tokens.push(Token::Word(word));
      }
    }
  }
  Some(tokens)
}

struct Reader {
  tokens: Vec<Token>,
  at: usize,
}

impl Reader {
  fn new(text: &str) -> Option<Self> {
    Some(Self {
      tokens: tokenize(text)?,
      at: 0,
    })
  }

  fn done(&self) -> bool {
    self.at >= self.tokens.len()
  }

  fn peek(&self) -> Option<&Token> {
    self.tokens.get(self.at)
  }

  fn next(&mut self) -> Option<Token> {
    let token = self.tokens.get(self.at).cloned();
    self.at += 1;
    token
  }

  fn expect(&mut self, token: Token) -> Option<()> {
    (self.next()? == token).then_some(())
  }

  fn text(&mut self) -> Option<String> {
    match self.next()? {
      Token::Text(text) => Some(text),
      _ => None,
    }
  }

  fn word(&mut self) -> Option<String> {
    match self.next()? {
      Token::Word(word) => Some(word),
      _ => None,
    }
  }

  /// `name(`, where the next word is `name`.
  fn opens(&mut self, name: &str) -> Option<()> {
    (self.word()? == name).then_some(())?;
    self.expect(Token::Open)
  }

  /// The quoted texts up to the `)` that closes them.
  fn texts_to_close(&mut self) -> Option<Vec<String>> {
    let mut texts = Vec::new();
    loop {
      match self.next()? {
        Token::Close => return Some(texts),
        Token::Text(text) => texts.push(text),
        _ => return None,
      }
    }
  }
}

// The arrangement of the columns.

impl ColumnLayout {
  /// The arrangement as text that `parse` reads back to the same arrangement: each column in its order as
  /// `column(..)` of its id quoted, then `hidden`, `fit`, `width:` and its width, `pin:start` or `pin:end` where it
  /// is so.
  ///
  /// ```
  /// use lurq::ui::{ColumnLayout, ColumnPin, ColumnPlace};
  ///
  /// let layout = ColumnLayout {
  ///   columns: vec![
  ///     ColumnPlace { id: "size".into(), hidden: false, width: Some(150.0), fit: false, pin: ColumnPin::None },
  ///     ColumnPlace { id: "name".into(), hidden: false, width: None, fit: false, pin: ColumnPin::Start },
  ///     ColumnPlace { id: "status".into(), hidden: true, width: None, fit: false, pin: ColumnPin::None },
  ///   ],
  /// };
  /// assert_eq!(layout.to_text(), r#"column("size" width:150) column("name" pin:start) column("status" hidden)"#);
  /// assert_eq!(ColumnLayout::parse(&layout.to_text()), Some(layout));
  /// ```
  pub fn to_text(&self) -> String {
    let mut out = String::new();
    for place in &self.columns {
      space(&mut out);
      out.push_str("column(");
      write_string(&mut out, &place.id);
      if place.hidden {
        out.push_str(" hidden");
      }
      if place.fit {
        out.push_str(" fit");
      }
      if let Some(width) = place.width {
        out.push_str(&format!(" width:{width}"));
      }
      match place.pin {
        ColumnPin::Start => out.push_str(" pin:start"),
        ColumnPin::End => out.push_str(" pin:end"),
        ColumnPin::None => {}
      }
      out.push(')');
    }
    out
  }

  /// The arrangement `text` writes (see `to_text`), as written: `None` for text that is not the form. The grid makes
  /// it valid for its columns as it shows it; [`valid`](Self::valid) does it for the app.
  pub fn parse(text: &str) -> Option<ColumnLayout> {
    let mut reader = Reader::new(text)?;
    let mut columns = Vec::new();
    while !reader.done() {
      reader.opens("column")?;
      let mut place = ColumnPlace {
        id: Arc::from(reader.text()?),
        hidden: false,
        width: None,
        fit: false,
        pin: ColumnPin::None,
      };
      loop {
        match reader.next()? {
          Token::Close => break,
          Token::Word(word) => match word.as_str() {
            "hidden" => place.hidden = true,
            "fit" => place.fit = true,
            "width" => {
              reader.expect(Token::Colon)?;
              place.width = Some(reader.word()?.parse().ok()?);
            }
            "pin" => {
              reader.expect(Token::Colon)?;
              place.pin = match reader.word()?.as_str() {
                "start" => ColumnPin::Start,
                "end" => ColumnPin::End,
                _ => return None,
              };
            }
            _ => return None,
          },
          _ => return None,
        }
      }
      columns.push(place);
    }
    Some(ColumnLayout { columns })
  }

  /// The arrangement brought to the columns `ids` the app has now, in their order: a column it no longer has is
  /// left out, a column named twice is kept once, a width that is no width is the column's own, and a column the
  /// arrangement does not name takes its place after the one before it among `ids`.
  pub fn valid<S: AsRef<str>>(self, ids: impl IntoIterator<Item = S>) -> Self {
    let ids: Vec<String> = ids.into_iter().map(|id| id.as_ref().to_owned()).collect();
    let mut places: Vec<ColumnPlace> = Vec::with_capacity(ids.len());
    for mut place in self.columns {
      if !ids.iter().any(|id| **id == *place.id) || places.iter().any(|kept| kept.id == place.id) {
        continue;
      }
      place.width = place.width.filter(|width| width.is_finite() && *width >= 0.0);
      places.push(place);
    }
    for (index, id) in ids.iter().enumerate() {
      if places.iter().any(|place| *place.id == **id) {
        continue;
      }
      let at = ids[..index]
        .iter()
        .rev()
        .find_map(|before| places.iter().position(|place| *place.id == **before))
        .map_or(0, |before| before + 1);
      places.insert(
        at,
        ColumnPlace {
          id: Arc::from(id.as_str()),
          hidden: false,
          width: None,
          fit: false,
          pin: ColumnPin::None,
        },
      );
    }
    ColumnLayout { columns: places }
  }
}

impl fmt::Display for ColumnLayout {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(&self.to_text())
  }
}

impl FromStr for ColumnLayout {
  type Err = TableTextError;

  fn from_str(text: &str) -> Result<Self, Self::Err> {
    ColumnLayout::parse(text).ok_or(TableTextError)
  }
}

// The sort.

impl TableSort {
  /// The sort as text that `parse` reads back to the same sort: the column's id quoted, then `ascending` or
  /// `descending`: `"name" descending`.
  pub fn to_text(&self) -> String {
    let mut out = String::new();
    write_string(&mut out, &self.column);
    out.push_str(match self.direction {
      SortDirection::Ascending => " ascending",
      SortDirection::Descending => " descending",
    });
    out
  }

  /// The sort `text` writes (see `to_text`): `None` for text that is not the form.
  pub fn parse(text: &str) -> Option<TableSort> {
    let mut reader = Reader::new(text)?;
    let column = reader.text()?;
    let direction = match reader.word()?.as_str() {
      "ascending" => SortDirection::Ascending,
      "descending" => SortDirection::Descending,
      _ => return None,
    };
    reader.done().then(|| TableSort {
      column: Arc::from(column),
      direction,
    })
  }
}

impl TableSort {
  /// A sort of several columns as text, the first first: each column's text in turn, which `parse_list` reads
  /// back. No columns is no text.
  pub fn list_to_text(sorts: &[TableSort]) -> String {
    sorts.iter().map(TableSort::to_text).collect::<Vec<_>>().join(" ")
  }

  /// The sort `text` writes (see `list_to_text`): `None` for text that is not the form.
  pub fn parse_list(text: &str) -> Option<Vec<TableSort>> {
    if text.trim().is_empty() {
      return Some(Vec::new());
    }
    let mut reader = Reader::new(text)?;
    let mut sorts = Vec::new();
    while !reader.done() {
      let column = reader.text()?;
      let direction = match reader.word()?.as_str() {
        "ascending" => SortDirection::Ascending,
        "descending" => SortDirection::Descending,
        _ => return None,
      };
      sorts.push(TableSort {
        column: Arc::from(column),
        direction,
      });
    }
    Some(sorts)
  }
}

impl fmt::Display for TableSort {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(&self.to_text())
  }
}

impl FromStr for TableSort {
  type Err = TableTextError;

  fn from_str(text: &str) -> Result<Self, Self::Err> {
    TableSort::parse(text).ok_or(TableTextError)
  }
}

// The filters.

impl TableFilters {
  /// The filters as text that `parse` reads back to the same filters: `filter(..)` for each, its column's id
  /// quoted, then what it lets through: `contains`, `starts_with` or `equals` and a quoted text; `at_least:` and
  /// `at_most:` a number; `from:` and `to:` a day; `in` and the quoted values; `is:true` or `is:false`.
  ///
  /// ```
  /// use lurq::ui::{ColumnFilter, TableFilters};
  ///
  /// let filters = TableFilters::new()
  ///   .with("name", ColumnFilter::contains("lurq"))
  ///   .with("size", ColumnFilter::at_least(10.0))
  ///   .with("status", ColumnFilter::one_of(["Passing", "Failed"]));
  /// assert_eq!(
  ///   filters.to_text(),
  ///   r#"filter("name" contains "lurq") filter("size" at_least:10) filter("status" in "Passing" "Failed")"#
  /// );
  /// assert_eq!(TableFilters::parse(&filters.to_text()), Some(filters));
  /// ```
  pub fn to_text(&self) -> String {
    let mut parts = Vec::new();
    for (id, filter) in self.iter() {
      let mut out = String::from("filter(");
      write_string(&mut out, id);
      match filter {
        ColumnFilter::Text { how, text } => {
          out.push_str(match how {
            TextMatch::Contains => " contains ",
            TextMatch::StartsWith => " starts_with ",
            TextMatch::Equals => " equals ",
          });
          write_string(&mut out, text);
        }
        ColumnFilter::Number { at_least, at_most } => {
          if let Some(low) = at_least {
            out.push_str(&format!(" at_least:{low}"));
          }
          if let Some(high) = at_most {
            out.push_str(&format!(" at_most:{high}"));
          }
        }
        ColumnFilter::Date { from, to } => {
          if let Some(from) = from {
            out.push_str(&format!(" from:{from}"));
          }
          if let Some(to) = to {
            out.push_str(&format!(" to:{to}"));
          }
        }
        ColumnFilter::Set(values) => {
          out.push_str(" in");
          for value in values {
            space(&mut out);
            write_string(&mut out, value);
          }
        }
        ColumnFilter::Bool(value) => out.push_str(if *value { " is:true" } else { " is:false" }),
      }
      out.push(')');
      parts.push(out);
    }
    parts.join(" ")
  }

  /// The filters `text` writes (see `to_text`): `None` for text that is not the form. No text is no filters.
  pub fn parse(text: &str) -> Option<TableFilters> {
    let mut reader = Reader::new(text)?;
    let mut filters = TableFilters::new();
    while !reader.done() {
      reader.opens("filter")?;
      let (id, filter) = read_filter(&mut reader)?;
      filters.set(&id, filter);
    }
    Some(filters)
  }
}

/// A filter after its `filter(`: its column's id and what it lets through, up to its `)`.
fn read_filter(reader: &mut Reader) -> Option<(String, ColumnFilter)> {
  let id = reader.text()?;
  let filter = match reader.word()?.as_str() {
    word @ ("contains" | "starts_with" | "equals") => {
      let text = reader.text()?;
      reader.expect(Token::Close)?;
      ColumnFilter::Text {
        how: match word {
          "contains" => TextMatch::Contains,
          "starts_with" => TextMatch::StartsWith,
          _ => TextMatch::Equals,
        },
        text,
      }
    }
    "in" => ColumnFilter::Set(reader.texts_to_close()?),
    first => {
      // Pairs of a name and a value, up to the close.
      let mut pairs = vec![(first.to_owned(), {
        reader.expect(Token::Colon)?;
        reader.word()?
      })];
      loop {
        match reader.next()? {
          Token::Close => break,
          Token::Word(name) => {
            reader.expect(Token::Colon)?;
            pairs.push((name, reader.word()?));
          }
          _ => return None,
        }
      }
      let value = |name: &str| {
        pairs
          .iter()
          .find(|(held, _)| held == name)
          .map(|(_, value)| value.clone())
      };
      match pairs[0].0.as_str() {
        "at_least" | "at_most" => {
          let number = |name: &str| -> Option<Option<f64>> {
            match value(name) {
              None => Some(None),
              Some(text) => text.parse().ok().map(Some),
            }
          };
          ColumnFilter::Number {
            at_least: number("at_least")?,
            at_most: number("at_most")?,
          }
        }
        "from" | "to" => ColumnFilter::Date {
          from: match value("from") {
            Some(text) => Some(parse_date(&text)?),
            None => None,
          },
          to: match value("to") {
            Some(text) => Some(parse_date(&text)?),
            None => None,
          },
        },
        "is" => match value("is")?.as_str() {
          "true" => ColumnFilter::Bool(true),
          "false" => ColumnFilter::Bool(false),
          _ => return None,
        },
        _ => return None,
      }
    }
  };
  Some((id, filter))
}

/// A day written `2026-11-12`.
fn parse_date(text: &str) -> Option<Date> {
  let mut parts = text.splitn(3, '-');
  let year = parts.next()?.parse().ok()?;
  let month = parts.next()?.parse().ok()?;
  let day = parts.next()?.parse().ok()?;
  Date::new(year, month, day)
}

impl GridQuery {
  /// The query as text that `parse` reads back to the same query: `sort(..)` of its sort's columns in turn, its
  /// filters' text, and `search(..)` of its query, each where there is one.
  ///
  /// ```
  /// use lurq::ui::{ColumnFilter, GridQuery, TableFilters, TableSort};
  ///
  /// let query = GridQuery {
  ///   sort: vec![TableSort::descending("size")],
  ///   filters: TableFilters::new().with("status", ColumnFilter::one_of(["Failed"])),
  ///   search: "canvas".into(),
  /// };
  /// assert_eq!(
  ///   query.to_text(),
  ///   r#"sort("size" descending) filter("status" in "Failed") search("canvas")"#
  /// );
  /// assert_eq!(GridQuery::parse(&query.to_text()), Some(query));
  /// ```
  pub fn to_text(&self) -> String {
    let mut parts = Vec::new();
    if !self.sort.is_empty() {
      parts.push(format!("sort({})", TableSort::list_to_text(&self.sort)));
    }
    if !self.filters.is_empty() {
      parts.push(self.filters.to_text());
    }
    if !self.search.is_empty() {
      let mut out = String::from("search(");
      write_string(&mut out, &self.search);
      out.push(')');
      parts.push(out);
    }
    parts.join(" ")
  }

  /// The query `text` writes (see `to_text`): `None` for text that is not the form. No text is the query of every
  /// row in its order.
  pub fn parse(text: &str) -> Option<GridQuery> {
    let mut reader = Reader::new(text)?;
    let mut query = GridQuery::default();
    while !reader.done() {
      match reader.word()?.as_str() {
        "sort" => {
          reader.expect(Token::Open)?;
          loop {
            match reader.next()? {
              Token::Close => break,
              Token::Text(column) => {
                let direction = match reader.word()?.as_str() {
                  "ascending" => SortDirection::Ascending,
                  "descending" => SortDirection::Descending,
                  _ => return None,
                };
                query.sort.push(TableSort {
                  column: Arc::from(column),
                  direction,
                });
              }
              _ => return None,
            }
          }
        }
        "filter" => {
          reader.expect(Token::Open)?;
          let (id, filter) = read_filter(&mut reader)?;
          query.filters.set(&id, filter);
        }
        "search" => {
          reader.expect(Token::Open)?;
          query.search = reader.text()?;
          reader.expect(Token::Close)?;
        }
        _ => return None,
      }
    }
    Some(query)
  }
}

impl fmt::Display for GridQuery {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(&self.to_text())
  }
}

impl FromStr for GridQuery {
  type Err = TableTextError;

  fn from_str(text: &str) -> Result<Self, Self::Err> {
    GridQuery::parse(text).ok_or(TableTextError)
  }
}

impl fmt::Display for TableFilters {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(&self.to_text())
  }
}

impl FromStr for TableFilters {
  type Err = TableTextError;

  fn from_str(text: &str) -> Result<Self, Self::Err> {
    TableFilters::parse(text).ok_or(TableTextError)
  }
}

// The groups.

impl GroupKey {
  /// The group as text that `parse` reads back to the same group: `group(..)` of its values quoted:
  /// `group("Passing" "Ada")`.
  pub fn to_text(&self) -> String {
    let mut out = String::from("group(");
    for value in &self.values {
      space(&mut out);
      write_string(&mut out, value);
    }
    out.push(')');
    out
  }

  /// The group `text` writes (see `to_text`): `None` for text that is not the form.
  pub fn parse(text: &str) -> Option<GroupKey> {
    let mut groups = GroupKey::parse_list(text)?;
    (groups.len() == 1).then(|| groups.remove(0))
  }

  /// Groups as text, the groups open of a grid: each group's text in turn, which `parse_list` reads back.
  pub fn list_to_text(groups: &[GroupKey]) -> String {
    groups.iter().map(GroupKey::to_text).collect::<Vec<_>>().join(" ")
  }

  /// The groups `text` writes (see `list_to_text`): `None` for text that is not the form.
  pub fn parse_list(text: &str) -> Option<Vec<GroupKey>> {
    let mut reader = Reader::new(text)?;
    let mut groups = Vec::new();
    while !reader.done() {
      reader.opens("group")?;
      groups.push(GroupKey {
        values: reader.texts_to_close()?,
      });
    }
    Some(groups)
  }
}

impl fmt::Display for GroupKey {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(&self.to_text())
  }
}

impl FromStr for GroupKey {
  type Err = TableTextError;

  fn from_str(text: &str) -> Result<Self, Self::Err> {
    GroupKey::parse(text).ok_or(TableTextError)
  }
}

// Stored as their text forms, the way a string is.

#[cfg(feature = "persistent_storage")]
mod stored {
  use super::{ColumnLayout, GridQuery, GroupKey, TableFilters, TableSort};
  use crate::persistent_storage::{IntoPersistentValue, PersistentValue};

  fn text(bytes: &[u8]) -> Option<String> {
    <String as PersistentValue>::decode_persistent_value(bytes)
  }

  /// Stored as its text form, the way a string is.
  impl PersistentValue for ColumnLayout {
    fn decode_persistent_value(bytes: &[u8]) -> Option<Self> {
      ColumnLayout::parse(&text(bytes)?)
    }
  }

  /// Stored as its text form, the way a string is.
  impl IntoPersistentValue for ColumnLayout {
    fn encode_persistent_value(self) -> Vec<u8> {
      self.to_text().encode_persistent_value()
    }
  }

  /// Stored as its text form, the way a string is.
  impl PersistentValue for TableSort {
    fn decode_persistent_value(bytes: &[u8]) -> Option<Self> {
      TableSort::parse(&text(bytes)?)
    }
  }

  /// Stored as its text form, the way a string is.
  impl IntoPersistentValue for TableSort {
    fn encode_persistent_value(self) -> Vec<u8> {
      self.to_text().encode_persistent_value()
    }
  }

  /// A grid's sort, none as no text.
  impl PersistentValue for Option<TableSort> {
    fn decode_persistent_value(bytes: &[u8]) -> Option<Self> {
      let text = text(bytes)?;
      if text.trim().is_empty() {
        return Some(None);
      }
      Some(Some(TableSort::parse(&text)?))
    }
  }

  /// A grid's sort, none as no text.
  impl IntoPersistentValue for Option<TableSort> {
    fn encode_persistent_value(self) -> Vec<u8> {
      self
        .map(|sort| sort.to_text())
        .unwrap_or_default()
        .encode_persistent_value()
    }
  }

  /// A grid's sort of several columns, as its list's text.
  impl PersistentValue for Vec<TableSort> {
    fn decode_persistent_value(bytes: &[u8]) -> Option<Self> {
      TableSort::parse_list(&text(bytes)?)
    }
  }

  /// A grid's sort of several columns, as its list's text.
  impl IntoPersistentValue for Vec<TableSort> {
    fn encode_persistent_value(self) -> Vec<u8> {
      TableSort::list_to_text(&self).encode_persistent_value()
    }
  }

  /// The query of a grid over rows on demand, as its text.
  impl PersistentValue for GridQuery {
    fn decode_persistent_value(bytes: &[u8]) -> Option<Self> {
      GridQuery::parse(&text(bytes)?)
    }
  }

  /// The query of a grid over rows on demand, as its text.
  impl IntoPersistentValue for GridQuery {
    fn encode_persistent_value(self) -> Vec<u8> {
      self.to_text().encode_persistent_value()
    }
  }

  /// A grid's filters, as their text.
  impl PersistentValue for TableFilters {
    fn decode_persistent_value(bytes: &[u8]) -> Option<Self> {
      TableFilters::parse(&text(bytes)?)
    }
  }

  /// A grid's filters, as their text.
  impl IntoPersistentValue for TableFilters {
    fn encode_persistent_value(self) -> Vec<u8> {
      self.to_text().encode_persistent_value()
    }
  }

  /// A grid's groups open, as their list's text.
  impl PersistentValue for Vec<GroupKey> {
    fn decode_persistent_value(bytes: &[u8]) -> Option<Self> {
      GroupKey::parse_list(&text(bytes)?)
    }
  }

  /// A grid's groups open, as their list's text.
  impl IntoPersistentValue for Vec<GroupKey> {
    fn encode_persistent_value(self) -> Vec<u8> {
      GroupKey::list_to_text(&self).encode_persistent_value()
    }
  }
}