1use 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#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Located {
30 pub id: String,
31 pub index: usize,
32 pub path: Vec<String>,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Target<'a> {
38 Body,
39 Field(&'a str),
41}
42
43impl<'a> Target<'a> {
44 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 fn from(field: Option<&'a str>) -> Self {
68 field.map_or(Target::Body, Target::Field)
69 }
70}
71
72#[derive(Debug, Clone, Copy, Default, PartialEq)]
74pub struct WriteOptions<'a> {
75 pub base: Option<&'a str>,
78}
79
80impl<'a> From<Option<&'a str>> for WriteOptions<'a> {
81 fn from(base: Option<&'a str>) -> Self {
83 WriteOptions { base }
84 }
85}
86
87#[derive(Debug, Clone)]
89pub enum Edit<'a> {
90 Apply(Change),
94 Structural(StructuralEdit),
97 Revise(&'a str),
101 Replace(Content),
104}
105
106#[derive(Debug, Clone, PartialEq)]
108pub struct Receipt {
109 pub applied: Change,
111 pub hash: String,
113 pub dropped_anchors: Vec<Dropped>,
117 pub moved_anchors: Vec<Moved>,
120 pub warnings: Vec<ImportWarning>,
122 pub minted: BTreeMap<String, String>,
125 counted: Counted,
126}
127
128#[derive(Debug, Clone, PartialEq)]
131enum Counted {
132 Host,
133 Content(Arc<Content>),
134}
135
136impl Receipt {
137 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
521pub(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
548pub const MAX_CHANGE_STEPS: usize = 16_384;
552
553pub 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
566pub 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}