use std::collections::{HashMap, HashSet};
use serde::Serialize;
use crate::changes::ChangeFilter;
use crate::inspect::{Opened, Piece, project_paragraph, source_sha256};
use crate::namespaces::{MC, W, W14};
use crate::xmllinq::{Dom, NodeId};
use super::origin::{Fate, Origin};
use super::{
EditError, EditPlan, ExistingRevisions, Loaded, ResolveRevisions, Settled, load_stories,
settle, v2,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ForEditRequest {
pub select: Option<String>,
pub story: Option<String>,
pub head: Option<usize>,
pub tail: Option<usize>,
pub find: Option<String>,
pub regex: Option<String>,
pub ignore_case: bool,
pub changed: bool,
pub by: Option<String>,
pub by_any: Vec<String>,
pub context: usize,
pub limit: Option<usize>,
pub max_chars: Option<usize>,
pub all: bool,
pub cursor: Option<String>,
pub accept: Vec<String>,
pub reject: Vec<String>,
pub existing_revisions: ExistingRevisions,
pub track: bool,
pub closed_ranges_only: bool,
}
impl Default for ForEditRequest {
fn default() -> Self {
Self {
select: None,
story: None,
head: None,
tail: None,
find: None,
regex: None,
ignore_case: false,
changed: false,
by: None,
by_any: Vec::new(),
context: 0,
limit: None,
max_chars: None,
all: false,
cursor: None,
accept: Vec::new(),
reject: Vec::new(),
existing_revisions: ExistingRevisions::Keep,
track: true,
closed_ranges_only: false,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct TargetPair {
pub short_id: String,
pub long_id: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct TextValue {
#[serde(skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text_preview: Option<String>,
pub complete: bool,
}
impl TextValue {
fn complete(text: String) -> Self {
Self {
text: Some(text),
text_preview: None,
complete: true,
}
}
fn bounded(text: &str, chars: usize) -> Self {
let mut preview: String = text.chars().take(chars).collect();
if preview.len() < text.len()
&& !preview.ends_with(char::is_whitespace)
&& text[preview.len()..]
.chars()
.next()
.is_some_and(|c| !c.is_whitespace())
{
preview.extend(
text[preview.len()..]
.chars()
.take_while(|c| !c.is_whitespace()),
);
}
if preview.len() == text.len() {
return Self::complete(text.to_string());
}
Self {
text: None,
text_preview: Some(preview),
complete: false,
}
}
fn chars(&self) -> usize {
self.text
.as_deref()
.or(self.text_preview.as_deref())
.map_or(0, |t| t.chars().count())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct WorkingText {
#[serde(flatten)]
pub value: TextValue,
#[serde(skip_serializing_if = "Option::is_none")]
pub before_sha256: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Blocker {
pub range: [usize; 2],
pub kind: String,
pub decision: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub revision: Option<TargetPair>,
#[serde(skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Readiness {
pub operation: String,
pub status: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub blockers: Vec<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct RevisionRef {
pub target: TargetPair,
pub kind: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub author: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub range: Option<[usize; 2]>,
pub basis: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct CommentRef {
pub short_id: String,
pub long_id: String,
pub status: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limitation: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Correspondence {
OneToOne,
Merged,
Removed,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ForEditRow {
pub target: TargetPair,
pub story: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub matched_by: Vec<String>,
pub original: TextValue,
#[serde(skip_serializing_if = "Option::is_none")]
pub original_sha256: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub working: Option<WorkingText>,
pub correspondence: Correspondence,
#[serde(skip_serializing_if = "Option::is_none")]
pub merged_into: Option<String>,
pub text_codec: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub revisions: Vec<RevisionRef>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub comments: Vec<CommentRef>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub blockers: Vec<Blocker>,
pub readiness: Vec<Readiness>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub unassessed_operations: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct SourceContextRow {
pub kind: String,
pub target: TargetPair,
#[serde(flatten)]
pub value: TextValue,
pub text_view: String,
pub text_codec: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub limitations: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub revisions: Vec<RevisionRef>,
pub reason_codes: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ForEditCoverage {
pub selection_complete: bool,
pub paragraphs_selected: usize,
pub paragraphs_returned: usize,
pub context_paragraphs: usize,
pub truncated: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub omissions: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ForEditBasis {
pub text_view: String,
pub text_codec_version: u32,
pub track: String,
pub existing_revisions: String,
pub accept: Vec<String>,
pub reject: Vec<String>,
pub working_sha256: String,
pub digest: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ForEditSettled {
pub changed: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub accepted: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rejected: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ForEdit {
pub schema: String,
pub source_sha256: String,
pub basis: ForEditBasis,
pub settled: ForEditSettled,
pub paragraphs: Vec<ForEditRow>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub unanchored_comments: Vec<CommentRef>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub source_context: Vec<SourceContextRow>,
#[serde(skip)]
pub comments: Vec<crate::comments::CommentRecord>,
pub coverage: ForEditCoverage,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub input_validity: Option<crate::validate::InputValidity>,
}
fn existing_revisions_name(policy: ExistingRevisions) -> &'static str {
match policy {
ExistingRevisions::Keep => "keep",
ExistingRevisions::Accept => "accept",
ExistingRevisions::Reject => "reject",
ExistingRevisions::Refuse => "refuse",
}
}
fn basis_digest(source_digest: &str, request: &ForEditRequest, selection: &Selection) -> String {
let mut accept = request.accept.clone();
let mut reject = request.reject.clone();
accept.sort();
accept.dedup();
reject.sort();
reject.dedup();
let basis = serde_json::json!({
"v": 1,
"source_sha256": source_digest,
"codec": v2::TEXT_CODEC_VERSION,
"view": "final",
"track": request.track,
"existing_revisions": existing_revisions_name(request.existing_revisions),
"accept": accept,
"reject": reject,
"select": request.select,
"story": request.story,
"head": request.head,
"tail": request.tail,
"find": request.find,
"regex": request.regex,
"ignore_case": request.ignore_case,
"changed": request.changed,
"by": request.by,
"by_any": request.by_any,
"context": request.context,
"frozen": selection.selected,
});
source_sha256(
serde_json::to_string(&basis)
.expect("basis serializes")
.as_bytes(),
)
}
fn cursor_token(basis: &str, offset: usize) -> String {
use base64::Engine;
let json = serde_json::json!({"v": 1, "basis": basis, "offset": offset});
base64::engine::general_purpose::URL_SAFE_NO_PAD
.encode(serde_json::to_string(&json).expect("cursor serializes"))
}
fn cursor_offset(token: &str, basis: &str) -> Result<usize, EditError> {
use base64::Engine;
let decode = || -> Option<serde_json::Value> {
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(token)
.ok()?;
serde_json::from_slice(&bytes).ok()
};
let cursor = decode().ok_or_else(|| {
super::err(
"USAGE",
None,
"the cursor is not a read --for-edit continuation token",
)
})?;
if cursor["v"] != 1 || !cursor["offset"].is_u64() || !cursor["basis"].is_string() {
return Err(super::err(
"USAGE",
None,
"the cursor is not a read --for-edit continuation token",
));
}
if cursor["basis"].as_str() != Some(basis) {
return Err(super::err(
"CURSOR_BASIS_CHANGED",
None,
"the cursor is bound to another source, selection, filter or working basis; start a new query",
));
}
Ok(cursor["offset"].as_u64().unwrap_or(0) as usize)
}
struct Selection {
selected: Vec<usize>,
matched_by: HashMap<usize, Vec<String>>,
context: usize,
}
impl Selection {
fn build(
request: &ForEditRequest,
s_opened: &Opened,
s_loaded: &Loaded,
source: &[u8],
) -> Result<Self, EditError> {
let total = s_loaded.paragraph_nodes.len();
let mut filters: Vec<(&'static str, HashSet<usize>)> = Vec::new();
if let Some(story) = request.story.as_deref().filter(|s| *s != "all") {
let si = s_loaded
.stories
.iter()
.position(|s| s.id == story)
.ok_or_else(|| {
super::err("USAGE", None, format!("unknown source story {story}"))
})?;
filters.push((
"story",
s_loaded
.paragraph_story
.iter()
.enumerate()
.filter(|(_, pair)| pair.0 == si)
.map(|(g, _)| g)
.collect(),
));
}
if let Some(spec) = &request.select {
filters.push((
"ids",
id_selection(spec, source, request.closed_ranges_only)?,
));
}
if let Some(head) = request.head {
filters.push((
"ids",
s_loaded
.paragraph_story
.iter()
.enumerate()
.filter(|(_, pair)| pair.0 == 0 && pair.1 < head)
.map(|(g, _)| g)
.collect(),
));
}
if let Some(tail) = request.tail {
let body = s_loaded
.paragraph_story
.iter()
.filter(|pair| pair.0 == 0)
.count();
let from = body.saturating_sub(tail);
filters.push((
"ids",
s_loaded
.paragraph_story
.iter()
.enumerate()
.filter(|(_, pair)| pair.0 == 0 && pair.1 >= from)
.map(|(g, _)| g)
.collect(),
));
}
if request.find.is_some() || request.regex.is_some() {
filters.push((
if request.find.is_some() {
"find"
} else {
"regex"
},
text_selection(request, &s_opened.dom, &s_loaded.paragraph_nodes)?,
));
}
if request.changed {
filters.push(("changed", changed_selection(request, s_loaded, source)?));
}
let mut matched_by: HashMap<usize, Vec<String>> = HashMap::new();
let selected: Vec<usize> = if filters.is_empty() {
(0..total).collect()
} else {
let mut it = filters.iter();
let mut keep: HashSet<usize> = it.next().map_or_else(HashSet::new, |(_, s)| s.clone());
for (_, set) in it {
keep.retain(|g| set.contains(g));
}
for (name, set) in &filters {
for &g in &keep {
if set.contains(&g) {
matched_by.entry(g).or_default().push((*name).to_string());
}
}
}
(0..total).filter(|g| keep.contains(g)).collect()
};
for names in matched_by.values_mut() {
names.dedup();
}
Ok(Self {
selected,
matched_by,
context: request.context,
})
}
}
fn id_selection(spec: &str, source: &[u8], closed_only: bool) -> Result<HashSet<usize>, EditError> {
super::v2_apply::SourceModel::new(source)?.selected_paragraphs(spec, !closed_only)
}
pub fn matching_body_paragraphs(
source: &[u8],
find: Option<&str>,
regex: Option<&str>,
ignore_case: bool,
) -> Result<Vec<usize>, EditError> {
let opened = Opened::open(source).map_err(super::open_error)?;
let paragraphs = crate::inspect::body_paragraph_nodes(&opened.dom, opened.body);
let request = ForEditRequest {
find: find.map(str::to_owned),
regex: regex.map(str::to_owned),
ignore_case,
..ForEditRequest::default()
};
let matches = text_selection(&request, &opened.dom, ¶graphs)?;
Ok((0..paragraphs.len())
.filter(|p| matches.contains(p))
.collect())
}
const REGEX_SIZE_LIMIT: usize = 10 * (1 << 20);
fn text_selection(
request: &ForEditRequest,
dom: &Dom,
paragraph_nodes: &[NodeId],
) -> Result<HashSet<usize>, EditError> {
let matcher: Box<dyn Fn(&str) -> bool> = if let Some(find) = &request.find {
let needle = if request.ignore_case {
find.to_lowercase()
} else {
find.clone()
};
let ignore_case = request.ignore_case;
Box::new(move |text: &str| {
if ignore_case {
text.to_lowercase().contains(&needle)
} else {
text.contains(&needle)
}
})
} else {
let pattern = request.regex.as_deref().unwrap_or("");
let pattern = if request.ignore_case {
format!("(?i){pattern}")
} else {
pattern.to_string()
};
let compiled = regex::RegexBuilder::new(&pattern)
.size_limit(REGEX_SIZE_LIMIT)
.build()
.map_err(|e| super::err("USAGE", None, format!("--regex does not compile: {e}")))?;
Box::new(move |text: &str| compiled.is_match(text))
};
Ok(paragraph_nodes
.iter()
.enumerate()
.filter(|(_, p)| matcher(&project_paragraph(dom, **p).text))
.map(|(g, _)| g)
.collect())
}
fn changed_selection(
request: &ForEditRequest,
s_loaded: &Loaded,
source: &[u8],
) -> Result<HashSet<usize>, EditError> {
let story_index: HashMap<String, usize> = s_loaded
.stories
.iter()
.enumerate()
.map(|(i, s)| (s.id.clone(), i))
.collect();
let place = |id: Option<&String>| -> Option<(usize, usize)> {
let (story, local) = crate::ids::paragraph_place(id?)?;
Some((*story_index.get(&story)?, local))
};
let global = |at: (usize, usize)| -> Option<usize> {
s_loaded.paragraph_story.iter().position(|&pair| pair == at)
};
let authors: Vec<&str> = request
.by
.iter()
.chain(&request.by_any)
.map(|a| {
let a = a.trim();
a.strip_prefix('@').unwrap_or(a)
})
.collect();
let by = |name: Option<&str>, initials: Option<&str>| -> bool {
if authors.is_empty() {
return true;
}
authors
.iter()
.any(|want| name.is_some_and(|a| a == *want) || initials.is_some_and(|i| i == *want))
};
let mut out = HashSet::new();
let changes = crate::changes::list_changes(source)
.map_err(|e| super::err("INVALID_DOCUMENT", None, e.to_string()))?;
for change in &changes {
if !by(change.author.as_deref(), None) {
continue;
}
if let Some(g) = place(change.paragraph.as_ref()).and_then(global) {
out.insert(g);
}
}
let comments = crate::comments::list_comments(source)
.map_err(|e| super::err(e.code(), None, e.to_string()))?;
for comment in &comments {
if !by(Some(&comment.author), comment.initials.as_deref()) {
continue;
}
for at in comment_paragraphs(comment, s_loaded).0 {
if let Some(g) = global(at) {
out.insert(g);
}
}
}
Ok(out)
}
fn comment_paragraphs(
comment: &crate::comments::CommentRecord,
s_loaded: &Loaded,
) -> (Vec<(usize, usize)>, bool) {
let story_index: HashMap<&str, usize> = s_loaded
.stories
.iter()
.enumerate()
.map(|(i, s)| (s.id.as_str(), i))
.collect();
let place = |id: Option<&String>| -> Option<(usize, usize)> {
let (story, local) = crate::ids::paragraph_place(id?)?;
Some((*story_index.get(story.as_str())?, local))
};
let Some(first) = place(comment.paragraph.as_ref()) else {
return (Vec::new(), false);
};
match comment.last_paragraph.as_ref() {
None => (vec![first], false),
Some(_) => match place(comment.last_paragraph.as_ref()) {
None => (vec![first], true),
Some(l) if l.0 == first.0 => {
let (lo, hi) = (first.1.min(l.1), first.1.max(l.1));
((lo..=hi).map(|local| (first.0, local)).collect(), false)
}
Some(l) => (vec![first, l], true),
},
}
}
fn comment_ref(comment: &crate::comments::CommentRecord) -> CommentRef {
CommentRef {
short_id: format!("c{}", comment.id),
long_id: format!("comments.w:comment.w:id.{}", comment.id),
status: if comment.done {
"done".to_string()
} else {
"open".to_string()
},
limitation: None,
}
}
fn comments_by_paragraph(
comments: &[crate::comments::CommentRecord],
s_loaded: &Loaded,
) -> (HashMap<usize, Vec<CommentRef>>, Vec<CommentRef>) {
let global = |at: (usize, usize)| s_loaded.paragraph_story.iter().position(|&p| p == at);
let mut out: HashMap<usize, Vec<CommentRef>> = HashMap::new();
let mut unanchored = Vec::new();
for comment in comments {
let (paragraphs, cross_story) = comment_paragraphs(comment, s_loaded);
if paragraphs.is_empty() {
unanchored.push(comment_ref(comment));
continue;
}
let mut reference = comment_ref(comment);
if cross_story {
reference.limitation = Some("cross_story_range".to_string());
}
for at in paragraphs {
if let Some(g) = global(at) {
out.entry(g).or_default().push(reference.clone());
}
}
}
(out, unanchored)
}
struct NativeKeys {
counts: Vec<HashMap<u32, usize>>,
}
impl NativeKeys {
fn collect(dom: &Dom, stories: &[super::StoryPart]) -> Self {
let counts = stories
.iter()
.map(|story| {
let mut counts: HashMap<u32, usize> = HashMap::new();
for p in dom.descendants(story.root, Some(&W::p())) {
if let Some(value) = native_para_id(dom, p) {
*counts.entry(value).or_default() += 1;
}
}
counts
})
.collect();
Self { counts }
}
fn pair(
&self,
dom: &Dom,
story: usize,
part: &str,
short_id: &str,
paragraph: NodeId,
) -> TargetPair {
let stem = crate::ids::part_story(part);
let key = native_para_id(dom, paragraph)
.filter(|value| self.counts[story].get(value) == Some(&1));
let long_id = match key.and_then(|_| {
dom.attribute(paragraph, &W14::name("paraId"))
.map(str::to_string)
}) {
Some(lexical) => format!("{stem}.w:p.w14:paraId.{lexical}"),
None => format!("{stem}.w:p.j:short.{short_id}"),
};
TargetPair {
short_id: short_id.to_string(),
long_id,
}
}
}
fn native_para_id(dom: &Dom, paragraph: NodeId) -> Option<u32> {
super::native_keys::para_id(dom.attribute(paragraph, &W14::name("paraId"))?)
}
pub(super) fn revision_pair(dom: &Dom, el: NodeId, story: &str, part: &str) -> TargetPair {
let local = dom
.name(el)
.map(|n| n.local_name().to_string())
.unwrap_or_default();
let wid = dom.attribute(el, &W::id()).unwrap_or_default();
let short = crate::ids::ChangeId::new(story, wid).short();
let stem = crate::ids::part_story(part);
let usable = super::native_keys::revision_id(wid).is_some();
let long_id = if usable {
format!("{stem}.w:{local}.w:id.{}", escape_value(wid))
} else {
format!("{stem}.w:{local}.j:short.{short}")
};
TargetPair {
short_id: short,
long_id,
}
}
fn escape_value(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for &b in text.as_bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':') {
out.push(char::from(b));
} else {
out.push_str(&format!("-{b:02X}"));
}
}
out
}
fn piece_element(piece: &Piece) -> NodeId {
match piece {
Piece::Text { t, .. } => *t,
Piece::Glyph { element, .. } => *element,
}
}
fn classify(
dom: &Dom,
run: NodeId,
paragraph: NodeId,
story: &str,
part: &str,
) -> (String, String, Option<TargetPair>, Option<String>) {
for &node in &dom.ancestors(run, None) {
if node == paragraph {
break;
}
let Some(name) = dom.name(node) else {
continue;
};
if name.namespace_name() == MC::URI {
return (
"opaque".to_string(),
"unavailable".to_string(),
None,
Some("alternate content".to_string()),
);
}
if name.namespace_name() != W::URI {
continue;
}
match name.local_name() {
"ins" | "moveTo" => {
let kind = if name.local_name() == "ins" {
"tracked_insertion"
} else {
"move"
};
let revision = revision_pair(dom, node, story, part);
let author = dom.attribute(node, &W::author());
return (
kind.to_string(),
"conditional".to_string(),
Some(revision),
author.map(|a| format!("a tracked change by {a:?}; a decision frees it")),
);
}
"hyperlink" => {
return (
"hyperlink".to_string(),
"unavailable".to_string(),
None,
Some("edit beside it or comment on it".to_string()),
);
}
"fldSimple" => {
return (
"field".to_string(),
"unavailable".to_string(),
None,
Some("the result of a field".to_string()),
);
}
"sdt" => {
return (
"content_control".to_string(),
"unavailable".to_string(),
None,
Some("a content control; fill it or comment on it".to_string()),
);
}
"smartTag" | "customXml" | "dir" | "bdo" | "del" | "moveFrom" => {
return (
"opaque".to_string(),
"unavailable".to_string(),
None,
Some(format!("inside w:{}", name.local_name())),
);
}
_ => {}
}
}
(
"field".to_string(),
"unavailable".to_string(),
None,
Some("the result of a field".to_string()),
)
}
fn char_pos(text: &str, byte: usize) -> usize {
text[..byte].chars().count()
}
fn obstacles(
dom: &Dom,
paragraph: NodeId,
story: &str,
part: &str,
) -> (Vec<Blocker>, Vec<RevisionRef>, Vec<RevisionRef>) {
let projection = project_paragraph(dom, paragraph);
let text = projection.text.as_str();
let order: HashMap<NodeId, usize> = dom
.descendants(paragraph, None)
.into_iter()
.enumerate()
.map(|(i, n)| (n, i))
.collect();
let mut blockers: Vec<Blocker> = Vec::new();
let mut revisions: Vec<RevisionRef> = Vec::new();
let mut seen: HashSet<String> = HashSet::new();
let revision = |dom: &Dom,
el: NodeId,
kind: &str,
range: Option<[usize; 2]>,
revisions: &mut Vec<RevisionRef>,
seen: &mut HashSet<String>| {
let pair = revision_pair(dom, el, story, part);
if seen.insert(pair.short_id.clone()) {
revisions.push(RevisionRef {
target: pair,
kind: kind.to_string(),
author: dom.attribute(el, &W::author()).map(str::to_string),
range,
basis: "working".to_string(),
});
}
};
type Open = (usize, String, String, Option<TargetPair>, Option<String>);
let mut open: Option<Open> = None;
let close = |blockers: &mut Vec<Blocker>, open: &mut Option<Open>, end: usize| {
if let Some((start, kind, decision, rev, detail)) = open.take() {
blockers.push(Blocker {
range: [start, end],
kind,
decision,
revision: rev,
detail,
});
}
};
for seg in &projection.segments {
let el = piece_element(&seg.piece);
if dom.name_is(el, &W::name("sym")) {
close(&mut blockers, &mut open, char_pos(text, seg.start));
blockers.push(Blocker {
range: [char_pos(text, seg.start), char_pos(text, seg.end)],
kind: "symbol".to_string(),
decision: "unavailable".to_string(),
revision: None,
detail: Some("a symbol run; its font would draw the text".to_string()),
});
continue;
}
if seg.direct {
close(&mut blockers, &mut open, char_pos(text, seg.start));
continue;
}
let run = match &seg.piece {
Piece::Text { run, .. } | Piece::Glyph { run, .. } => *run,
};
let (kind, decision, rev, detail) = classify(dom, run, paragraph, story, part);
if let Some(el) = dom.ancestors(run, None).into_iter().find(|&a| {
dom.name(a)
.is_some_and(|n| n.namespace_name() == W::URI && n.local_name() == "ins")
}) {
revision(
dom,
el,
"insertion",
Some([char_pos(text, seg.start), char_pos(text, seg.end)]),
&mut revisions,
&mut seen,
);
}
if let Some(el) = dom.ancestors(run, None).into_iter().find(|&a| {
dom.name(a)
.is_some_and(|n| n.namespace_name() == W::URI && n.local_name() == "moveTo")
}) {
revision(
dom,
el,
"move",
Some([char_pos(text, seg.start), char_pos(text, seg.end)]),
&mut revisions,
&mut seen,
);
}
let start = char_pos(text, seg.start);
let same = matches!(
&open,
Some((_, k, d, r, dt)) if *k == kind && *d == decision && *r == rev && *dt == detail
);
if !same {
close(&mut blockers, &mut open, start);
open = Some((start, kind, decision, rev, detail));
}
}
close(&mut blockers, &mut open, text.chars().count());
for &mark in &projection.field_marks {
blockers.push(Blocker {
range: [char_pos(text, mark), char_pos(text, mark)],
kind: "field".to_string(),
decision: "unavailable".to_string(),
revision: None,
detail: Some("a field marker; edits may not cross it".to_string()),
});
}
for &el in dom.descendants(paragraph, None).iter() {
let Some(name) = dom.name(el) else {
continue;
};
if name.namespace_name() != W::URI {
continue;
}
let local = name.local_name();
let in_ppr = dom
.ancestors(el, None)
.into_iter()
.take_while(|&a| a != paragraph)
.any(|a| dom.name_is(a, &W::p_pr()));
if in_ppr {
continue;
}
if !matches!(
local,
"del" | "moveFrom" | "moveFromRangeStart" | "moveFromRangeEnd"
) {
continue;
}
let kind = if local == "del" {
"tracked_deletion"
} else {
"move"
};
let order_of = order.get(&el).copied().unwrap_or(usize::MAX);
let subtree = dom.descendants_and_self(el, None).len();
let pos = projection
.segments
.iter()
.filter(|seg| {
order
.get(&piece_element(&seg.piece))
.is_some_and(|&o| o >= order_of + subtree)
})
.map(|seg| seg.start)
.min()
.unwrap_or(text.len());
blockers.push(Blocker {
range: [char_pos(text, pos), char_pos(text, pos)],
kind: kind.to_string(),
decision: "conditional".to_string(),
revision: Some(revision_pair(dom, el, story, part)),
detail: Some("a pending deletion; a decision removes it".to_string()),
});
revision(dom, el, "deletion", None, &mut revisions, &mut seen);
}
let mut mark_revisions: Vec<RevisionRef> = Vec::new();
if let Some(rpr) = dom
.element(paragraph, &W::p_pr())
.and_then(|ppr| dom.element(ppr, &W::r_pr()))
{
for el in dom.elements(rpr, None) {
let Some(name) = dom.name(el) else {
continue;
};
if name.namespace_name() != W::URI {
continue;
}
let kind = match name.local_name() {
"ins" => "paragraph_mark",
"del" | "moveFrom" | "moveTo" => "paragraph_mark",
_ => continue,
};
let pair = revision_pair(dom, el, story, part);
mark_revisions.push(RevisionRef {
target: pair,
kind: kind.to_string(),
author: dom.attribute(el, &W::author()).map(str::to_string),
range: None,
basis: "working".to_string(),
});
}
}
for el in dom.descendants(paragraph, Some(&W::r_pr_change())) {
let pair = revision_pair(dom, el, story, part);
revisions.push(RevisionRef {
target: pair,
kind: "formatting".to_string(),
author: dom.attribute(el, &W::author()).map(str::to_string),
range: None,
basis: "working".to_string(),
});
}
(blockers, revisions, mark_revisions)
}
fn text_chars(row: &ForEditRow) -> usize {
row.original.chars() + row.working.as_ref().map_or(0, |w| w.value.chars())
}
fn bound_row(row: &mut ForEditRow, budget: usize) {
if let Some(working) = &mut row.working
&& let Some(text) = working.value.text.take()
{
working.value = TextValue::bounded(&text, budget);
}
let remaining = budget.saturating_sub(row.working.as_ref().map_or(0, |w| w.value.chars()));
if let Some(text) = row.original.text.take() {
row.original = TextValue::bounded(&text, remaining);
}
}
struct RowCtx<'a> {
selection: &'a Selection,
fates: &'a [Fate],
s_opened: &'a Opened,
s_loaded: &'a Loaded,
w_opened: &'a Opened,
w_stories: &'a [super::StoryPart],
w_nodes: &'a [NodeId],
w_story: &'a [(usize, usize)],
native: &'a NativeKeys,
comments: &'a HashMap<usize, Vec<CommentRef>>,
}
fn make_row(g: usize, ctx: &RowCtx<'_>) -> ForEditRow {
let selection = ctx.selection;
let fates = ctx.fates;
let s_opened = ctx.s_opened;
let s_loaded = ctx.s_loaded;
let w_opened = ctx.w_opened;
let w_stories = ctx.w_stories;
let w_nodes = ctx.w_nodes;
let w_story = ctx.w_story;
let native = ctx.native;
let comments = ctx.comments;
let (story, local) = s_loaded.paragraph_story[g];
let story_id = s_loaded.stories[story].id.as_str();
let part = s_loaded.stories[story].part.as_str();
let short_id = crate::ids::paragraph_id(story_id, local);
let s_node = s_loaded.paragraph_nodes[g];
let original_text = project_paragraph(&s_opened.dom, s_node).text;
let original_sha256 = v2::logical_text(&s_opened.dom, s_node)
.ok()
.map(|text| source_sha256(text.as_bytes()));
let (correspondence, w_at) = match fates[g] {
Fate::Kept(post) => (Correspondence::OneToOne, Some(post)),
Fate::Merged(post) => (Correspondence::Merged, Some(post)),
Fate::Gone => (Correspondence::Removed, None),
};
let merged_into = match fates[g] {
Fate::Merged(post) => {
let (story, local) = w_story[post];
Some(crate::ids::paragraph_id(
w_stories[story].id.as_str(),
local,
))
}
_ => None,
};
let mut blockers = Vec::new();
let mut revisions = Vec::new();
let mut mark_revisions = Vec::new();
let mut text_codec = "supported".to_string();
let mut working = None;
if let Some(post) = w_at {
let w_node = w_nodes[post];
let w_story_id = w_stories[w_story[post].0].id.as_str();
let w_part = w_stories[w_story[post].0].part.as_str();
let w_text = project_paragraph(&w_opened.dom, w_node).text;
let codec = v2::logical_text(&w_opened.dom, w_node);
let before_sha256 = codec.ok().map(|text| source_sha256(text.as_bytes()));
if before_sha256.is_none() {
text_codec = "unsupported".to_string();
}
working = Some(WorkingText {
value: TextValue::complete(w_text),
before_sha256,
});
if matches!(fates[g], Fate::Kept(_)) {
let (b, r, m) = obstacles(&w_opened.dom, w_node, w_story_id, w_part);
blockers = b;
revisions = r;
mark_revisions = m;
}
}
if !matches!(fates[g], Fate::Kept(_)) {
let (_, r, m) = obstacles(&s_opened.dom, s_node, story_id, part);
for mut reference in r.into_iter().chain(m) {
reference.basis = "original".to_string();
revisions.push(reference);
}
}
let readiness = readiness(
fates[g],
before_sha256_present(&working),
&blockers,
&mark_revisions,
);
ForEditRow {
target: native.pair(&s_opened.dom, story, part, &short_id, s_node),
story: story_id.to_string(),
matched_by: selection.matched_by.get(&g).cloned().unwrap_or_default(),
original: TextValue::complete(original_text),
original_sha256,
working,
correspondence,
merged_into,
text_codec,
revisions,
comments: comments.get(&g).cloned().unwrap_or_default(),
blockers,
readiness,
unassessed_operations: vec![
"format".to_string(),
"fill".to_string(),
"fields".to_string(),
"merge".to_string(),
],
}
}
fn before_sha256_present(working: &Option<WorkingText>) -> bool {
working.as_ref().is_some_and(|w| w.before_sha256.is_some())
}
fn readiness(
fate: Fate,
representable: bool,
blockers: &[Blocker],
mark_revisions: &[RevisionRef],
) -> Vec<Readiness> {
let all: Vec<usize> = (0..blockers.len()).collect();
let gone = matches!(fate, Fate::Gone);
let merged = matches!(fate, Fate::Merged(_));
let status = |conditional: bool| -> String {
if gone {
"unavailable".to_string()
} else if conditional {
"conditional".to_string()
} else {
"available".to_string()
}
};
let reason = |text: &str| Some(text.to_string());
let mut rows = Vec::new();
let gated = blockers
.iter()
.any(|b| b.range[0] < b.range[1] || b.decision == "unavailable");
for operation in ["replace", "insert", "delete"] {
rows.push(Readiness {
operation: operation.to_string(),
status: if gone || merged {
"unavailable".to_string()
} else {
status(gated)
},
blockers: all.clone(),
reason: (gone || merged).then(|| {
if gone {
"the paragraph is gone once revisions settle".to_string()
} else {
"the paragraph merged with its neighbours; name the settled paragraph"
.to_string()
}
}),
});
}
rows.push(Readiness {
operation: "rewrite".to_string(),
status: if gone || merged || !representable {
"unavailable".to_string()
} else {
status(!blockers.is_empty() || !mark_revisions.is_empty())
},
blockers: all.clone(),
reason: if gone {
reason("the paragraph is gone once revisions settle")
} else if merged {
reason("a rewrite needs exact one-to-one working correspondence")
} else if !representable {
reason("the exact text codec does not represent this paragraph")
} else if !blockers.is_empty() || !mark_revisions.is_empty() {
reason("desired text must not change the blocked ranges")
} else {
None
},
});
rows.push(Readiness {
operation: "insert_paragraph".to_string(),
status: if gone || merged {
"unavailable".to_string()
} else {
status(!blockers.is_empty() || !mark_revisions.is_empty())
},
blockers: all.clone(),
reason: gone.then(|| "the paragraph is gone once revisions settle".to_string()),
});
rows.push(Readiness {
operation: "delete_paragraph".to_string(),
status: if gone || merged {
"unavailable".to_string()
} else {
status(!blockers.is_empty() || !mark_revisions.is_empty())
},
blockers: all.clone(),
reason: if gone {
reason("the paragraph is gone once revisions settle")
} else if merged {
reason("the paragraph merged with its neighbours; name the settled paragraph")
} else if !blockers.is_empty() || !mark_revisions.is_empty() {
reason("the paragraph still holds revisions; a decision frees it")
} else {
None
},
});
rows.push(Readiness {
operation: "comment".to_string(),
status: status(false),
blockers: Vec::new(),
reason: gone.then(|| "the paragraph is gone once revisions settle".to_string()),
});
rows
}
fn context_of(
g: usize,
selection: &Selection,
s_opened: &Opened,
s_loaded: &Loaded,
native: &NativeKeys,
budget: &mut usize,
) -> Vec<SourceContextRow> {
if selection.context == 0 {
return Vec::new();
}
let (story, local) = s_loaded.paragraph_story[g];
let from = local.saturating_sub(selection.context);
let to = local.saturating_add(selection.context);
let mut out = Vec::new();
for l in from..=to {
if l == local {
continue;
}
let Some(neighbour) = s_loaded
.paragraph_story
.iter()
.position(|&pair| pair == (story, l))
else {
continue;
};
if selection.selected.contains(&neighbour) {
continue;
}
let node = s_loaded.paragraph_nodes[neighbour];
let story_id = s_loaded.stories[story].id.as_str();
let part = s_loaded.stories[story].part.as_str();
let short_id = crate::ids::paragraph_id(story_id, l);
let projection = project_paragraph(&s_opened.dom, node);
let representable = v2::logical_text(&s_opened.dom, node).is_ok();
let text_codec = if representable {
"supported"
} else {
"unsupported"
};
let (_, mut revisions, mark_revisions) = obstacles(&s_opened.dom, node, story_id, part);
revisions.extend(mark_revisions);
for reference in &mut revisions {
reference.basis = "original".to_string();
}
let value = TextValue::bounded(&projection.text, *budget);
*budget = budget.saturating_sub(value.chars());
out.push(SourceContextRow {
kind: if representable { "paragraph" } else { "opaque" }.to_string(),
target: native.pair(&s_opened.dom, story, part, &short_id, node),
value,
text_view: "final".to_string(),
text_codec: text_codec.to_string(),
limitations: projection.limitations.into_iter().collect(),
revisions,
reason_codes: if representable {
vec!["context".to_string()]
} else {
vec!["context".to_string(), "unsupported_text_codec".to_string()]
},
});
}
out
}
pub fn for_edit(source: &[u8], request: &ForEditRequest) -> Result<ForEdit, EditError> {
for_edit_quoting(source, request, super::PlanSyntax::V1)
}
#[doc(hidden)]
pub fn for_edit_quoting(
source: &[u8],
request: &ForEditRequest,
syntax: super::PlanSyntax,
) -> Result<ForEdit, EditError> {
if request.find.is_some() && request.regex.is_some() {
return Err(super::err("USAGE", None, "--find and --regex conflict"));
}
if (request.by.is_some() || !request.by_any.is_empty()) && !request.changed {
return Err(super::err("USAGE", None, "--by needs --changed"));
}
let source_digest = source_sha256(source);
let probe = Opened::open(source).map_err(super::open_error)?;
let plan = EditPlan {
schema_version: crate::inspect::SCHEMA_VERSION,
source_sha256: Some(source_digest.clone()),
author: "jubarte read --for-edit".to_string(),
date: None,
initials: None,
resolve_revisions: (!request.accept.is_empty() || !request.reject.is_empty()).then(|| {
ResolveRevisions {
accept: (!request.accept.is_empty())
.then(|| ChangeFilter::ids(request.accept.iter().cloned())),
reject: (!request.reject.is_empty())
.then(|| ChangeFilter::ids(request.reject.iter().cloned())),
reject_visible: false,
}
}),
removed_anchor_comments: Default::default(),
existing_revisions: request.existing_revisions,
operations: Vec::new(),
update_fields: false,
rewrite_others_comments: false,
others: super::Others::Allow,
};
let Settled {
base,
mut opened,
resolved_revisions,
changed,
..
} = settle(source, &plan, probe, syntax)?;
let Loaded {
stories,
paragraph_nodes,
paragraph_story,
} = load_stories(&mut opened)?;
let mut s_opened = Opened::open(source).map_err(super::open_error)?;
let s_loaded = load_stories(&mut s_opened)?;
let fates: Vec<Fate> = if changed {
let ids: Vec<String> = stories.iter().map(|s| s.id.clone()).collect();
let origin = Origin::build(source, &plan, &ids, ¶graph_story)?;
(0..s_loaded.paragraph_nodes.len())
.map(|g| match origin.exact(g) {
Ok(post) => Fate::Kept(post),
Err(_) => match origin.fate(g) {
Fate::Kept(post) | Fate::Merged(post) => Fate::Merged(post),
Fate::Gone => Fate::Gone,
},
})
.collect()
} else {
(0..s_loaded.paragraph_nodes.len())
.map(Fate::Kept)
.collect()
};
let native = NativeKeys::collect(&s_opened.dom, &s_loaded.stories);
let selection = Selection::build(request, &s_opened, &s_loaded, source)?;
let basis_digest = basis_digest(&source_digest, request, &selection);
let offset = match &request.cursor {
Some(token) => cursor_offset(token, &basis_digest)?,
None => 0,
};
if offset > selection.selected.len() {
return Err(super::err(
"CURSOR_BASIS_CHANGED",
None,
"the cursor continues past the frozen selection; start a new query",
));
}
let comment_list = crate::comments::list_comments(source)
.map_err(|e| super::err(e.code(), None, e.to_string()))?;
let (comments, unanchored_comments) = comments_by_paragraph(&comment_list, &s_loaded);
let limit = if request.all {
usize::MAX
} else {
request.limit.unwrap_or(100)
};
let max_chars = if request.all {
usize::MAX
} else {
request.max_chars.unwrap_or(24_000)
};
let mut rows: Vec<ForEditRow> = Vec::new();
let mut context_rows = Vec::new();
let mut omissions = Vec::new();
let mut budget = max_chars;
let mut next = selection.selected.len();
let mut truncated = false;
for (i, &g) in selection.selected.iter().enumerate().skip(offset) {
if rows.len() >= limit {
next = i;
truncated = true;
break;
}
let mut row = make_row(
g,
&RowCtx {
selection: &selection,
fates: &fates,
s_opened: &s_opened,
s_loaded: &s_loaded,
w_opened: &opened,
w_stories: &stories,
w_nodes: ¶graph_nodes,
w_story: ¶graph_story,
native: &native,
comments: &comments,
},
);
bound_row(&mut row, budget);
let used = text_chars(&row);
let complete =
row.original.complete && row.working.as_ref().is_none_or(|w| w.value.complete);
budget = budget.saturating_sub(used);
for ctx in context_of(g, &selection, &s_opened, &s_loaded, &native, &mut budget) {
context_rows.push(ctx);
}
let id = row.target.short_id.clone();
rows.push(row);
if !complete {
truncated = true;
next = i + 1;
if next < selection.selected.len() {
omissions.push(format!(
"text budget exhausted inside {id}; its previews are not complete text"
));
}
break;
}
}
if selection.selected.is_empty() {
let filters: Vec<&str> = [
request.select.is_some().then_some("ids"),
request.head.is_some().then_some("ids"),
request.tail.is_some().then_some("ids"),
request.find.is_some().then_some("find"),
request.regex.is_some().then_some("regex"),
request.changed.then_some("changed"),
request.by.is_some().then_some("by"),
]
.into_iter()
.flatten()
.collect();
if !filters.is_empty() {
omissions.push(format!(
"no paragraphs match every filter given: {}",
filters.join(", ")
));
}
}
let next_cursor = (next < selection.selected.len()).then(|| cursor_token(&basis_digest, next));
if next_cursor.is_some() {
truncated = true;
omissions.push(format!(
"{} of {} selected paragraphs returned; continue with --cursor",
rows.len(),
selection.selected.len()
));
}
let mut accept = request.accept.clone();
let mut reject = request.reject.clone();
accept.sort();
accept.dedup();
reject.sort();
reject.dedup();
Ok(ForEdit {
schema: "jubarte-read-for-edit-v1".to_string(),
source_sha256: source_digest,
basis: ForEditBasis {
text_view: "final".to_string(),
text_codec_version: v2::TEXT_CODEC_VERSION,
track: if request.track {
"on".to_string()
} else {
"off".to_string()
},
existing_revisions: existing_revisions_name(request.existing_revisions).to_string(),
accept,
reject,
working_sha256: source_sha256(&base),
digest: basis_digest,
},
settled: ForEditSettled {
changed,
accepted: resolved_revisions.accepted,
rejected: resolved_revisions.rejected,
},
coverage: ForEditCoverage {
selection_complete: next_cursor.is_none(),
paragraphs_selected: selection.selected.len(),
paragraphs_returned: rows.len(),
context_paragraphs: context_rows.len(),
truncated,
omissions,
},
paragraphs: rows,
unanchored_comments,
source_context: context_rows,
comments: comment_list,
next_cursor,
input_validity: None,
})
}
pub fn for_edit_json(
source: &[u8],
request: &ForEditRequest,
validity: Option<crate::validate::InputValidity>,
) -> Result<String, EditError> {
let mut result = for_edit(source, request)?;
result.input_validity = validity;
let json = serde_json::to_string(&result).expect("ForEdit serializes");
Ok(format!("{json}\n"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cursor_binds_frozen_membership_independently_of_request_filters() {
let request = ForEditRequest::default();
let mut selection = Selection {
selected: vec![0, 1],
matched_by: HashMap::new(),
context: 0,
};
let source = source_sha256(b"source");
let basis = basis_digest(&source, &request, &selection);
let cursor = cursor_token(&basis, 1);
assert_eq!(cursor_offset(&cursor, &basis).unwrap(), 1);
selection.selected = vec![1, 2];
let changed = basis_digest(&source, &request, &selection);
let error = cursor_offset(&cursor, &changed).unwrap_err();
assert_eq!(error.code, "CURSOR_BASIS_CHANGED");
}
#[test]
fn cursor_binds_source_digest_independently_of_selection() {
let request = ForEditRequest::default();
let selection = Selection {
selected: vec![0, 1],
matched_by: HashMap::new(),
context: 0,
};
let source = source_sha256(b"source");
let basis = basis_digest(&source, &request, &selection);
let cursor = cursor_token(&basis, 1);
assert_eq!(cursor_offset(&cursor, &basis).unwrap(), 1);
let changed = basis_digest(&source_sha256(b"other"), &request, &selection);
let error = cursor_offset(&cursor, &changed).unwrap_err();
assert_eq!(error.code, "CURSOR_BASIS_CHANGED");
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod request_branch_tests {
use super::super::deeper_boundary_fixture::{docx, para};
use super::*;
fn source() -> Vec<u8> {
docx(&format!(
"{}{}{}",
para("Alpha one."),
para("Beta two."),
para("Gamma three.")
))
}
fn token(json: &serde_json::Value) -> String {
use base64::Engine;
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json.to_string())
}
#[test]
fn previews_cut_only_between_words() {
let at_space = TextValue::bounded("ab cd", 3);
assert_eq!(at_space.text_preview.as_deref(), Some("ab "));
let before_space = TextValue::bounded("ab cd", 2);
assert_eq!(before_space.text_preview.as_deref(), Some("ab"));
let mid_word = TextValue::bounded("abcd ef", 2);
assert_eq!(mid_word.text_preview.as_deref(), Some("abcd"));
assert!(TextValue::bounded("abcd", 2).complete);
}
#[test]
fn requests_refuse_conflicting_or_incomplete_filters() {
let source = source();
let both = ForEditRequest {
find: Some("a".into()),
regex: Some("b".into()),
..ForEditRequest::default()
};
assert_eq!(
for_edit(&source, &both).unwrap_err().message,
"--find and --regex conflict"
);
let by = ForEditRequest {
by: Some("Bo".into()),
..ForEditRequest::default()
};
assert_eq!(
for_edit(&source, &by).unwrap_err().message,
"--by needs --changed"
);
let by_any = ForEditRequest {
by_any: vec!["Bo".into()],
..ForEditRequest::default()
};
assert_eq!(
for_edit(&source, &by_any).unwrap_err().message,
"--by needs --changed"
);
}
#[test]
fn cursors_must_be_ours_and_inside_the_selection() {
let source = source();
let page = ForEditRequest {
limit: Some(1),
..ForEditRequest::default()
};
let first = for_edit(&source, &page).unwrap();
assert_eq!(first.paragraphs.len(), 1);
let next = first.next_cursor.clone().expect("more to read");
let second = for_edit(
&source,
&ForEditRequest {
cursor: Some(next.clone()),
..page.clone()
},
)
.unwrap();
assert_eq!(second.paragraphs.len(), 1);
assert_ne!(second.paragraphs[0].target, first.paragraphs[0].target);
let basis = {
use base64::Engine;
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(&next)
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
v["basis"].as_str().unwrap().to_string()
};
for bad in [
serde_json::json!({"v": 2, "basis": basis, "offset": 1}),
serde_json::json!({"v": 1, "basis": basis, "offset": "1"}),
serde_json::json!({"v": 1, "basis": 7, "offset": 1}),
] {
let e = for_edit(
&source,
&ForEditRequest {
cursor: Some(token(&bad)),
..page.clone()
},
)
.unwrap_err();
assert_eq!(e.code, "USAGE", "{bad}");
}
let past = for_edit(
&source,
&ForEditRequest {
cursor: Some(cursor_token(&basis, 99)),
..page.clone()
},
)
.unwrap_err();
assert_eq!(past.code, "CURSOR_BASIS_CHANGED");
assert!(
past.message.contains("past the frozen selection"),
"{}",
past.message
);
}
#[test]
fn head_and_tail_pick_body_paragraphs() {
let source = source();
let ids = |request: ForEditRequest| -> Vec<String> {
for_edit(&source, &request)
.unwrap()
.paragraphs
.into_iter()
.map(|r| r.original.text.unwrap_or_default())
.collect()
};
let head = ids(ForEditRequest {
head: Some(1),
..ForEditRequest::default()
});
assert_eq!(head, ["Alpha one."]);
let tail = ids(ForEditRequest {
tail: Some(2),
..ForEditRequest::default()
});
assert_eq!(tail, ["Beta two.", "Gamma three."]);
let none = for_edit(
&source,
&ForEditRequest {
find: Some("zzz".into()),
..ForEditRequest::default()
},
)
.unwrap();
assert!(none.paragraphs.is_empty());
assert!(
none.coverage
.omissions
.iter()
.any(|o| o.contains("every filter given: find")),
"{:?}",
none.coverage.omissions
);
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod reference_branch_tests {
use super::*;
#[test]
fn values_escape_every_byte_outside_the_literal_set() {
assert_eq!(escape_value("a.b_c:9"), "a.b_c:9");
assert_eq!(escape_value("a b/é"), "a-20b-2F-C3-A9");
}
#[test]
fn a_resolved_comment_reads_done() {
let mut record = crate::comments::CommentRecord {
id: 4,
r#ref: "c4".into(),
author: "Bo".into(),
initials: None,
date: None,
text: "Note".into(),
parent: None,
done: true,
paragraph: None,
last_paragraph: None,
anchor_text: String::new(),
before: String::new(),
after: String::new(),
};
let done = comment_ref(&record);
assert_eq!(done.short_id, "c4");
assert_eq!(done.status, "done");
record.done = false;
assert_eq!(comment_ref(&record).status, "open");
}
}