promkit-core 0.2.0

Core library for promkit
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
use std::{
    collections::VecDeque,
    fmt,
    ops::{Deref, DerefMut},
};

use crossterm::style::{Attribute, ContentStyle};
use unicode_width::UnicodeWidthChar;

/// Represents a single grapheme (character) with its display width and optional styling.
///
/// This structure is similar to `Grapheme` but includes styling information directly.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StyledGrapheme {
    ch: char,
    width: usize,
    style: ContentStyle,
}

impl From<char> for StyledGrapheme {
    fn from(ch: char) -> Self {
        Self {
            ch,
            width: UnicodeWidthChar::width(ch).unwrap_or(0),
            style: ContentStyle::default(),
        }
    }
}

impl fmt::Display for StyledGraphemes {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for styled_grapheme in self.iter() {
            write!(f, "{}", styled_grapheme.ch)?;
        }
        Ok(())
    }
}

impl StyledGrapheme {
    pub fn new(ch: char, style: ContentStyle) -> Self {
        Self {
            ch,
            width: UnicodeWidthChar::width(ch).unwrap_or(0),
            style,
        }
    }

    pub fn width(&self) -> usize {
        self.width
    }

    pub fn apply_style(&mut self, style: ContentStyle) {
        self.style = style;
    }
}

/// A collection of `StyledGrapheme` instances.
///
/// This structure supports operations like calculating the total display width of the collection
/// and generating a display representation that respects the applied styles.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct StyledGraphemes(pub VecDeque<StyledGrapheme>);

impl Deref for StyledGraphemes {
    type Target = VecDeque<StyledGrapheme>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for StyledGraphemes {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl FromIterator<StyledGraphemes> for StyledGraphemes {
    fn from_iter<I: IntoIterator<Item = StyledGraphemes>>(iter: I) -> Self {
        let concatenated = iter
            .into_iter()
            .flat_map(|g| g.0.into_iter())
            .collect::<VecDeque<StyledGrapheme>>();
        StyledGraphemes(concatenated)
    }
}

impl<'a> FromIterator<&'a StyledGraphemes> for StyledGraphemes {
    fn from_iter<I: IntoIterator<Item = &'a StyledGraphemes>>(iter: I) -> Self {
        let concatenated = iter
            .into_iter()
            .flat_map(|g| g.0.iter().cloned())
            .collect::<VecDeque<StyledGrapheme>>();
        StyledGraphemes(concatenated)
    }
}

impl FromIterator<StyledGrapheme> for StyledGraphemes {
    fn from_iter<I: IntoIterator<Item = StyledGrapheme>>(iter: I) -> Self {
        let mut g = StyledGraphemes::default();
        for i in iter {
            g.push_back(i);
        }
        g
    }
}

impl<S: AsRef<str>> From<S> for StyledGraphemes {
    fn from(string: S) -> Self {
        Self::from_str(string, ContentStyle::default())
    }
}

impl fmt::Debug for StyledGraphemes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for styled_grapheme in self.iter() {
            write!(f, "{}", styled_grapheme.ch)?;
        }
        Ok(())
    }
}

impl StyledGraphemes {
    pub fn from_str<S: AsRef<str>>(string: S, style: ContentStyle) -> Self {
        string
            .as_ref()
            .chars()
            .map(|ch| StyledGrapheme::new(ch, style))
            .collect()
    }

    /// Returns a `Vec<char>` containing the characters of all `Grapheme` instances in the collection.
    pub fn chars(&self) -> Vec<char> {
        self.0.iter().map(|grapheme| grapheme.ch).collect()
    }

    /// Calculates the total display width of all `Grapheme` instances in the collection.
    pub fn widths(&self) -> usize {
        self.0.iter().map(|grapheme| grapheme.width).sum()
    }

    /// Replaces all occurrences of a substring `from` with another substring `to` within the `StyledGraphemes`.
    pub fn replace<S: AsRef<str>>(mut self, from: S, to: S) -> Self {
        let from_len = from.as_ref().chars().count();
        let to_len = to.as_ref().chars().count();

        let mut offset = 0;
        let diff = from_len.abs_diff(to_len);

        let pos = self.find_all(from);

        for p in pos {
            let adjusted_pos = if to_len > from_len {
                p + offset
            } else {
                p.saturating_sub(offset)
            };
            self.replace_range(adjusted_pos..adjusted_pos + from_len, &to);
            offset += diff;
        }

        self
    }

