1use serde::{Deserialize, Serialize};
8
9use quillmark_content::markdown::from_markdown as import_markdown;
10use quillmark_content::model::Content;
11
12use crate::error::ParseError;
13use crate::error::{Diagnostic, Severity};
14use crate::version::QuillReference;
15
16#[cfg(test)]
18pub(crate) fn stored_over(old: Option<&serde_json::Value>, content: &Content) -> serde_json::Value {
19 stored_as(old, content, content.codec)
20}
21
22pub(crate) fn stored_as(
25 old: Option<&serde_json::Value>,
26 content: &Content,
27 codec: quillmark_content::model::Codec,
28) -> serde_json::Value {
29 let mut content = match held_value(old) {
30 Some(held) => quillmark_content::diff::align(&held, content.clone()),
31 None => content.clone(),
32 };
33 content.codec = codec;
34 content.to_value()
35}
36
37fn held_value(old: Option<&serde_json::Value>) -> Option<Content> {
38 old.filter(|v| v.is_object())
39 .and_then(|v| Content::from_value_lenient(v).ok())
40 .map(|read| read.content)
41}
42
43pub(crate) fn import_body(md: &str) -> Result<Content, ImportError> {
44 import_markdown(md).map(|imported| imported.content)
45}
46
47pub(crate) fn import_body_at(
50 md: &str,
51 at: &crate::path::DocPath,
52 warnings: &mut Vec<Diagnostic>,
53) -> Result<Content, ImportError> {
54 let imported = import_markdown(md)?;
55 warnings.extend(dropped_constructs(imported.warnings, Some(at)));
56 Ok(imported.content)
57}
58
59pub const DROPPED_CONSTRUCT: &str = "parse::dropped_construct";
61
62pub fn dropped_construct(warning: ImportWarning) -> Diagnostic {
67 let ImportWarning { construct, count } = warning;
68 let (message, hint) = dropped_message(&construct, count);
69 let mut args = std::collections::BTreeMap::new();
70 args.insert("construct".to_string(), construct.to_string().into());
71 args.insert("count".to_string(), count.into());
72 Diagnostic::new(Severity::Warning, message)
73 .with_code(DROPPED_CONSTRUCT.to_string())
74 .with_hint(hint)
75 .with_args(args)
76}
77
78pub fn dropped_constructs(
80 warnings: Vec<ImportWarning>,
81 at: Option<&crate::path::DocPath>,
82) -> Vec<Diagnostic> {
83 let at = at.map(ToString::to_string);
84 warnings
85 .into_iter()
86 .map(|w| match &at {
87 Some(at) => dropped_construct(w).with_path(at.clone()),
88 None => dropped_construct(w),
89 })
90 .collect()
91}
92
93pub const NONCANONICAL_READ: &str = "content::noncanonical_read";
96
97pub fn noncanonical_read() -> Diagnostic {
101 Diagnostic::new(
102 Severity::Warning,
103 "a stored content value is not in canonical form, and reads as it".to_string(),
104 )
105 .with_code(NONCANONICAL_READ.to_string())
106 .with_hint("store the document again to write its canonical form".to_string())
107}
108
109fn listed(words: &[&str], last: &str) -> String {
111 let ticked: Vec<String> = words.iter().map(|w| format!("`{w}`")).collect();
112 match ticked.split_last() {
113 Some((tail, [])) => tail.clone(),
114 Some((tail, init)) => format!("{} {last} {tail}", init.join(", ")),
115 None => String::new(),
116 }
117}
118
119fn dropped_message(construct: &DroppedConstruct, n: usize) -> (String, String) {
122 use quillmark_content::markdown::carrier::RESERVED_ATTRS;
123 use quillmark_content::table::{CELL_VALIGNS, TABLE_ALIGNS};
124 const TIGHT: &str =
125 "Markdown on the lines under a tag line drops with it, up to the next blank line.";
126 const BESIDE: &str = "A tag line beside a line of other tags drops with the markdown under it, up to the next blank line.";
127 let some = |one: &str, many: &str| {
128 if n == 1 {
129 format!("a {one}")
130 } else {
131 format!("{n} {many}")
132 }
133 };
134 let some_in_field = |one: &str, many: &str| {
135 if n == 1 {
136 format!("a {one} in this field was")
137 } else {
138 format!("{n} {many} in this field were")
139 }
140 };
141 let attr_dropped = |tag: &str, attr: &str, hint: String| {
142 let on = if n == 1 {
143 String::new()
144 } else {
145 format!(" on {n} tags")
146 };
147 (
148 format!(
149 "markdown import dropped the `{attr}` attribute of `<{tag}>`{on} in this field"
150 ),
151 hint,
152 )
153 };
154 let tag = construct.to_string();
155 match construct {
156 DroppedConstruct::Footnote => (
157 format!(
158 "markdown import dropped {} in this field",
159 some("footnote", "footnotes")
160 ),
161 "A footnote is a reference `[^label]` in prose, outside a table cell or another note, and one \
162 definition `[^label]: note` naming the same label."
163 .to_string(),
164 ),
165 DroppedConstruct::FootnoteSize => (
166 format!(
167 "markdown import kept {} in this field as written text",
168 some("footnote reference", "footnote references")
169 ),
170 format!(
171 "A reference copies its whole note, and after the first reading of each note the copies share {} characters; the references past it stay as `[^label]`. Cite a long note once.",
172 quillmark_content::MAX_NOTE_COPIES
173 ),
174 ),
175 DroppedConstruct::NoteBlock(block) => (
176 format!(
177 "markdown import kept the text of {} inside a footnote and dropped its structure",
178 some(&format!("{block} block"), &format!("{block} blocks"))
179 ),
180 "A footnote's note is inline text: each paragraph, list item or other block in it becomes a line \
181 of that text."
182 .to_string(),
183 ),
184 DroppedConstruct::Bidi => (
185 format!(
186 "markdown import dropped {} from this field",
187 some("bidi control", "bidi controls")
188 ),
189 "Content text admits no bidi formatting control (U+061C, U+200E, U+200F, U+202A–U+202E, \
190 U+2066–U+2069); the renderer orders mixed-direction text by the Unicode bidi algorithm."
191 .to_string(),
192 ),
193 DroppedConstruct::Math => (
194 format!(
195 "markdown import kept {} as written text in this field",
196 some("equation", "equations")
197 ),
198 "An equation `$…$` or `$$…$$` reads as one in prose, outside a table cell, an image's alt text \
199 and a footnote's note, around TeX that is not blank; write `\\$` for a dollar sign that opens none."
200 .to_string(),
201 ),
202 DroppedConstruct::Table => (
203 format!(
204 "markdown import closed {} in this field where its HTML block ended",
205 some("`<table>`", "`<table>`s")
206 ),
207 "An HTML table is one HTML block: a blank line inside it ends the table there, and what follows \
208 reads as markdown. Close each `<table>` with `</table>` before any blank line."
209 .to_string(),
210 ),
211 DroppedConstruct::TableRow => (
212 format!(
213 "markdown import padded {} in this field to its table's columns",
214 some("table row", "table rows")
215 ),
216 "An HTML table is as wide as its widest row. A row leaves out each cell a `rowspan` above it covers, \
217 and a row short of the width pads with empty cells."
218 .to_string(),
219 ),
220 DroppedConstruct::TableSize => (
221 format!(
222 "markdown import cut {} in this field at {} cells",
223 some("table", "tables"),
224 quillmark_content::MAX_TABLE_CELLS
225 ),
226 "A table's rows times its columns stay within the bound; the rows past it drop. Split the table."
227 .to_string(),
228 ),
229 DroppedConstruct::TableText => (
230 format!(
231 "markdown import dropped {} outside every cell of an HTML table in this field",
232 some("run of text", "runs of text")
233 ),
234 "Text in an HTML table sits in a `<td>` or `<th>`; a `<caption>` and text between rows drop.".to_string(),
235 ),
236 DroppedConstruct::TableAttr { tag: element, attr } => attr_dropped(
237 element,
238 attr,
239 match (element.as_str(), attr.as_str()) {
240 ("table", "widths") => {
241 "`widths` is a whole number from 1 to 2^53 - 1, or `auto`, per column, such as `widths=\"2 1 auto\"`."
242 .to_string()
243 }
244 ("table", "aligns") => {
245 "`aligns` is `none`, `left`, `center` or `right` per column, such as `aligns=\"left none right\"`."
246 .to_string()
247 }
248 ("table" | "td" | "th", "align") => format!("`align` is {}.", listed(&TABLE_ALIGNS, "or")),
249 ("table", _) => "`<table>` takes `widths`, `aligns` and `align`.".to_string(),
250 (_, "colspan" | "rowspan") => format!("`{attr}` is a whole number from 1."),
251 (_, "valign") => format!("`valign` is {}.", listed(&CELL_VALIGNS, "or")),
252 ("td" | "th", _) => "`<td>` and `<th>` take `colspan`, `rowspan`, `align` and `valign`.".to_string(),
253 _ => format!("`<{element}>` takes no attributes."),
254 },
255 ),
256 DroppedConstruct::ElementAttr { element, attr }
257 if attr == "ref" && quillmark_content::markdown::carrier::RESERVED.contains(&element.as_str()) =>
258 {
259 let (what, spelling) = match element == quillmark_content::markdown::carrier::ANCHOR {
260 true => ("anchor", ("tag", "tags")),
261 false => ("island", ("token", "tokens")),
262 };
263 let element = DroppedConstruct::Element(element.clone());
264 (
265 format!(
266 "markdown revise dropped {} naming no {what} the stored value holds, or one an earlier \
267 tag names, in this field",
268 some(&format!("`<{element}>` {}", spelling.0), &format!("`<{element}>` {}", spelling.1))
269 ),
270 format!(
271 "A `ref` names a {what} of the value the annotated read was taken from, once per {what}: \
272 copy the tag from the read, or remove it. An anchor without its tag keeps its place by \
273 the text around it."
274 ),
275 )
276 }
277 DroppedConstruct::ElementAttr { element, attr } => attr_dropped(
278 &DroppedConstruct::Element(element.clone()).to_string(),
279 attr,
280 format!(
281 "An attribute name is lowercase letters, digits and `_`, opening with a letter, once per tag, \
282 and none of `{}` or a name opening `on`.",
283 RESERVED_ATTRS.join("`, `")
284 ),
285 ),
286 DroppedConstruct::BadName(_) => (
287 format!(
288 "markdown import does not carry raw HTML: {} dropped",
289 some_in_field(&format!("`<{tag}>` tag"), &format!("`<{tag}>` tags"))
290 ),
291 format!(
292 "An element name after `qm-` is lowercase words of letters and digits joined by single `-`, \
293 opening with a letter. {TIGHT}"
294 ),
295 ),
296 DroppedConstruct::Element(name) if name == quillmark_content::markdown::carrier::SPAN => (
297 format!(
298 "markdown import dropped {} in this field",
299 some(&format!("`<{tag}>` tag"), &format!("`<{tag}>` tags"))
300 ),
301 format!(
302 "A `<{tag}>` pair sets a `family` inside one line of text and closes with `</{tag}>` there; \
303 HTML reads `<{tag}/>` as an open tag. A family is a run's, never a block's. {BESIDE}"
304 ),
305 ),
306 DroppedConstruct::Element(name) if name == quillmark_content::markdown::carrier::ISLAND => (
307 format!(
308 "markdown import dropped {} in this field",
309 some(&format!("`<{tag}>` token"), &format!("`<{tag}>` tokens"))
310 ),
311 format!(
312 "A `<{tag}>` token stands for an island of the stored value an annotated read was taken from, \
313 in prose: only a revise of that value reads it. A plain import, a table cell, a footnote and \
314 an image's alt text drop it."
315 ),
316 ),
317 DroppedConstruct::Element(_) => (
318 format!(
319 "markdown import dropped {} in this field",
320 some(&format!("`<{tag}>` tag"), &format!("`<{tag}>` tags"))
321 ),
322 format!("A `<{tag}>` tag carries nothing: what it wraps stays and the tags drop. Remove them."),
323 ),
324 DroppedConstruct::Tag(name) => match name.as_str() {
325 "u" => (
326 format!("markdown import dropped {} in this field", some("`<u>` tag", "`<u>` tags")),
327 "A `<u>` takes no attributes and closes with `</u>` in the paragraph, heading, list item or \
328 table cell it opens in."
329 .to_string(),
330 ),
331 "pre" | "script" | "style" | "textarea" => (
332 format!(
333 "markdown import does not carry raw HTML: {} dropped",
334 some_in_field(&format!("`<{tag}>` block"), &format!("`<{tag}>` blocks"))
335 ),
336 format!("A `<{tag}>` block drops whole, through its closing tag. Write code in a backtick fence."),
337 ),
338 _ => (
339 format!(
340 "markdown import does not carry raw HTML: {} dropped",
341 some_in_field(&format!("`<{tag}>` tag"), &format!("`<{tag}>` tags"))
342 ),
343 "Raw HTML imports nothing but `<u>`, `<br>`, a `<table>` and `<qm-span>`. Where a line \
344 opens with any other tag, its block runs to the next blank line and drops whole, markdown \
345 included; a blank line under the tag line keeps what follows."
346 .to_string(),
347 ),
348 },
349 }
350}
351
352#[derive(Debug, Clone, PartialEq, Eq)]
355pub(crate) enum ContentDecodeError {
356 NotContent(String),
357 BadMarkdown(String),
358}
359
360impl ContentDecodeError {
361 pub(crate) fn into_message(self) -> String {
362 match self {
363 ContentDecodeError::NotContent(m) | ContentDecodeError::BadMarkdown(m) => m,
364 }
365 }
366}
367
368#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub(crate) enum Codec {
375 Richtext,
378 Text,
381}
382
383impl Codec {
384 pub(crate) fn of_object(value: &serde_json::Value) -> Codec {
387 match value.get("codec").and_then(serde_json::Value::as_str) {
388 Some("plain") => Codec::Text,
389 _ => Codec::Richtext,
390 }
391 }
392
393 pub(crate) fn content(self) -> quillmark_content::model::Codec {
395 match self {
396 Codec::Richtext => quillmark_content::model::Codec::Rich,
397 Codec::Text => quillmark_content::model::Codec::Plain,
398 }
399 }
400
401 pub(crate) fn name(self) -> &'static str {
404 match self {
405 Codec::Richtext => edit::CODEC_RICHTEXT,
406 Codec::Text => edit::CODEC_TEXT,
407 }
408 }
409
410 fn string_form(self) -> &'static str {
412 match self {
413 Codec::Richtext => "a markdown string",
414 Codec::Text => "a string",
415 }
416 }
417
418 pub(crate) fn decode_value(
424 self,
425 value: &serde_json::Value,
426 ) -> Option<Result<quillmark_content::markdown::Imported, ContentDecodeError>> {
427 self.decode_value_admitting(value, quillmark_content::markdown::Admit::Blocks)
428 }
429
430 pub(crate) fn decode_value_admitting(
432 self,
433 value: &serde_json::Value,
434 admit: quillmark_content::markdown::Admit,
435 ) -> Option<Result<quillmark_content::markdown::Imported, ContentDecodeError>> {
436 let whole = |content| quillmark_content::markdown::Imported {
437 content,
438 warnings: Vec::new(),
439 };
440 match value {
441 serde_json::Value::Object(_) => Some(
442 Content::from_value_lenient(value)
443 .map(|read| whole(read.content))
444 .map_err(|e| ContentDecodeError::NotContent(e.to_string())),
445 ),
446 serde_json::Value::String(s) => Some(match self {
447 Codec::Richtext => quillmark_content::markdown::from_markdown_admitting(s, admit)
448 .map_err(|e| ContentDecodeError::BadMarkdown(e.to_string())),
449 Codec::Text => Ok(whole(quillmark_content::markdown::plain(s))),
450 }),
451 _ => None,
452 }
453 }
454
455 pub(crate) fn unshaped_message(self, value: &serde_json::Value) -> String {
459 format!(
460 "expected a {} content object or {}, got {}",
461 self.name(),
462 self.string_form(),
463 match value {
464 serde_json::Value::Bool(_) => "a boolean",
465 serde_json::Value::Number(_) => "a number",
466 serde_json::Value::Array(_) => "an array",
467 _ => "an unsupported value",
468 }
469 )
470 }
471
472 pub(crate) fn decode_field(
476 self,
477 value: &serde_json::Value,
478 ) -> Result<Content, ContentDecodeError> {
479 match self.decode_value(value) {
480 Some(result) => result.map(|imported| imported.content),
481 None if value.is_null() => Ok(Content::empty_as(self.content())),
482 None => Err(ContentDecodeError::NotContent(self.unshaped_message(value))),
483 }
484 }
485
486 pub(crate) fn decode_content(
489 self,
490 value: &serde_json::Value,
491 ) -> Result<Content, ContentDecodeError> {
492 match value {
493 serde_json::Value::Object(_) => Content::from_value(value)
494 .map_err(|e| ContentDecodeError::NotContent(e.to_string())),
495 serde_json::Value::String(s) => match self {
496 Codec::Richtext => quillmark_content::markdown::from_markdown(s)
497 .map(|i| i.content)
498 .map_err(|e| ContentDecodeError::BadMarkdown(e.to_string())),
499 Codec::Text => Ok(quillmark_content::markdown::plain(s)),
500 },
501 serde_json::Value::Null => Ok(Content::empty_as(self.content())),
502 _ => Err(ContentDecodeError::NotContent(self.unshaped_message(value))),
503 }
504 }
505
506 pub(crate) fn read_content(
510 self,
511 value: &serde_json::Value,
512 ) -> Result<Content, ContentDecodeError> {
513 match value {
514 serde_json::Value::Object(_) => Content::from_value_lenient(value)
515 .map(|read| read.content)
516 .map_err(|e| ContentDecodeError::NotContent(e.to_string())),
517 _ => self.decode_content(value),
518 }
519 }
520
521 pub(crate) fn project(self, content: &Content) -> String {
524 match self {
525 Codec::Richtext => quillmark_content::markdown::to_markdown(content),
526 Codec::Text => quillmark_content::markdown::to_plaintext(content),
527 }
528 }
529}
530
531#[derive(Debug, Clone, PartialEq, Eq)]
534pub(crate) enum RichtextValueError {
535 Decode(ContentDecodeError),
537 Unshaped,
539 NotSingleLine,
541 NotLines,
543}
544
545pub(crate) fn canonical_richtext_value(
550 value: &serde_json::Value,
551 shape: crate::quill::Shape,
552) -> Result<(serde_json::Value, Vec<ImportWarning>), RichtextValueError> {
553 let (mut content, warnings) = match value {
554 serde_json::Value::Object(_) => (
555 Content::from_value(value).map_err(|e| {
556 RichtextValueError::Decode(ContentDecodeError::NotContent(e.to_string()))
557 })?,
558 Vec::new(),
559 ),
560 serde_json::Value::String(s) => {
561 let imported = quillmark_content::markdown::from_markdown_admitting(s, shape.admit())
562 .map_err(|e| {
563 RichtextValueError::Decode(ContentDecodeError::BadMarkdown(e.to_string()))
564 })?;
565 (imported.content, imported.warnings)
566 }
567 _ => return Err(RichtextValueError::Unshaped),
568 };
569 if !shape.admits(&content) {
570 return Err(match shape {
571 crate::quill::Shape::Line => RichtextValueError::NotSingleLine,
572 _ => RichtextValueError::NotLines,
573 });
574 }
575 content.codec = quillmark_content::model::Codec::Rich;
576 Ok((content.to_value(), warnings))
577}
578
579pub(crate) fn trim_line_end(mut content: Content) -> Content {
584 let keep = content.text.trim_end().len();
585 if keep == content.text.len() {
586 return content;
587 }
588 content.text.truncate(keep);
589 content
590 .blocks
591 .truncate(content.text.matches('\n').count() + 1);
592 cut_anchors(&mut content);
593 content
594}
595
596pub(crate) fn fold_line_breaks(mut content: Content) -> Content {
600 content.text = content
601 .text
602 .chars()
603 .map(|c| match c {
604 '\n' | quillmark_content::model::HARD_BREAK => ' ',
605 c => c,
606 })
607 .collect();
608 content.blocks.truncate(1);
609 if let Some(block) = content.blocks.first_mut() {
610 block.kind = quillmark_content::model::BlockKind::Para;
611 block.path.clear();
612 }
613 content.containers.clear();
614 cut_anchors(&mut content);
615 content
616}
617
618fn cut_anchors(content: &mut Content) {
619 let len = content.len_scalars();
620 for a in &mut content.anchors {
621 a.start = a.start.min(len);
622 a.end = a.end.min(len);
623 }
624 content.normalize();
625}
626
627pub(crate) mod align;
628pub mod anchors;
629pub mod assemble;
630pub mod base;
631pub mod card_id;
632pub mod dto;
633pub mod edit;
634pub mod emit;
635pub mod fences;
636pub mod meta;
637pub mod payload;
638pub(crate) mod prescan;
639pub mod revise;
640pub mod wire;
641pub mod write;
642pub(crate) mod yaml_hints;
643
644pub use anchors::AnchorSelector;
645pub use base::{HASH_TAG, StaleBase, content_hash, value_hash};
646pub use dto::{
647 STORAGE_V0_124_0, STORAGE_V0_129_0, STORAGE_V0_131_0, STORAGE_V0_134_0, STORAGE_V0_135_0,
648 StorageError, StoredDocument, peek_storage_version,
649};
650pub use edit::{CardMut, EditError, Unchecked};
651pub use emit::{AnnotatedMarkdown, DocumentAnchor};
652pub use meta::{CardKindError, is_valid_kind_name, validate_composable_kind};
653pub use payload::{MetaKey, Payload, PayloadItem};
654pub use quillmark_content::anchors::Reattached;
656pub use quillmark_content::markdown::ImportError;
658pub use quillmark_content::markdown::{AnchorRead, Annotated};
660pub use quillmark_content::markdown::{DroppedConstruct, ImportWarning};
662pub use revise::DocumentRevised;
663pub use prescan::NestedComment;
665pub use wire::{CardWire, PayloadItemWire, WireError};
666pub use write::{
667 Edit, Located, MAX_CHANGE_STEPS, Receipt, Target, WriteOptions, check_change,
668 check_content_value,
669};
670
671pub const MARKDOWN_RULES: &str = "Quillmark Markdown rules:
675\u{2022} Block opener and closer are EXACTLY `~~~` (three tildes). The opener's info string is ignored \u{2014} `~~~card-yaml` is accepted and re-emits as a bare `~~~`.
676\u{2022} A blank line must precede every `~~~` block opener (unless it is line 1), and the opener must be at column zero (no leading spaces). An indented `~~~` is an ordinary code block, not a card.
677\u{2022} The first block is the root and MUST contain `$quill: <name>` or `$quill: <name>@<selector>`. Its `$kind` is `main` by position \u{2014} an explicit `$kind: main` is accepted but not required. Every later block is a composable card and MUST declare `$kind: <card_kind>`.
678\u{2022} Reserved `$`-keys: `$quill`, `$kind`, `$id`, `$ext`, `$seed`. User fields use lowercase snake_case.
679\u{2022} A composable card's `$id` line names it across edits: keep it when you edit or move the card, leave it out of a new card (one is minted), and never copy it onto a second card.
680\u{2022} Prose body is the text after a block's closing `~~~`, up to the next opener or EOF. To include a literal fenced code block in prose, use a backtick fence (```); any column-zero `~~~` block is parsed as card metadata.
681\u{2022} A blank or null value (`field:`, `field: null`, `field: ~`) is the same as omitting the field: it falls back to the field's default, else its blank. `field: \"\"` is kept as written, an explicit empty value.
682\u{2022} Plain-scalar values cannot start with `*` or `&` (YAML alias/anchor markers) and cannot contain `: ` (colon-space). For markdown emphasis, embedded colons, or other special prefixes, quote the value: `field: '**bold**'` or `field: \"Name: subtitle\"`. Multi-line values use `|-`, not multi-line quoted scalars.
683\u{2022} In a body or richtext value, `<qm-span family=\"<family>\">text</qm-span>` sets a run's font family. Pairs nest, the innermost winning and the outer resuming past it. Name only a family the host's font library supplies: any other keeps the surrounding font and warns.
684\u{2022} Markdown read from an annotated read carries `<qm-anchor ref=\"\u{2026}\"></qm-anchor>` tags and `<qm-island ref=\"\u{2026}\"></qm-island>` tokens. Keep each tag before the text it marks, moving it with that text; drop a tag only with its text. Keep each token where its island belongs: it stands for a table, image or equation kept as stored. Never write a `ref` the read did not hold.";
685
686#[cfg(test)]
687mod tests;
688
689#[derive(Debug)]
695#[must_use = "carries parse warnings; read `.document`/`.warnings` or bind it"]
696pub struct Parsed {
697 pub document: Document,
698 pub warnings: Vec<Diagnostic>,
699}
700
701#[derive(Debug)]
704pub(crate) struct Revising {
705 pub parsed: Parsed,
706 pub bodies: Vec<String>,
707}
708
709#[derive(Debug, Clone, PartialEq)]
713pub struct Card {
714 payload: Payload,
715 body: Content,
716 hashes: Hashes,
717}
718
719#[derive(Clone, Default)]
724pub(crate) struct Hashes {
725 body: Option<String>,
726 fields: std::collections::HashMap<String, String>,
727}
728
729impl Hashes {
730 pub(crate) fn body(&self) -> Option<&str> {
731 self.body.as_deref()
732 }
733
734 pub(crate) fn field(&self, name: &str) -> Option<&str> {
735 self.fields.get(name).map(String::as_str)
736 }
737}
738
739impl PartialEq for Hashes {
740 fn eq(&self, _: &Self) -> bool {
741 true
742 }
743}
744
745impl std::fmt::Debug for Hashes {
746 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
747 f.write_str("Hashes")
748 }
749}
750
751impl Card {
752 pub(crate) fn from_parts(payload: Payload, body: Content) -> Self {
754 Self {
755 payload,
756 body,
757 hashes: Hashes::default(),
758 }
759 }
760
761 pub fn quill(&self) -> Option<&QuillReference> {
762 self.payload.quill()
763 }
764
765 pub fn kind(&self) -> Option<&str> {
766 self.payload.kind()
767 }
768
769 pub fn id(&self) -> Option<&str> {
773 self.payload.id()
774 }
775
776 pub fn ext(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
780 self.payload.ext()
781 }
782
783 pub fn payload(&self) -> &Payload {
786 &self.payload
787 }
788
789 pub(crate) fn payload_mut(&mut self) -> &mut Payload {
790 self.hashes.fields.clear();
791 &mut self.payload
792 }
793
794 pub fn body(&self) -> &Content {
797 &self.body
798 }
799
800 pub fn body_markdown(&self) -> String {
804 quillmark_content::markdown::to_markdown(&self.body)
805 }
806
807 pub(crate) fn set_body(&mut self, body: Content) {
808 self.hashes.body = None;
809 self.body = body;
810 }
811
812 pub(crate) fn remember_hash(&mut self, field: Option<&str>, hash: String) {
814 match field {
815 None => self.hashes.body = Some(hash),
816 Some(name) => {
817 self.hashes.fields.insert(name.to_string(), hash);
818 }
819 }
820 }
821
822 #[cfg(test)]
836 pub(crate) fn field_content(
837 &self,
838 name: &str,
839 codec: Codec,
840 ) -> Option<Result<Content, ContentDecodeError>> {
841 Some(codec.decode_field(self.payload.get(name)?.as_json()))
842 }
843
844 #[cfg(test)]
847 pub(crate) fn field_text(
848 &self,
849 name: &str,
850 codec: Codec,
851 ) -> Option<Result<String, ContentDecodeError>> {
852 Some(
853 codec
854 .decode_field(self.payload.get(name)?.as_json())
855 .map(|c| codec.project(&c)),
856 )
857 }
858}
859
860#[derive(Debug, Clone, PartialEq, Default)]
871pub struct SeedOverlay {
872 pub fields: indexmap::IndexMap<String, crate::value::QuillValue>,
874 pub body: Option<String>,
876}
877
878impl SeedOverlay {
879 pub fn from_json(value: &serde_json::Value) -> Option<Self> {
883 value.as_object().map(Self::from_json_map)
884 }
885
886 fn from_json_map(map: &serde_json::Map<String, serde_json::Value>) -> Self {
888 let mut fields = indexmap::IndexMap::new();
889 let mut body = None;
890 for (key, value) in map {
891 if key == "$body" {
892 if let Some(s) = value.as_str() {
893 body = Some(s.to_string());
894 }
895 } else if key.starts_with('$') {
896 continue;
897 } else {
898 fields.insert(
899 key.clone(),
900 crate::value::QuillValue::from_json(value.clone()),
901 );
902 }
903 }
904 SeedOverlay { fields, body }
905 }
906}
907
908impl Serialize for SeedOverlay {
909 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
910 use serde::ser::SerializeMap;
911 let len = self.fields.len() + usize::from(self.body.is_some());
912 let mut map = serializer.serialize_map(Some(len))?;
913 for (key, value) in &self.fields {
914 map.serialize_entry(key, value.as_json())?;
915 }
916 if let Some(body) = &self.body {
917 map.serialize_entry("$body", body)?;
918 }
919 map.end()
920 }
921}
922
923#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
929#[serde(into = "StoredDocument", try_from = "StoredDocument")]
930pub struct Document {
931 main: Card,
932 cards: Vec<Card>,
933}
934
935impl Document {
936 pub fn new(quill: QuillReference) -> Self {
942 let mut payload = Payload::new();
943 payload.set_quill(quill);
944 payload.set_kind("main");
947 Self {
948 main: Card::from_parts(payload, Content::empty()),
949 cards: Vec::new(),
950 }
951 }
952
953 pub(crate) fn from_main_and_cards(main: Card, mut cards: Vec<Card>) -> Self {
965 debug_assert!(main.quill().is_some(), "main card must carry `$quill`");
966 debug_assert!(
967 cards.iter().all(|c| c.kind().is_some()),
968 "composable cards must carry `$kind`"
969 );
970 debug_assert!(
971 cards.iter().all(|c| c.quill().is_none()),
972 "composable cards must not carry `$quill`"
973 );
974 debug_assert!(
975 cards.iter().all(|c| c.seed().is_none()),
976 "composable cards must not carry `$seed`"
977 );
978 card_id::settle(&mut cards, &std::collections::HashSet::new());
979 Self { main, cards }
980 }
981
982 pub fn from_stored(json: &str) -> Result<Parsed, serde_json::Error> {
987 let stored: StoredDocument = serde_json::from_str(json)?;
988 dto::from_stored(stored).map_err(serde::de::Error::custom)
989 }
990
991 #[doc(alias = "from_markdown")]
997 pub fn parse(markdown: &str) -> Result<Parsed, ParseError> {
998 let mut parsed = Self::parse_unsettled(markdown)?;
999 let reserved = std::collections::HashSet::new();
1000 card_id::settle_reporting(&mut parsed.document.cards, &reserved, &mut parsed.warnings);
1001 Ok(parsed)
1002 }
1003
1004 pub(crate) fn parse_unsettled(markdown: &str) -> Result<Parsed, ParseError> {
1007 assemble::decompose_with_warnings(markdown, import_markdown)
1008 .map(|(document, warnings, _)| Parsed { document, warnings })
1009 }
1010
1011 pub(crate) fn parse_revising(markdown: &str) -> Result<Revising, ParseError> {
1016 let (document, warnings, bodies) = assemble::decompose_with_warnings(
1017 markdown,
1018 quillmark_content::markdown::from_markdown_unresolved,
1019 )?;
1020 Ok(Revising {
1021 parsed: Parsed { document, warnings },
1022 bodies,
1023 })
1024 }
1025
1026 pub fn main(&self) -> &Card {
1027 &self.main
1028 }
1029
1030 pub fn main_mut(&mut self) -> CardMut<'_> {
1031 CardMut::new(&mut self.main)
1032 }
1033
1034 pub fn quill_reference(&self) -> QuillReference {
1036 self.main
1037 .quill()
1038 .cloned()
1039 .expect("root block's $quill is validated at parse time")
1040 }
1041
1042 pub fn cards(&self) -> &[Card] {
1043 &self.cards
1044 }
1045
1046 pub fn card(&self, index: usize) -> Option<&Card> {
1049 self.cards.get(index)
1050 }
1051
1052 pub fn card_index(&self, id: &str) -> Option<usize> {
1054 self.cards.iter().position(|card| card.id() == Some(id))
1055 }
1056
1057 pub fn card_by_id(&self, id: &str) -> Option<&Card> {
1059 self.card_index(id).map(|index| &self.cards[index])
1060 }
1061
1062 pub(crate) fn main_card_mut(&mut self) -> &mut Card {
1063 &mut self.main
1064 }
1065
1066 pub(crate) fn cards_vec_mut(&mut self) -> &mut Vec<Card> {
1067 &mut self.cards
1068 }
1069
1070 pub(crate) fn to_plate_json_gated(
1099 &self,
1100 main_body: bool,
1101 card_bodies: Option<&[bool]>,
1102 ) -> serde_json::Value {
1103 let mut map = serde_json::Map::new();
1104
1105 map.insert(
1106 "$quill".to_string(),
1107 serde_json::Value::String(self.quill_reference().to_string()),
1108 );
1109
1110 if main_body {
1114 map.insert("$body".to_string(), self.main.body().to_value());
1115 }
1116
1117 let cards_array: Vec<serde_json::Value> = self
1118 .cards
1119 .iter()
1120 .enumerate()
1121 .map(|(i, card)| {
1122 let mut card_map = serde_json::Map::new();
1123 if let Some(kind) = card.kind() {
1124 card_map.insert(
1125 "$kind".to_string(),
1126 serde_json::Value::String(kind.to_string()),
1127 );
1128 }
1129 if card_bodies.map_or(true, |f| f.get(i).copied().unwrap_or(true)) {
1131 card_map.insert("$body".to_string(), card.body().to_value());
1132 }
1133 for (key, value) in card.payload.iter() {
1134 card_map.insert(key.clone(), value.as_json().clone());
1135 }
1136 serde_json::Value::Object(card_map)
1137 })
1138 .collect();
1139
1140 map.insert("$cards".to_string(), serde_json::Value::Array(cards_array));
1141
1142 for (key, value) in self.main.payload.iter() {
1143 map.insert(key.clone(), value.as_json().clone());
1144 }
1145
1146 serde_json::Value::Object(map)
1147 }
1148}