teksilo-widgets 0.9.2

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! An ambient band behind the sentence — or paragraph — the caret is in.
//!
//! `CaretHighlightSession` owns a **range session** on a [`TextDocument`] (see
//! `add_range_session_with_priority`) holding at most one range: the extent of whatever the
//! caret is currently inside. It is the writing-comfort counterpart of
//! [`FindSession`](super::find_session::FindSession) — same registry, same staleness discipline,
//! opposite intent. Find answers "where is this text"; this answers "where am I".
//!
//! ## Only the view being written in bands
//!
//! Two panes over one document each own a session, and an **inactive view clears its range**.
//! So the union of what the document carries is exactly one band, at the caret of the pane
//! being written in, and neither view needs a [`HighlightMask`] to say so. That is also what
//! makes the band vanish the moment focus leaves the editor, which is what you want: the band
//! marks where you are *writing*, not where a caret happens to rest.
//!
//! A **selection** makes a view inactive for the same reason. The band answers "where am I
//! writing"; a selection answers it better and more precisely, so while one is up the band is
//! redundant. It was also actively wrong: the range is resolved from the caret, which during a
//! selection is its *moving end*, so the band skipped from sentence to sentence underneath a
//! growing selection.
//!
//! ## Priority, not registration order
//!
//! The session registers at [`CARET_HIGHLIGHT_PRIORITY`], below every other layer, so a find
//! match or a spell squiggle always paints over the band. Registration order could not express
//! that: a view's session is registered when the view appears, so a split pane opened *after*
//! the find banner would outrank it in that pane and not in its sibling.
//!
//! ## Staleness on edit
//!
//! The range is an absolute char offset frozen at push time, and text-document does not
//! re-anchor a range session the way it re-anchors carets. Like `FindSession` this one
//! subscribes to its document and marks itself stale on any content edit; the host calls
//! `CaretHighlightSession::refresh` each frame with the live caret, which is
//! cheap — a caret that has not moved into a different sentence pushes nothing at all.
//!
//! [`HighlightMask`]: teksilo_text::text_document::HighlightMask

use std::cell::{Cell, RefCell};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use teksilo_text::text_document::{
    DocumentEvent, HighlightFormat, RangeHighlight, SessionId, Subscription, TextDocument,
};

/// Where the caret-highlight session sits in the document's merge order.
///
/// Far below the default `0` every other layer takes, so anything meaningful — a find match, a
/// spell squiggle, a syntax colour — wins the overlap. The band is ambient; it must never hide
/// something the writer asked to see.
pub const CARET_HIGHLIGHT_PRIORITY: i32 = -1000;

/// How much text around the caret the band covers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaretHighlightScope {
    /// The sentence the caret is in, in [`CaretHighlight::content_locale`]'s language.
    Sentence,
    /// The whole paragraph (block) the caret is in. Needs no language.
    Paragraph,
}

/// The band an editor should draw, or the absence of one.
///
/// Handed over whole rather than field by field, so a host pushes the same way whichever of
/// its inputs changed — the shape [`EditorTypographyDefaults`](teksilo_text::EditorTypographyDefaults)
/// already uses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CaretHighlight {
    pub scope: CaretHighlightScope,
    /// How the band paints. Should be **paint-only** — a background colour — so it stays a
    /// recolor rather than a reshape, and stays out of the accessibility tree.
    pub format: HighlightFormat,
    /// BCP-47-ish tag naming the language of the text, which selects the sentence tailoring
    /// (abbreviations, French spaced guillemets, the Greek question mark). Ignored by
    /// [`CaretHighlightScope::Paragraph`], which needs no language to find a block.
    pub content_locale: Option<String>,
}