    /// Replaces the specified range with the given string.
    pub fn replace_range<S: AsRef<str>>(&mut self, range: std::ops::Range<usize>, replacement: S) {
        // Remove the specified range.
        for _ in range.clone() {
            self.0.remove(range.start);
        }

        // Insert the replacement at the start of the range.
        let replacement_graphemes: StyledGraphemes = replacement.as_ref().into();
        for grapheme in replacement_graphemes.0.iter().rev() {
            self.0.insert(range.start, grapheme.clone());
        }
    }

    /// Applies a given style to all `StyledGrapheme` instances within the collection.
    pub fn apply_style(mut self, style: ContentStyle) -> Self {
        for grapheme in &mut self.0 {
            grapheme.apply_style(style);
        }
        self
    }

    /// Applies a given style to a specific `StyledGrapheme` at the specified index.
    pub fn apply_style_at(mut self, idx: usize, style: ContentStyle) -> Self {
        if let Some(grapheme) = self.0.get_mut(idx) {
            grapheme.apply_style(style);
        }
        self
    }

    /// Finds all occurrences of a query string within the StyledGraphemes and returns their start indices.
    pub fn find_all<S: AsRef<str>>(&self, query: S) -> Vec<usize> {
        let query_str = query.as_ref();
        if query_str.is_empty() {
            return Vec::new();
        }

        let mut indices = Vec::new();
        let mut pos = 0;
        let query_chars: Vec<char> = query_str.chars().collect();
        let query_len = query_chars.len();

        // Iterate through each grapheme in self
        while pos + query_len <= self.0.len() {
            let mut match_found = true;
            for (i, query_char) in query_chars.iter().enumerate() {
                if self.0[pos + i].ch != *query_char {
                    match_found = false;
                    break;
                }
            }
            if match_found {
                indices.push(pos);
                pos += 1; // Move to the next position even after a match
            } else {
                pos += 1; // Check the next position
            }
        }

        indices
    }

    /// Highlights all occurrences of a specified query string
    /// within the `StyledGraphemes` collection by applying a given style.
    ///
    /// # Returns
    /// An `Option<Self>` which is:
    /// - `Some(Self)`:
    ///     - with the style applied to all occurrences of the query if the query is found.
    ///     - unchanged if the query string is empty.
    /// - `None`: if the query string is not found in the collection.
    pub fn highlight<S: AsRef<str>>(mut self, query: S, style: ContentStyle) -> Option<Self> {
        let query_str = query.as_ref();
        if query_str.is_empty() {
            return Some(self);
        }

        let indices = self.find_all(query_str);
        if indices.is_empty() {
            return None;
        }

        let query_len = query_str.chars().count();

        for &start_index in &indices {
            for i in start_index..start_index + query_len {
                if let Some(grapheme) = self.0.get_mut(i) {
                    grapheme.apply_style(style);
                }
            }
        }

        Some(self)
    }

    /// Applies a given attribute to all `StyledGrapheme` instances within the collection.
    pub fn apply_attribute(mut self, attr: Attribute) -> Self {
        for styled_grapheme in &mut self.0 {
            styled_grapheme.style.attributes.set(attr);
        }
        self
    }

    /// Returns a displayable format of the styled graphemes.
    pub fn styled_display(&self) -> StyledGraphemesDisplay<'_> {
        StyledGraphemesDisplay {
            styled_graphemes: self,
        }
    }

    /// Organizes the `StyledGraphemes` into a matrix format based on specified width and height,
    /// considering an offset for pagination or scrolling.
    pub fn matrixify(
        &self,
        width: usize,
        height: usize,
        offset: usize,
    ) -> (Vec<StyledGraphemes>, usize) {
        let mut all = VecDeque::new();
        let mut row = StyledGraphemes::default();
        for styled in self.iter() {
            let width_with_next_char = row.iter().fold(0, |mut layout, g| {
                layout += g.width;
                layout
            }) + styled.width;
            if !row.is_empty() && width < width_with_next_char {
                all.push_back(row);
                row = StyledGraphemes::default();
            }
            if width >= styled.width {
                row.push_back(styled.clone());
            }
        }
        if !row.is_empty() {
            all.push_back(row);
        }

        if all.is_empty() {
            return (vec![], 0);
        }

        let mut offset = std::cmp::min(offset, all.len().saturating_sub(1));

        // Adjust the start and end rows based on the offset and height
        while all.len() > height && offset < all.len() {
            if offset > 0 {
                all.pop_front();
                offset -= 1;
            } else {
                all.pop_back();
            }
        }

        (Vec::from(all), offset)
    }
}

