Skip to main content

quillmark_core/document/
write.rs

1//! The content write primitive and its producers.
2//!
3//! [`Card::write`] lands an [`Edit`] on a body or a richtext field and
4//! answers a [`Receipt`]: a [`Change`], or one built from a structural edit, a
5//! writer's markdown or a whole value. Each takes the hash its writer read as
6//! [`WriteOptions::base`], and a value that no longer hashes to it refuses
7//! the write with `edit::stale_base`.
8
9use std::collections::{BTreeMap, HashSet};
10use std::sync::Arc;
11
12use quillmark_content::change::{self, Change, Dropped, Moved, Step};
13use quillmark_content::diff;
14use quillmark_content::markdown::ImportWarning;
15use quillmark_content::mint;
16use quillmark_content::model::Content;
17use quillmark_content::model::IslandType;
18use quillmark_content::structural::{StructuralEdit, Wrap};
19use quillmark_content::units::{self, Units};
20
21use super::Card;
22use super::base::{check_base, content_hash};
23use super::edit::EditError;
24use crate::value::QuillValue;
25
26/// Where an offset sits: the block holding it, by id and index, and that
27/// block's container path, outermost first.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Located {
30    pub id: String,
31    pub index: usize,
32    pub path: Vec<String>,
33}
34
35/// The value a write reaches on its card.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Target<'a> {
38    Body,
39    /// A richtext field, an absent one the empty content.
40    Field(&'a str),
41}
42
43impl<'a> Target<'a> {
44    /// The field's name, `None` for the body.
45    pub fn field(self) -> Option<&'a str> {
46        match self {
47            Target::Body => None,
48            Target::Field(name) => Some(name),
49        }
50    }
51}
52
53impl<'a> From<&'a str> for Target<'a> {
54    fn from(name: &'a str) -> Self {
55        Target::Field(name)
56    }
57}
58
59impl<'a> From<&'a String> for Target<'a> {
60    fn from(name: &'a String) -> Self {
61        Target::Field(name)
62    }
63}
64
65impl<'a> From<Option<&'a str>> for Target<'a> {
66    /// `None` the body, a name that field.
67    fn from(field: Option<&'a str>) -> Self {
68        field.map_or(Target::Body, Target::Field)
69    }
70}
71
72/// What a write reads besides its edit.
73#[derive(Debug, Clone, Copy, Default, PartialEq)]
74pub struct WriteOptions<'a> {
75    /// The hash of the value the writer read: a value that hashes otherwise
76    /// refuses the write.
77    pub base: Option<&'a str>,
78}
79
80impl<'a> From<Option<&'a str>> for WriteOptions<'a> {
81    /// The options of a write with this hash for its base.
82    fn from(base: Option<&'a str>) -> Self {
83        WriteOptions { base }
84    }
85}
86
87/// How a write builds its change from the value its writer read.
88#[derive(Debug, Clone)]
89pub enum Edit<'a> {
90    /// A change, its offsets into the value now. A record it puts
91    /// may carry a [placeholder](quillmark_content::ids::is_placeholder),
92    /// which the write fills and names in [`Receipt::minted`].
93    Apply(Change),
94    /// A structural edit's change on the value now, its offsets into it;
95    /// the ids it opens are placeholders the write fills.
96    Structural(StructuralEdit),
97    /// The value rewritten as markdown: the anchors and islands whose `qm-*`
98    /// tags it keeps stay put, and the rest keeps what a word-aligned diff
99    /// keeps.
100    Revise(&'a str),
101    /// A whole value, each anchor it names nowhere carried where the diff
102    /// keeps its text. A value that is not valid is refused.
103    Replace(Content),
104}
105
106/// What a write did.
107#[derive(Debug, Clone, PartialEq)]
108pub struct Receipt {
109    /// The change in its normalized form, which [`change::invert`] undoes.
110    pub applied: Change,
111    /// The value's new hash, the next write's base.
112    pub hash: String,
113    /// Each anchor the value held and holds nowhere now, as it read before,
114    /// with the slot that held it: every one a revise or replace lost, and
115    /// for an apply every one but those its `anchor` steps removed.
116    pub dropped_anchors: Vec<Dropped>,
117    /// Each surviving anchor the write moved, a point included, and what
118    /// moved: its position, its block or its context.
119    pub moved_anchors: Vec<Moved>,
120    /// The markdown import's warnings, for a revise.
121    pub warnings: Vec<ImportWarning>,
122    /// Each placeholder the change gave a record it put, and the id the
123    /// write minted for it past every id the value it landed on holds.
124    pub minted: BTreeMap<String, String>,
125    counted: Counted,
126}
127
128/// What a receipt's `applied` counts its offsets over, when it counts them in
129/// scalars and holds what [`Receipt::in_units`] converts them on.
130#[derive(Debug, Clone, PartialEq)]
131enum Counted {
132    Host,
133    Content(Arc<Content>),
134}
135
136impl Receipt {
137    /// The receipt with `applied` counted in `u`. A writer's revise answers
138    /// its change in scalars, and this converts it on the value it read; a
139    /// receipt [`Card::write`] or [`Card::write_in`] answered comes back as
140    /// it is, in the units its write was given.
141    pub fn in_units(mut self, u: impl Units) -> Receipt {
142        self.applied = match std::mem::replace(&mut self.counted, Counted::Host) {
143            Counted::Host => return self,
144            Counted::Content(before) => units::change_from_scalars(&self.applied, &before, u)
145                .expect("a receipt's change applies to the value it read"),
146        };
147        self
148    }
149
150    /// The receipt's warnings as diagnostics at `at`: a
151    /// [`dropped_construct`](super::dropped_construct) per construct the
152    /// markdown dropped.
153    pub fn diagnostics(&self, at: Option<&crate::path::DocPath>) -> Vec<crate::error::Diagnostic> {
154        super::dropped_constructs(self.warnings.clone(), at)
155    }
156}
157
158impl Card {
159    /// The value at `target`.
160    pub fn read<'t>(&self, target: impl Into<Target<'t>>) -> Result<Content, EditError> {
161        match target.into() {
162            Target::Body => Ok(self.body().clone()),
163            Target::Field(name) => self.richtext_value(name),
164        }
165    }
166
167    /// The hash of the value at `target`, the `base` a write to it names.
168    pub fn hash_of<'t>(&self, target: impl Into<Target<'t>>) -> Result<String, EditError> {
169        match target.into() {
170            Target::Body => Ok(self.body_hash()),
171            Target::Field(name) => self.field_hash(name),
172        }
173    }
174
175    /// The annotated read of the value at `target`: the scoped read a revise
176    /// of it reads back. A field stored under `codec: "plain"` reads as its literal
177    /// text, its anchors listed and no tag spelled.
178    pub fn annotated<'t>(
179        &self,
180        target: impl Into<Target<'t>>,
181    ) -> Result<quillmark_content::markdown::Annotated, EditError> {
182        match target.into() {
183            Target::Body => Ok(self.body_annotated()),
184            Target::Field(name) => self.field_annotated(name),
185        }
186    }
187
188    /// [`write`](Self::write) of [`Edit::Apply`].
189    pub fn apply<'o>(
190        &mut self,
191        target: Target<'_>,
192        change: &Change,
193        opts: impl Into<WriteOptions<'o>>,
194    ) -> Result<Receipt, EditError> {
195        self.write(target, Edit::Apply(change.clone()), opts)
196    }
197
198    /// [`write`](Self::write) of [`Edit::Revise`].
199    pub fn revise<'o>(
200        &mut self,
201        target: Target<'_>,
202        markdown: &str,
203        opts: impl Into<WriteOptions<'o>>,
204    ) -> Result<Receipt, EditError> {
205        self.write(target, Edit::Revise(markdown), opts)
206    }
207
208    /// [`write`](Self::write) of [`Edit::Replace`].
209    pub fn replace<'o>(
210        &mut self,
211        target: Target<'_>,
212        content: &Content,
213        opts: impl Into<WriteOptions<'o>>,
214    ) -> Result<Receipt, EditError> {
215        self.write(target, Edit::Replace(content.clone()), opts)
216    }
217
218    /// Enter at `at`: [`write`](Self::write) of
219    /// [`StructuralEdit::SplitBlock`], the new block `id` or one the write mints.
220    pub fn split_block<'o>(
221        &mut self,
222        target: Target<'_>,
223        at: usize,
224        id: Option<&str>,
225        opts: impl Into<WriteOptions<'o>>,
226    ) -> Result<Receipt, EditError> {
227        self.write(
228            target,
229            Edit::Structural(StructuralEdit::SplitBlock {
230                at,
231                id: id.map(str::to_string),
232            }),
233            opts,
234        )
235    }
236
237    /// Backspace at the start of block `id`: [`write`](Self::write) of
238    /// [`StructuralEdit::JoinBlocks`].
239    pub fn join_blocks<'o>(
240        &mut self,
241        target: Target<'_>,
242        id: &str,
243        opts: impl Into<WriteOptions<'o>>,
244    ) -> Result<Receipt, EditError> {
245        self.write(
246            target,
247            Edit::Structural(StructuralEdit::JoinBlocks { id: id.to_string() }),
248            opts,
249        )
250    }
251
252    /// Deleting `[start, end)`: [`write`](Self::write) of
253    /// [`StructuralEdit::DeleteRange`].
254    pub fn delete_range<'o>(
255        &mut self,
256        target: Target<'_>,
257        start: usize,
258        end: usize,
259        opts: impl Into<WriteOptions<'o>>,
260    ) -> Result<Receipt, EditError> {
261        self.write(
262            target,
263            Edit::Structural(StructuralEdit::DeleteRange { start, end }),
264            opts,
265        )
266    }
267
268    /// Tab over the blocks `first` to `last`: [`write`](Self::write) of
269    /// [`StructuralEdit::Indent`].
270    pub fn indent<'o>(
271        &mut self,
272        target: Target<'_>,
273        first: &str,
274        last: &str,
275        opts: impl Into<WriteOptions<'o>>,
276    ) -> Result<Receipt, EditError> {
277        self.write(
278            target,
279            Edit::Structural(StructuralEdit::Indent {
280                first: first.to_string(),
281                last: last.to_string(),
282            }),
283            opts,
284        )
285    }
286
287    /// Shift-Tab over the blocks `first` to `last`: [`write`](Self::write)
288    /// of [`StructuralEdit::Outdent`].
289    pub fn outdent<'o>(
290        &mut self,
291        target: Target<'_>,
292        first: &str,
293        last: &str,
294        opts: impl Into<WriteOptions<'o>>,
295    ) -> Result<Receipt, EditError> {
296        self.write(
297            target,
298            Edit::Structural(StructuralEdit::Outdent {
299                first: first.to_string(),
300                last: last.to_string(),
301            }),
302            opts,
303        )
304    }
305
306    /// Wrapping the blocks `first` to `last`: [`write`](Self::write) of
307    /// [`StructuralEdit::Wrap`].
308    pub fn wrap<'o>(
309        &mut self,
310        target: Target<'_>,
311        first: &str,
312        last: &str,
313        with: Wrap,
314        opts: impl Into<WriteOptions<'o>>,
315    ) -> Result<Receipt, EditError> {
316        self.write(
317            target,
318            Edit::Structural(StructuralEdit::Wrap {
319                first: first.to_string(),
320                last: last.to_string(),
321                with,
322            }),
323            opts,
324        )
325    }
326
327    /// The block holding offset `at` of the value at `target`, its index and
328    /// its container path; at a block's end, that block. `Stale` where `at`
329    /// is past the text.
330    pub fn block_at(&self, target: Target<'_>, at: usize) -> Result<Located, EditError> {
331        let content = self.read(target)?;
332        if at > content.len_scalars() {
333            return Err(EditError::change(change::ApplyError::Stale { step: 0 }));
334        }
335        let index = content.block_at(at);
336        let block = &content.blocks[index];
337        Ok(Located {
338            id: block.id.clone(),
339            index,
340            path: block.path.clone(),
341        })
342    }
343
344    /// Land `edit` on the value at `target`, all of it or none, while the
345    /// value hashes to the options' base where one is given. A revise or
346    /// replace is refused where it would drop an `x-` island.
347    pub fn write<'o>(
348        &mut self,
349        target: Target<'_>,
350        edit: Edit<'_>,
351        opts: impl Into<WriteOptions<'o>>,
352    ) -> Result<Receipt, EditError> {
353        self.write_with(target, edit, opts.into(), None::<units::Scalars>)
354    }
355
356    /// [`write`](Self::write) for a host counting offsets in `u`: an
357    /// [`Edit::Apply`]'s change, an [`Edit::Structural`]'s offsets and the
358    /// receipt's `applied` are in `u`.
359    pub fn write_in<'o>(
360        &mut self,
361        target: Target<'_>,
362        edit: Edit<'_>,
363        opts: impl Into<WriteOptions<'o>>,
364        u: impl Units,
365    ) -> Result<Receipt, EditError> {
366        self.write_with(target, edit, opts.into(), Some(u))
367    }
368
369    fn write_with<U: Units>(
370        &mut self,
371        target: Target<'_>,
372        edit: Edit<'_>,
373        opts: WriteOptions<'_>,
374        u: Option<U>,
375    ) -> Result<Receipt, EditError> {
376        if let Edit::Apply(change) = &edit {
377            check_change(change)?;
378        }
379        let now = self.read(target)?;
380        check_base(
381            opts.base,
382            || Ok(self.hash_now(target, &now)),
383            target.field(),
384        )?;
385        let fill = |change: &Change| mint::fill(change, &[&now]).map_err(EditError::change);
386        let mut minted = BTreeMap::new();
387        let (change, warnings, diffed) = match edit {
388            Edit::Apply(change) => {
389                let filled = fill(&change)?;
390                minted = filled.minted;
391                match u {
392                    Some(u) => (
393                        units::change_to_scalars(&filled.change, &now, u)
394                            .map_err(EditError::change)?,
395                        Vec::new(),
396                        false,
397                    ),
398                    None => (filled.change, Vec::new(), false),
399                }
400            }
401            Edit::Structural(edit) => {
402                let edit = match u {
403                    Some(u) => edit.to_scalars(&now, u).map_err(EditError::change)?,
404                    None => edit,
405                };
406                let filled = fill(&edit.change(&now).map_err(EditError::change)?)?;
407                minted = filled.minted;
408                (filled.change, Vec::new(), false)
409            }
410            Edit::Revise(markdown) => {
411                let revision = diff::revise(&now, markdown).map_err(|e| match e {
412                    diff::ReviseError::Import(e) => EditError::import(e),
413                    diff::ReviseError::Refused(e) => EditError::change(e),
414                })?;
415                (revision.change, revision.warnings, true)
416            }
417            Edit::Replace(content) => {
418                let change =
419                    diff::replace(&now, &content).map_err(|e| EditError::change(e.into()))?;
420                (change, Vec::new(), true)
421            }
422        };
423        let mut applied = change::apply(&now, &change).map_err(EditError::change)?;
424        if diffed {
425            keeps_ext_islands(&now, &applied.content)?;
426            applied.dropped = change::lost_anchors(&now, &applied.content, |_| true);
427        }
428        let shown = match u {
429            Some(u) => {
430                units::change_from_scalars(&applied.applied, &now, u).map_err(EditError::change)?
431            }
432            None => applied.applied.clone(),
433        };
434        let hash = self.land(target, &now, applied.content)?;
435        Ok(Receipt {
436            applied: shown,
437            hash,
438            dropped_anchors: applied.dropped,
439            moved_anchors: applied.moved,
440            warnings,
441            minted,
442            counted: Counted::Host,
443        })
444    }
445
446    /// [`revise`](Self::revise) with no base, its receipt counted in scalars
447    /// on the value it read, which [`Receipt::in_units`] converts.
448    pub(crate) fn revise_counted(
449        &mut self,
450        target: Target<'_>,
451        markdown: &str,
452    ) -> Result<Receipt, EditError> {
453        let before = self.read(target)?;
454        let mut receipt = self.write(target, Edit::Revise(markdown), WriteOptions::default())?;
455        receipt.counted = Counted::Content(Arc::new(before));
456        Ok(receipt)
457    }
458
459    /// Run `write`, which stores a new value at `target`, and answer its
460    /// receipt: the change from `before`, the value the caller read there, to
461    /// the value after, in scalars.
462    pub(crate) fn revising(
463        &mut self,
464        target: Target<'_>,
465        before: Content,
466        warnings: Vec<ImportWarning>,
467        write: impl FnOnce(&mut Self) -> Result<(), EditError>,
468    ) -> Result<Receipt, EditError> {
469        write(self)?;
470        let after = self.read(target)?;
471        let change = diff::diff(&before, &after).map_err(|e| EditError::change(e.into()))?;
472        let applied = change::apply(&before, &change).map_err(EditError::change)?;
473        let dropped_anchors = change::lost_anchors(&before, &after, |_| true);
474        let hash = self.hash_now(target, &after);
475        Ok(Receipt {
476            applied: applied.applied,
477            hash,
478            dropped_anchors,
479            moved_anchors: applied.moved,
480            warnings,
481            minted: applied.minted,
482            counted: Counted::Content(Arc::new(before)),
483        })
484    }
485
486    /// The hash of `now`, the value at `target`: the one the last write left
487    /// there, or `now` hashed.
488    fn hash_now(&self, target: Target<'_>, now: &Content) -> String {
489        let held = match target {
490            Target::Body => self.hashes.body(),
491            Target::Field(name) => self.hashes.field(name),
492        };
493        held.map_or_else(|| content_hash(now), str::to_string)
494    }
495
496    /// Store `content` at `target`, where it differs from `before`, the value
497    /// read, and answer its hash. Equality decides, not the hash, since a
498    /// hash does not see a transient anchor and a write may move only one.
499    fn land(
500        &mut self,
501        target: Target<'_>,
502        before: &Content,
503        content: Content,
504    ) -> Result<String, EditError> {
505        let hash = content_hash(&content);
506        if content != *before {
507            match target {
508                Target::Field(name) => {
509                    self.payload_mut()
510                        .insert(name.to_string(), QuillValue::from_json(content.to_value()))
511                        .map_err(EditError::InvalidPayload)?;
512                }
513                Target::Body => self.set_body(content),
514            }
515        }
516        self.remember_hash(target.field(), hash.clone());
517        Ok(hash)
518    }
519}
520
521/// Refuses a revise or replace whose result no longer holds an `x-` island
522/// `before` holds, at any depth.
523pub(crate) fn keeps_ext_islands(before: &Content, after: &Content) -> Result<(), EditError> {
524    fn ext(c: &Content, at: &str, out: &mut Vec<(String, String, String)>) {
525        for island in &c.islands {
526            let here = format!("{at}/{}", island.id);
527            if let IslandType::Ext(name) = &island.island_type {
528                out.push((here.clone(), island.id.clone(), name.clone()));
529            }
530            for (slot, inner) in &island.slots {
531                ext(inner, &format!("{here}/{slot}"), out);
532            }
533        }
534    }
535    let (mut held, mut kept) = (Vec::new(), Vec::new());
536    ext(before, "", &mut held);
537    ext(after, "", &mut kept);
538    let kept: HashSet<&str> = kept.iter().map(|(at, _, _)| at.as_str()).collect();
539    match held
540        .into_iter()
541        .find(|(at, _, _)| !kept.contains(at.as_str()))
542    {
543        Some((_, island, kind)) => Err(EditError::DropsExtIsland { island, kind }),
544        None => Ok(()),
545    }
546}
547
548/// The steps one change a host writes may hold, nested ones counted. Each
549/// step is applied on its own, so a change past this is refused before any of
550/// that runs; a writer splits a larger edit into several changes.
551pub const MAX_CHANGE_STEPS: usize = 16_384;
552
553/// Refuses a change of more than [`MAX_CHANGE_STEPS`] steps, as
554/// [`EditError::TooManySteps`]. Every [`Card::write`] of a change runs it,
555/// and the bindings run it on each change they take.
556pub fn check_change(change: &Change) -> Result<(), EditError> {
557    match steps_in(change) {
558        count if count > MAX_CHANGE_STEPS => Err(EditError::TooManySteps {
559            count,
560            max: MAX_CHANGE_STEPS,
561        }),
562        _ => Ok(()),
563    }
564}
565
566/// Refuses a content value, as the JSON a host sent, whose text and its
567/// slots' texts together pass
568/// [`MAX_MARKDOWN_SIZE`](quillmark_content::MAX_MARKDOWN_SIZE) bytes, as
569/// [`EditError::InputTooLarge`]: the bound a markdown door holds, before the
570/// value is decoded. The bindings run it on each content value they take.
571pub fn check_content_value(v: &serde_json::Value) -> Result<(), EditError> {
572    fn text_bytes(v: &serde_json::Value) -> usize {
573        let own = v
574            .get("text")
575            .and_then(serde_json::Value::as_str)
576            .map_or(0, str::len);
577        let islands: Box<dyn Iterator<Item = &serde_json::Value>> = match v.get("islands") {
578            Some(serde_json::Value::Array(list)) => Box::new(list.iter()),
579            Some(serde_json::Value::Object(map)) => Box::new(map.values()),
580            _ => Box::new(std::iter::empty()),
581        };
582        islands
583            .filter_map(|i| i.get("slots").and_then(serde_json::Value::as_object))
584            .flat_map(|slots| slots.values())
585            .map(text_bytes)
586            .fold(own, usize::saturating_add)
587    }
588    let max = quillmark_content::MAX_MARKDOWN_SIZE;
589    match text_bytes(v) {
590        size if size > max => Err(EditError::InputTooLarge { size, max }),
591        _ => Ok(()),
592    }
593}
594
595fn steps_in(change: &Change) -> usize {
596    change
597        .steps
598        .iter()
599        .map(|s| match s {
600            Step::Nested { change, .. } => 1 + steps_in(change),
601            _ => 1,
602        })
603        .sum()
604}