/// The band layer for one view of one document.
pub(crate) struct CaretHighlightSession {
    doc: TextDocument,
    session: SessionId,
    /// What to draw, or `None` while the feature is off. Kept even while inactive, so becoming
    /// active again needs no re-push from the host.
    config: RefCell<Option<CaretHighlight>>,
    /// Whether this view should be showing a band at all — see [`set_active`](Self::set_active).
    active: Cell<bool>,
    /// The range last pushed, so an unchanged recompute skips the push — and so a format-only
    /// change (a theme switch) can re-push the same extent without re-deriving it.
    last: Cell<Option<(usize, usize)>>,
    /// Set by the document subscription on any offset-moving edit; drained by
    /// [`refresh`](Self::refresh).
    dirty: Arc<AtomicBool>,
    /// Kept alive so the subscription lives as long as the session.
    _sub: Subscription,
}

impl CaretHighlightSession {
    /// Attach an idle band session to `doc`. Draws nothing until
    /// [`set_config`](Self::set_config) and [`set_active`](Self::set_active) both say so.
    pub(crate) fn new(doc: &TextDocument) -> Self {
        let session = doc.add_range_session_with_priority(CARET_HIGHLIGHT_PRIORITY);
        let dirty = Arc::new(AtomicBool::new(false));
        let sub = {
            let dirty = dirty.clone();
            doc.on_change(move |event| {
                // Only edits that MOVE char offsets stale the cached range. Format- and
                // highlight-only events leave the text where it was — and reacting to
                // `HighlightPaintChanged` here would loop, since this session's own
                // `set_session_ranges` emits exactly that. Same filter `FindSession` uses.
                if matches!(
                    event,
                    DocumentEvent::ContentsChanged { .. }
                        | DocumentEvent::DocumentReset
                        | DocumentEvent::BlockCountChanged(_)
                        | DocumentEvent::FlowElementsInserted { .. }
                        | DocumentEvent::FlowElementsRemoved { .. }
                ) {
                    dirty.store(true, Ordering::Relaxed);
                }
            })
        };
        Self {
            doc: doc.clone(),
            session,
            config: RefCell::new(None),
            active: Cell::new(false),
            last: Cell::new(None),
            dirty,
            _sub: sub,
        }
    }

    /// The document session this layer owns — for a view's
    /// [`HighlightMask`](teksilo_text::text_document::HighlightMask), should it name one.
    #[allow(dead_code)]
    pub(crate) fn session_id(&self) -> SessionId {
        self.session
    }

    /// What this session is currently configured to draw.
    pub(crate) fn config(&self) -> Option<CaretHighlight> {
        self.config.borrow().clone()
    }

    /// Set (or clear) what to draw. Returns `true` if a repaint is owed.
    ///
    /// A change to the **format alone** — what a light/dark switch does — re-pushes the extent
    /// already resolved rather than recomputing it, so a theme toggle costs one range write per
    /// open editor and no segmentation at all.
    pub(crate) fn set_config(&self, config: Option<CaretHighlight>) -> bool {
        let previous = self.config.replace(config.clone());
        if previous == config {
            return false;
        }
        match (&previous, &config) {
            (None, _) | (_, None) => {
                // Turned on or off: `refresh` resolves it (or `clear` empties it) next.
                if config.is_none() {
                    return self.clear();
                }
                self.last.set(None);
                true
            }
            (Some(before), Some(after))
                if before.scope == after.scope && before.content_locale == after.content_locale =>
            {
                // Format-only: repaint the same extent in the new colour.
                match self.last.get() {
                    Some(range) => self.push(Some(range), after),
                    None => true,
                }
            }
            _ => {
                // The scope or the language changed: the extent has to be re-derived.
                self.last.set(None);
                true
            }
        }
    }

    /// Tell the session whether its view should be banding right now: focused, and not in the
    /// middle of a selection. An inactive view draws no band — see the module docs for why that
    /// is what makes both split panes and selections behave.
    ///
    /// Returns `true` if a repaint is owed.
    pub(crate) fn set_active(&self, active: bool) -> bool {
        if self.active.replace(active) == active {
            return false;
        }
        if active { true } else { self.clear() }
    }