pub struct StyledGraphemesDisplay<'a> {
    styled_graphemes: &'a StyledGraphemes,
}

impl fmt::Display for StyledGraphemesDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for styled_grapheme in self.styled_graphemes.iter() {
            write!(f, "{}", styled_grapheme.style.apply(styled_grapheme.ch))?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    mod from_str {
        use super::*;

        #[test]
        fn test() {
            let style = ContentStyle::default();
            let graphemes = StyledGraphemes::from_str("abc", style.clone());
            assert_eq!(3, graphemes.0.len());
            assert!(graphemes.0.iter().all(|g| g.style == style));
        }
    }

    mod chars {
        use super::*;

        #[test]
        fn test() {
            let graphemes = StyledGraphemes::from("abc");
            let chars = graphemes.chars();
            assert_eq!(vec!['a', 'b', 'c'], chars);
        }
    }

    mod widths {
        use super::*;

        #[test]
        fn test() {
            let graphemes = StyledGraphemes::from("a b");
            assert_eq!(3, graphemes.widths()); // 'a' and 'b' are each 1 width, and space is 1 width
        }
    }

    mod replace_char {
        use super::*;

        #[test]
        fn test() {
            let graphemes = StyledGraphemes::from("banana");
            assert_eq!("bonono", graphemes.replace("a", "o").to_string());
        }

        #[test]
        fn test_with_nonexistent_character() {
            let graphemes = StyledGraphemes::from("Hello World");
            assert_eq!("Hello World", graphemes.replace("x", "o").to_string());
        }

        #[test]
        fn test_with_empty_string() {
            let graphemes = StyledGraphemes::from("Hello World");
            assert_eq!("Hell Wrld", graphemes.replace("o", "").to_string());
        }

        #[test]
        fn test_with_multiple_characters() {
            let graphemes = StyledGraphemes::from("Hello World");
            assert_eq!("Hellabc Wabcrld", graphemes.replace("o", "abc").to_string());
        }
    }

    mod replace_range {
        use super::*;

        #[test]
        fn test() {
            let mut graphemes = StyledGraphemes::from("Hello");
            graphemes.replace_range(1..5, "i");
            assert_eq!("Hi", graphemes.to_string());
        }
    }

    mod apply_style {
        use super::*;

        use crossterm::style::Color;

        #[test]
        fn test() {
            let mut graphemes = StyledGraphemes::from("abc");
            let new_style = ContentStyle {
                foreground_color: Some(Color::Green),
                ..Default::default()
            };
            graphemes = graphemes.apply_style(new_style.clone());
            assert!(graphemes.iter().all(|g| g.style == new_style));
        }
    }

    mod apply_style_at {
        use super::*;

        use crossterm::style::Color;

        #[test]
        fn test_apply_style_at_specific_index() {
            let mut graphemes = StyledGraphemes::from("abc");
            let new_style = ContentStyle {
                foreground_color: Some(Color::Green),
                ..Default::default()
            };
            graphemes = graphemes.apply_style_at(1, new_style.clone());
            assert_eq!(graphemes.0[1].style, new_style);
            assert_ne!(graphemes.0[0].style, new_style);
            assert_ne!(graphemes.0[2].style, new_style);
        }

        #[test]
        fn test_apply_style_at_out_of_bounds_index() {
            let mut graphemes = StyledGraphemes::from("abc");
            let new_style = ContentStyle {
                foreground_color: Some(Color::Green),
                ..Default::default()
            };
            graphemes = graphemes.apply_style_at(5, new_style.clone()); // Out of bounds
            assert_eq!(graphemes.0.len(), 3); // Ensure no changes in length
        }
    }

    mod find_all {
        use super::*;

        #[test]
        fn test_with_empty_query() {
            let graphemes = StyledGraphemes::from("Hello, world!");
            let indices = graphemes.find_all("");
            assert!(
                indices.is_empty(),
                "Should return an empty vector for an empty query string"
            );
        }

        #[test]
        fn test_with_repeated_substring() {
            let graphemes = StyledGraphemes::from("Hello, world! Hello, universe!");
            let indices = graphemes.find_all("Hello");
            assert_eq!(
                indices,
                vec![0, 14],
                "Should find all starting indices of 'Hello'"
            );
        }

