perspective_viewer/exprtk/cursor.rs
1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
5// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors. ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use perspective_client::ExprValidationError;
14use yew::prelude::*;
15
16/// A tokenizer cursor for ExprTK parsing.
17///
18/// Because ExprTK reports errors in column/row coordinates and visually needs
19/// to be applied to an entire token rather than a single character, we need
20/// fairly obnoxious counter logic to figure out how to generate the resulting
21/// syntax-highlighted HTML. The `Counter<'a>` struct encpsulates this logic,
22/// generating a `NodeRef` to any autocomplete-able `<span>` tokens, as well
23/// as other convenient data for HTML rendering, and can be called incrementally
24/// while iterating tokens after parsing.
25pub struct Cursor<'a> {
26 row: u32,
27 col: u32,
28 index: u32,
29 pub err: &'a Option<ExprValidationError>,
30 pub txt: &'a str,
31 pub noderef: NodeRef,
32 pub auto: Option<String>,
33}
34
35impl<'a> Cursor<'a> {
36 pub fn new(err: &'a Option<ExprValidationError>) -> Self {
37 Self {
38 row: 1,
39 col: 0,
40 index: 0,
41 err,
42 txt: "",
43 auto: None,
44 noderef: NodeRef::default(),
45 }
46 }
47
48 /// Is the cursor currently overlapping a token with an error?
49 pub const fn is_error(&self) -> bool {
50 if let Some(err) = &self.err {
51 err.line + 1 == self.row
52 && err.column >= self.col
53 && err.column < (self.col + self.txt.len() as u32)
54 } else {
55 false
56 }
57 }
58
59 /// Is the cursor currently overlapping an autocomplete-able token?
60 pub const fn is_autocomplete(&self, position: u32) -> bool {
61 position > self.index && position <= self.index + self.txt.len() as u32
62 }
63
64 /// TODO this is alot of type backage for what could just be `num_rows()`.
65 pub fn map_rows<T, F: Fn(u32) -> T>(self, f: F) -> impl Iterator<Item = T> {
66 (0..self.row).map(f)
67 }
68
69 /// Increment the counter column by `size` characters.
70 pub fn increment_column(&mut self, size: u32) {
71 self.col += size;
72 self.index += size;
73 }
74
75 /// Increment to the next line, typewriter-style.
76 pub fn increment_line(&mut self) {
77 self.row += 1;
78 self.col = 0;
79 self.index += 1;
80 }
81}