perspective_viewer/exprtk/cursor.rs
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
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ Copyright (c) 2017, the Perspective Authors. ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃ This file is part of the Perspective library, distributed under the terms ┃
// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
use perspective_client::ExprValidationError;
use yew::prelude::*;
/// A tokenizer cursor for ExprTK parsing.
///
/// Because ExprTK reports errors in column/row coordinates and visually needs
/// to be applied to an entire token rather than a single character, we need
/// fairly obnoxious counter logic to figure out how to generate the resulting
/// syntax-highlighted HTML. The `Counter<'a>` struct encpsulates this logic,
/// generating a `NodeRef` to any autocomplete-able `<span>` tokens, as well
/// as other convenient data for HTML rendering, and can be called incrementally
/// while iterating tokens after parsing.
pub struct Cursor<'a> {
row: u32,
col: u32,
index: u32,
pub err: &'a Option<ExprValidationError>,
pub txt: &'a str,
pub noderef: NodeRef,
pub auto: Option<String>,
}
impl<'a> Cursor<'a> {
pub fn new(err: &'a Option<ExprValidationError>) -> Self {
Self {
row: 1,
col: 0,
index: 0,
err,
txt: "",
auto: None,
noderef: NodeRef::default(),
}
}
/// Is the cursor currently overlapping a token with an error?
pub const fn is_error(&self) -> bool {
if let Some(err) = &self.err {
err.line + 1 == self.row
&& err.column >= self.col
&& err.column < (self.col + self.txt.len() as u32)
} else {
false
}
}
/// Is the cursor currently overlapping an autocomplete-able token?
pub const fn is_autocomplete(&self, position: u32) -> bool {
position > self.index && position <= self.index + self.txt.len() as u32
}
/// TODO this is alot of type backage for what could just be `num_rows()`.
pub fn map_rows<T, F: Fn(u32) -> T>(self, f: F) -> impl Iterator<Item = T> {
(0..self.row).map(f)
}
/// Increment the counter column by `size` characters.
pub fn increment_column(&mut self, size: u32) {
self.col += size;
self.index += size;
}
/// Increment to the next line, typewriter-style.
pub fn increment_line(&mut self) {
self.row += 1;
self.col = 0;
self.index += 1;
}
}