        #[test]
        fn test_with_nonexistent_substring() {
            let graphemes = StyledGraphemes::from("Hello, world!");
            let indices = graphemes.find_all("xyz");
            assert!(
                indices.is_empty(),
                "Should return an empty vector for a non-existent substring"
            );
        }

        #[test]
        fn test_with_special_character() {
            let graphemes = StyledGraphemes::from("µs µs µs");
            let indices = graphemes.find_all("s");
            assert_eq!(
                indices,
                vec![1, 4, 7],
                "Should correctly find indices of substring 'µs'"
            );
        }

        #[test]
        fn test_with_single_character() {
            let graphemes = StyledGraphemes::from("abcabcabc");
            let indices = graphemes.find_all("b");
            assert_eq!(
                indices,
                vec![1, 4, 7],
                "Should find all indices of character 'b'"
            );
        }

        #[test]
        fn test_with_full_match() {
            let graphemes = StyledGraphemes::from("Hello");
            let indices = graphemes.find_all("Hello");
            assert_eq!(indices, vec![0], "Should match the entire string");
        }

        #[test]
        fn test_with_partial_overlap() {
            let graphemes = StyledGraphemes::from("ababa");
            let indices = graphemes.find_all("aba");
            assert_eq!(
                indices,
                vec![0, 2],
                "Should handle overlapping matches correctly"
            );
        }
    }

    mod highlight {
        use super::*;

        #[test]
        fn test_with_empty_query() {
            let graphemes = StyledGraphemes::from("Hello, world!");
            let expected = graphemes.clone();
            let highlighted = graphemes.highlight("", ContentStyle::default());
            assert_eq!(highlighted.unwrap(), expected);
        }
    }

    mod apply_attribute {
        use super::*;

        #[test]
        fn test() {
            let mut graphemes = StyledGraphemes::from("abc");
            graphemes = graphemes.apply_attribute(Attribute::Bold);
            assert!(
                graphemes
                    .iter()
                    .all(|g| g.style.attributes.has(Attribute::Bold))
            );
        }
    }

    mod styled_display {
        use super::*;

        #[test]
        fn test() {
            let graphemes = StyledGraphemes::from("abc");
            let display = graphemes.styled_display();
            assert_eq!(format!("{}", display), "abc"); // Assuming default styles do not alter appearance
        }
    }

    #[cfg(test)]
    mod matrixify {
        use super::*;

        #[test]
        fn test_with_empty_input() {
            let input = StyledGraphemes::default();
            let (matrix, offset) = input.matrixify(10, 2, 0);
            assert_eq!(matrix.len(), 0);
            assert_eq!(offset, 0);
        }

        #[test]
        fn test_with_exact_width_fit() {
            let input = StyledGraphemes::from("1234567890");
            let (matrix, offset) = input.matrixify(10, 1, 0);
            assert_eq!(matrix.len(), 1);
            assert_eq!("1234567890", matrix[0].to_string());
            assert_eq!(offset, 0);
        }

        #[test]
        fn test_with_narrow_width() {
            let input = StyledGraphemes::from("1234567890");
            let (matrix, offset) = input.matrixify(5, 2, 0);
            assert_eq!(matrix.len(), 2);
            assert_eq!("12345", matrix[0].to_string());
            assert_eq!("67890", matrix[1].to_string());
            assert_eq!(offset, 0);
        }

        #[test]
        fn test_with_offset() {
            let input = StyledGraphemes::from("1234567890");
            let (matrix, offset) = input.matrixify(2, 2, 1);
            assert_eq!(matrix.len(), 2);
            assert_eq!("34", matrix[0].to_string());
            assert_eq!("56", matrix[1].to_string());
            assert_eq!(offset, 0);
        }

        #[test]
        fn test_with_padding() {
            let input = StyledGraphemes::from("1234567890");
            let (matrix, offset) = input.matrixify(2, 100, 1);
            assert_eq!(matrix.len(), 5);
            assert_eq!("12", matrix[0].to_string());
            assert_eq!("34", matrix[1].to_string());
            assert_eq!("56", matrix[2].to_string());
            assert_eq!("78", matrix[3].to_string());
            assert_eq!("90", matrix[4].to_string());
            assert_eq!(offset, 1);
        }

        #[test]
        fn test_with_large_offset() {
            let input = StyledGraphemes::from("1234567890");
            let (matrix, offset) = input.matrixify(10, 2, 100); // Offset beyond content
            assert_eq!(matrix.len(), 1);
            assert_eq!("1234567890", matrix[0].to_string());
            assert_eq!(offset, 0);
        }
    }
}