    /// Re-resolve the band for `caret` and push it if it moved. Returns `true` if the pushed
    /// range changed, so the caller can pump a frame.
    ///
    /// Cheap to call every frame: an inactive or unconfigured session returns immediately, and
    /// a caret that stayed inside the same sentence pushes nothing.
    pub(crate) fn refresh(&self, caret: usize) -> bool {
        let stale = self.dirty.swap(false, Ordering::Relaxed);
        let config = self.config.borrow().clone();
        let Some(config) = config else {
            return false;
        };
        if !self.active.get() {
            return false;
        }
        let range = self.resolve(caret, &config);
        // An edit can leave the extent numerically identical while the text under it changed
        // (typing inside a sentence that already ran to the block's end), so a staled session
        // pushes even when the range matches.
        if range == self.last.get() && !stale {
            return false;
        }
        self.push(range, &config)
    }

    /// The extent the caret is inside, per the scope.
    fn resolve(&self, caret: usize, config: &CaretHighlight) -> Option<(usize, usize)> {
        match config.scope {
            CaretHighlightScope::Sentence => self
                .doc
                .sentence_at(caret, config.content_locale.as_deref()),
            CaretHighlightScope::Paragraph => {
                // `block_at_caret`, not `block_at`: the latter reads its argument as a
                // character index, where the inter-block separator belongs to the block
                // *after* it. A caret at the end of a paragraph sits on exactly that index,
                // so the band lit the next paragraph the moment you finished typing one.
                let block = self.doc.block_at_caret(caret).ok()?;
                let (start, len) = (block.start, block.length);
                (len > 0).then_some((start, start + len))
            }
        }
    }

    /// Write `range` to the document as this session's only highlight.
    fn push(&self, range: Option<(usize, usize)>, config: &CaretHighlight) -> bool {
        let ranges = match range {
            Some((start, end)) if end > start => vec![RangeHighlight {
                start,
                length: end - start,
                format: config.format.clone(),
            }],
            _ => Vec::new(),
        };
        self.doc.set_session_ranges(self.session, ranges);
        self.last.set(range);
        true
    }

    /// Drop the band without forgetting the configuration. Returns `true` if anything went away.
    fn clear(&self) -> bool {
        if self.last.get().is_none() {
            return false;
        }
        self.doc.set_session_ranges(self.session, Vec::new());
        self.last.set(None);
        true
    }
}

