use std::ops::Range;
use canvist_model::BlockId;
use canvist_model::MarkTypeId;
use canvist_model::Selection;
use canvist_model::Value;
use crate::EditorState;
use crate::commands;
use crate::position;
fn head_block(state: &EditorState) -> BlockId {
match state.selection() {
Selection::Text { head, .. } => head.block,
Selection::Blocks { anchor, .. } => anchor,
}
}
pub fn around(state: &EditorState, name: &str) -> Option<BlockId> {
let kind = state.schema().block_type(name)?;
let doc = state.doc();
position::ancestors_or_self(doc, head_block(state))
.find(|&id| doc.block(id).is_some_and(|block| block.kind() == kind))
}
pub fn attr_around(state: &EditorState, name: &str, key: &str) -> Option<Value> {
let id = around(state, name)?;
state.doc().block(id)?.attrs().get(key).cloned()
}
pub fn mark_active(state: &EditorState, name: &str) -> bool {
state
.schema()
.mark_type(name)
.is_some_and(|kind| commands::is_mark_active(state, kind))
}
pub fn shared_mark_attr(state: &EditorState, name: &str, key: &str) -> Option<Value> {
let kind = state.schema().mark_type(name)?;
if !commands::is_mark_active(state, kind) {
return None;
}
let ranges = position::selected_text(state.doc(), state.selection());
let mut values = ranges
.iter()
.filter(|(_, range)| !range.is_empty())
.flat_map(|(block, range)| run_attrs(state, *block, range.clone(), kind, key));
let Some(first) = values.next() else {
let marks = commands::active_marks(state);
return marks.get(kind)?.attrs.get(key).cloned();
};
values.all(|value| value == first).then_some(first)
}
fn run_attrs(
state: &EditorState,
block: BlockId,
range: Range<u32>,
kind: MarkTypeId,
key: &str,
) -> Vec<Value> {
let Some(runs) = state
.doc()
.inline(block)
.and_then(|text| text.mark_runs(range).ok())
else {
return Vec::new();
};
runs.iter()
.map(|(_, marks)| {
marks
.get(kind)
.and_then(|mark| mark.attrs.get(key).cloned())
.unwrap_or_default()
})
.collect()
}