use std::collections::HashMap;
use std::ops::Range;
use serde::{Deserialize, Serialize};
use super::Block;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DocumentNavigation {
pub block_count: usize,
pub anchors: Vec<DocumentAnchor>,
pub folds: Vec<DocumentFold>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DocumentAnchor {
pub name: String,
pub block: Option<usize>,
pub source_line: usize,
pub active: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DocumentFold {
pub heading: usize,
pub source_line: usize,
#[serde(default)]
pub source_text: String,
pub initially_open: bool,
pub extent: Range<usize>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct InPageTarget {
pub fragment: Option<String>,
pub block: Option<usize>,
}
impl DocumentNavigation {
pub fn is_current(&self, blocks: &[Block]) -> bool {
blocks.len() == self.block_count
}
pub fn resolve(&self, name: &str) -> Option<usize> {
self.anchors
.iter()
.find(|anchor| anchor.active && anchor.name == name)
.and_then(|anchor| anchor.block)
}
pub fn folds_containing(&self, block: usize) -> impl Iterator<Item = &DocumentFold> {
self.folds
.iter()
.filter(move |fold| fold.extent.contains(&block))
}
pub fn fold_keys(&self) -> Vec<FoldKey> {
let mut seen: HashMap<&str, usize> = HashMap::new();
self.folds
.iter()
.map(|fold| {
let count = seen.entry(fold.source_text.as_str()).or_default();
let key = FoldKey {
source_text: fold.source_text.clone(),
occurrence: *count,
};
*count += 1;
key
})
.collect()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FoldKey {
pub source_text: String,
pub occurrence: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FoldState {
open: HashMap<FoldKey, bool>,
}
impl FoldState {
pub fn reconcile(&mut self, navigation: &DocumentNavigation) {
let keys = navigation.fold_keys();
self.open.retain(|key, _| keys.contains(key));
}
pub fn is_open(&self, navigation: &DocumentNavigation, fold: usize) -> bool {
self.open_with(navigation, &navigation.fold_keys(), fold)
}
pub fn toggle(&mut self, navigation: &DocumentNavigation, fold: usize) -> bool {
let keys = navigation.fold_keys();
let open = !self.open_with(navigation, &keys, fold);
self.open.insert(keys[fold].clone(), open);
open
}
pub fn open_ancestors(&mut self, navigation: &DocumentNavigation, block: usize) -> bool {
let keys = navigation.fold_keys();
let mut changed = false;
for (fold, entry) in navigation.folds.iter().enumerate() {
if entry.extent.contains(&block) && !self.open_with(navigation, &keys, fold) {
self.open.insert(keys[fold].clone(), true);
changed = true;
}
}
changed
}
pub fn hidden(&self, navigation: &DocumentNavigation) -> Vec<Range<usize>> {
let keys = navigation.fold_keys();
let mut hidden: Vec<Range<usize>> = Vec::new();
for (fold, entry) in navigation.folds.iter().enumerate() {
let covered = hidden
.last()
.is_some_and(|last| last.end >= entry.extent.end);
if !entry.extent.is_empty() && !covered && !self.open_with(navigation, &keys, fold) {
hidden.push(entry.extent.clone());
}
}
hidden
}
fn open_with(&self, navigation: &DocumentNavigation, keys: &[FoldKey], fold: usize) -> bool {
self.open
.get(&keys[fold])
.copied()
.unwrap_or(navigation.folds[fold].initially_open)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FoldMarkers {
pub open: String,
pub closed: String,
}
impl FoldMarkers {
pub fn marker(&self, open: bool) -> &str {
if open { &self.open } else { &self.closed }
}
}
impl Default for FoldMarkers {
fn default() -> Self {
Self {
open: "\u{25be} ".into(),
closed: "\u{25b8} ".into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn table() -> DocumentNavigation {
DocumentNavigation {
block_count: 4,
anchors: vec![
DocumentAnchor {
name: "a".into(),
block: Some(2),
source_line: 3,
active: true,
},
DocumentAnchor {
name: "a".into(),
block: Some(3),
source_line: 5,
active: false,
},
DocumentAnchor {
name: "tail".into(),
block: None,
source_line: 9,
active: true,
},
],
folds: vec![
DocumentFold {
heading: 0,
source_line: 1,
source_text: "`->Outer".into(),
initially_open: false,
extent: 1..4,
},
DocumentFold {
heading: 1,
source_line: 2,
source_text: "`+>>Inner".into(),
initially_open: true,
extent: 2..3,
},
],
}
}
#[test]
fn resolve_uses_the_first_active_declaration() {
let navigation = table();
assert_eq!(navigation.resolve("a"), Some(2));
assert_eq!(navigation.resolve("tail"), None);
assert_eq!(navigation.resolve("missing"), None);
}
#[test]
fn folds_containing_lists_every_enclosing_fold() {
let navigation = table();
let headings = |block| {
navigation
.folds_containing(block)
.map(|fold| fold.heading)
.collect::<Vec<_>>()
};
assert_eq!(headings(2), [0, 1]);
assert_eq!(headings(3), [0]);
assert!(
headings(0).is_empty(),
"a heading is outside its own extent"
);
}
#[test]
fn fold_keys_count_occurrences_of_the_same_source_text() {
let mut navigation = table();
navigation.folds[1].source_text = navigation.folds[0].source_text.clone();
let keys = navigation.fold_keys();
assert_eq!(
keys.iter().map(|key| key.occurrence).collect::<Vec<_>>(),
[0, 1]
);
assert_ne!(keys[0], keys[1]);
}
#[test]
fn toggle_overrides_authored_state_and_hidden_merges_nested_extents() {
let navigation = table();
let mut state = FoldState::default();
assert_eq!(state.hidden(&navigation), [1..4], "authored: outer closed");
assert!(!state.toggle(&navigation, 1), "inner closes");
assert_eq!(
state.hidden(&navigation),
[1..4],
"the closed inner lies inside the closed outer"
);
assert!(state.toggle(&navigation, 0), "outer opens");
assert_eq!(
state.hidden(&navigation),
[2..3],
"the inner kept its state"
);
}
#[test]
fn open_ancestors_opens_only_closed_enclosing_folds() {
let navigation = table();
let mut state = FoldState::default();
state.toggle(&navigation, 1);
assert!(state.open_ancestors(&navigation, 2));
assert!(state.hidden(&navigation).is_empty());
assert!(
!state.open_ancestors(&navigation, 2),
"nothing left to open"
);
assert!(
!state.open_ancestors(&navigation, 0),
"a heading has no ancestors here"
);
}
#[test]
fn reconcile_drops_state_for_a_heading_whose_source_changed() {
let mut navigation = table();
let mut state = FoldState::default();
state.toggle(&navigation, 0);
state.toggle(&navigation, 1);
navigation.folds[1].source_text = "`->>Inner".into();
state.reconcile(&navigation);
assert!(
state.is_open(&navigation, 0),
"untouched heading keeps state"
);
assert!(
state.is_open(&navigation, 1),
"the edited heading is back to its authored open state"
);
}
#[test]
fn a_spliced_block_list_is_not_current() {
let navigation = table();
let mut blocks = vec![Block::Rule; 4];
assert!(navigation.is_current(&blocks));
blocks.insert(0, Block::Rule);
assert!(!navigation.is_current(&blocks));
}
#[test]
fn fold_markers_pick_by_state_and_default_to_distinct_glyphs() {
let markers = FoldMarkers::default();
assert_eq!(markers.marker(true), markers.open);
assert_eq!(markers.marker(false), markers.closed);
assert!(!markers.open.is_empty() && !markers.closed.is_empty());
assert_ne!(markers.open, markers.closed);
}
}