impl Drop for CaretHighlightSession {
    /// Retire the session, so a closed editor leaves no band behind on a document its siblings
    /// are still showing. The `Subscription`'s own drop stops callbacks but does **not** remove
    /// the highlight layer — exactly as `FindSession` documents.
    fn drop(&mut self) {
        self.doc.remove_session(self.session);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use teksilo_text::text_document::{Color, FlowElementSnapshot, HighlightMask};

    const BAND: Color = Color {
        red: 255,
        green: 254,
        blue: 235,
        alpha: 255,
    };
    const OTHER: Color = Color {
        red: 255,
        green: 140,
        blue: 0,
        alpha: 255,
    };

    fn doc(text: &str) -> TextDocument {
        let d = TextDocument::new();
        d.set_plain_text(text).unwrap();
        d
    }

    fn band(scope: CaretHighlightScope) -> CaretHighlight {
        CaretHighlight {
            scope,
            format: HighlightFormat {
                background_color: Some(BAND),
                ..Default::default()
            },
            content_locale: Some("en".into()),
        }
    }

    /// The band's paint spans on a block, as `(start, length)`.
    fn spans(doc: &TextDocument, block: usize) -> Vec<(usize, usize)> {
        match &doc.snapshot_flow_masked(&HighlightMask::all()).elements[block] {
            FlowElementSnapshot::Block(b) => b
                .paint_highlights
                .iter()
                .filter(|s| s.background_color == Some(BAND))
                .map(|s| (s.start, s.length))
                .collect(),
            _ => panic!("block"),
        }
    }

    /// A focused, configured session ready to band.
    fn live(d: &TextDocument, scope: CaretHighlightScope) -> CaretHighlightSession {
        let s = CaretHighlightSession::new(d);
        s.set_config(Some(band(scope)));
        s.set_active(true);
        s
    }

    #[test]
    fn each_scope_bands_its_own_extent() {
        let d = doc("One is first. Two is second.");

        let s = live(&d, CaretHighlightScope::Sentence);
        s.refresh(16);
        assert_eq!(spans(&d, 0), [(14, 14)], "just \"Two is second.\"");

        let p = live(&d, CaretHighlightScope::Paragraph);
        // Two sessions now band the same document; look at the paragraph one's own extent by
        // dropping the sentence one first.
        drop(s);
        p.refresh(16);
        assert_eq!(spans(&d, 0), [(0, 28)], "the whole block");
    }

    #[test]
    fn the_band_follows_the_caret_between_sentences() {
        let d = doc("One is first. Two is second.");
        let s = live(&d, CaretHighlightScope::Sentence);

        s.refresh(2);
        assert_eq!(spans(&d, 0), [(0, 13)]);
        assert!(s.refresh(16), "moving to another sentence re-pushes");
        assert_eq!(spans(&d, 0), [(14, 14)]);
    }

    /// The cheap path: a caret moving *within* one sentence changes nothing, so a burst of
    /// keystrokes costs one push and not one per frame.
    #[test]
    fn a_caret_move_inside_the_same_sentence_pushes_nothing() {
        let d = doc("One is first. Two is second.");
        let s = live(&d, CaretHighlightScope::Sentence);
        assert!(s.refresh(2), "the first resolve always pushes");
        assert!(!s.refresh(3), "same sentence: no push");
        assert!(!s.refresh(10), "still the same sentence");
    }

    #[test]
    fn an_inactive_view_draws_no_band() {
        let d = doc("One is first. Two is second.");
        let s = live(&d, CaretHighlightScope::Sentence);
        s.refresh(2);
        assert!(!spans(&d, 0).is_empty());

        assert!(s.set_active(false), "going inactive is a repaint");
        assert!(spans(&d, 0).is_empty(), "the band goes away");
        assert!(!s.refresh(2), "and stays away while inactive");
        assert!(spans(&d, 0).is_empty());

        s.set_active(true);
        s.refresh(2);
        assert!(!spans(&d, 0).is_empty(), "focus brings it back");
    }

    #[test]
    fn clearing_the_config_clears_the_band() {
        let d = doc("One is first.");
        let s = live(&d, CaretHighlightScope::Sentence);
        s.refresh(2);
        assert!(!spans(&d, 0).is_empty());

        assert!(s.set_config(None));
        assert!(spans(&d, 0).is_empty());
        assert!(!s.refresh(2), "nothing to draw");
    }

    /// A theme switch changes only the colour, and must not need the extent re-derived.
    #[test]
    fn a_format_only_change_repaints_the_same_extent() {
        let d = doc("One is first. Two is second.");
        let s = live(&d, CaretHighlightScope::Sentence);
        s.refresh(16);
        let before = spans(&d, 0);

        let mut recoloured = band(CaretHighlightScope::Sentence);
        recoloured.format.background_color = Some(OTHER);
        assert!(s.set_config(Some(recoloured)));

        // Same extent, new colour — without any call to `refresh`.
        let after = match &d.snapshot_flow_masked(&HighlightMask::all()).elements[0] {
            FlowElementSnapshot::Block(b) => b.paint_highlights.clone(),
            _ => panic!("block"),
        };
        assert_eq!(after.len(), 1);
        assert_eq!((after[0].start, after[0].length), before[0]);
        assert_eq!(after[0].background_color, Some(OTHER));
    }

    #[test]
    fn changing_scope_re_resolves_the_extent() {
        let d = doc("One is first. Two is second.");
        let s = live(&d, CaretHighlightScope::Sentence);
        s.refresh(16);
        assert_eq!(spans(&d, 0), [(14, 14)]);

        s.set_config(Some(band(CaretHighlightScope::Paragraph)));
        s.refresh(16);
        assert_eq!(spans(&d, 0), [(0, 28)]);
    }

    /// Offsets are frozen at push time, so an edit ahead of the band must re-derive it — the
    /// same discipline `FindSession` follows.
    #[test]
    fn an_edit_stales_the_band_and_refresh_re_derives_it() {
        let d = doc("One is first. Two is second.");
        let s = live(&d, CaretHighlightScope::Sentence);
        s.refresh(16);
        assert_eq!(spans(&d, 0), [(14, 14)]);

        d.set_plain_text("XXXX. One is first. Two is second.")
            .unwrap();
        assert!(s.refresh(22), "the edit staled it");
        assert_eq!(spans(&d, 0), [(20, 14)], "the band followed its text");
    }

    #[test]
    fn dropping_the_session_removes_the_layer() {
        let d = doc("One is first.");
        {
            let s = live(&d, CaretHighlightScope::Sentence);
            s.refresh(2);
            assert!(!spans(&d, 0).is_empty());
        }
        assert!(
            spans(&d, 0).is_empty(),
            "the band must not outlive its editor"
        );
    }

    /// The band is ambient and must lose every overlap, whichever layer was registered first.
    #[test]
    fn another_layer_paints_over_the_band() {
        for band_first in [true, false] {
            let d = doc("One is first.");
            let (s, other) = if band_first {
                let s = live(&d, CaretHighlightScope::Sentence);
                (s, d.add_range_session())
            } else {
                let o = d.add_range_session();
                (live(&d, CaretHighlightScope::Sentence), o)
            };
            s.refresh(2);
            d.set_session_ranges(
                other,
                vec![RangeHighlight {
                    start: 0,
                    length: 3,
                    format: HighlightFormat {
                        background_color: Some(OTHER),
                        ..Default::default()
                    },
                }],
            );

            let painted = match &d.snapshot_flow_masked(&HighlightMask::all()).elements[0] {
                FlowElementSnapshot::Block(b) => b.paint_highlights.clone(),
                _ => panic!("block"),
            };
            let at_zero = painted
                .iter()
                .rfind(|s| s.start == 0 && 0 < s.start + s.length)
                .and_then(|s| s.background_color);
            assert_eq!(
                at_zero,
                Some(OTHER),
                "the other layer must win (band registered first: {band_first})"
            );
        }
    }

    /// A caret at the end of a paragraph is still writing in *that* paragraph.
    ///
    /// The caret then sits on the character index of the inter-block separator, which
    /// `block_at` assigns to the following block — correct for a character query, wrong for a
    /// cursor. Both scopes read that answer, so pressing End (or just typing to the end of a
    /// paragraph) threw the band forward onto the next one.
    #[test]
    fn a_caret_at_the_end_of_a_paragraph_bands_that_paragraph() {
        let d = doc("One is first.\nTwo is second.");
        let end_of_first = "One is first.".chars().count();

        let p = live(&d, CaretHighlightScope::Paragraph);
        p.refresh(end_of_first);
        assert_eq!(
            spans(&d, 0),
            [(0, end_of_first)],
            "the band belongs to the paragraph the caret is finishing"
        );
        assert!(spans(&d, 1).is_empty(), "and not to the one after it");
        drop(p);

        let s = live(&d, CaretHighlightScope::Sentence);
        s.refresh(end_of_first);
        assert_eq!(spans(&d, 0), [(0, end_of_first)]);
        assert!(spans(&d, 1).is_empty());
    }

    /// The step past that boundary must still cross: one character further along is the start
    /// of the next block and belongs to it.
    #[test]
    fn the_band_does_cross_once_the_caret_enters_the_next_paragraph() {
        let d = doc("One is first.\nTwo is second.");
        let start_of_second = "One is first.\n".chars().count();

        let p = live(&d, CaretHighlightScope::Paragraph);
        p.refresh(start_of_second);
        assert!(spans(&d, 0).is_empty(), "left the first paragraph");
        assert_eq!(spans(&d, 1), [(0, "Two is second.".chars().count())]);
    }

    /// An empty block has no sentence and no paragraph extent, and must not push a zero-length
    /// range — which would be a highlight nobody can see but everybody has to merge.
    #[test]
    fn an_empty_block_bands_nothing() {
        let d = doc("Text.\n\nMore.");
        let s = live(&d, CaretHighlightScope::Paragraph);
        let blank = "Text.\n".chars().count();
        s.refresh(blank);
        assert!(spans(&d, 1).is_empty());
    }
}