Skip to main content

quillmark_core/
reader.rs

1//! Schema-bound typed reader — the read twin of
2//! [`TypedWriter`](crate::TypedWriter).
3//!
4//! The read surface's verbs split by read-vs-write, but the deeper fault line is
5//! **interpret-vs-transport**. The verbatim [`payload().get`](crate::Card::payload)
6//! (the WASM binding's `Document.getStored`) is *transport*: it returns the stored
7//! value verbatim, schema-free and round-trippable — the disambiguation / debug
8//! read. Projecting a field to
9//! markdown is *interpretation*: a schema-shaped question ("this field's
10//! richtext, as markdown") that a schema-free `Document` cannot answer without
11//! guessing which fields are even richtext. [`Card::field_markdown`] carries the
12//! projection but has no schema to name the field set, so an unknown field name
13//! reads back as absent rather than as the typo it is.
14//!
15//! [`Quill::reader`](crate::Quill::reader) binds the schema — where the authority
16//! already lives, the writer's twin — so a single verb interprets by the field's
17//! declared type:
18//!
19//! ```ignore
20//! let v = quill.reader(&doc);
21//! v.get("subject")?;            // richtext → Some(Markdown(..))
22//! v.get("qty")?;                // integer  → Some(Value(3))
23//! v.get("absent")?;             // absent   → None
24//! v.get("nope");                // unknown name → Err(UnknownField)
25//! v.card(2)?.get("body")?;      // card field, kind resolves its schema
26//! ```
27//!
28//! **absence returns; mismatch raises; an unknown name is a typo.** A `richtext`
29//! field projects to markdown ([`ReadValue::Markdown`]) and a `plaintext` field
30//! to its literal text ([`ReadValue::Plaintext`]); every other declared type
31//! returns its canonical value verbatim ([`ReadValue::Value`]) — the same
32//! transport `Document` reads, now reached with schema authority. A present value
33//! that does not decode under a content field raises
34//! [`EditError::FieldRichtextDecode`], the mismatch [`Card::field_markdown`] /
35//! [`Card::field_plaintext`] surfaces. A name the schema does not declare raises
36//! [`EditError::UnknownField`], exactly as [`TypedWriter::set`](crate::TypedWriter::set)
37//! rejects it on the write side.
38//!
39//! The body read stays quill-free: a body's type is a format fact, not a schema
40//! fact, so [`get_body`](TypedReader::get_body) mirrors
41//! [`Card::body_markdown`](crate::Card::body_markdown) rather than consulting the
42//! schema.
43//!
44//! Like [`TypedWriter`](crate::TypedWriter), a bound reader holds `&Document`
45//! and `&QuillConfig`, so
46//! it cannot cross a binding boundary that carries no lifetimes (wasm-bindgen /
47//! pyo3); those surfaces construct one per call from the quill handle.
48
49use indexmap::IndexMap;
50
51use crate::document::{Card, Document, EditError, RichtextDecodeError};
52use crate::quill::{CardSchema, FieldSchema, FieldType, QuillConfig};
53use crate::value::QuillValue;
54
55/// The interpreted value at a field address — the output of [`TypedReader::get`].
56/// A content field decodes to its codec's projection (`richtext` to markdown,
57/// `plaintext` to literal text); every other declared type carries its canonical
58/// value verbatim (the transport read, reached through the schema). Absence is
59/// the `None` of the enclosing `Option`, not a variant here.
60#[derive(Debug, Clone, PartialEq)]
61pub enum ReadValue {
62    /// A `richtext` field projected to markdown (`export ∘ decode`) — the lossy,
63    /// on-demand view (content-only marks do not survive markdown).
64    Markdown(String),
65    /// A `plaintext` field projected through its literal codec (`to_plaintext ∘
66    /// decode`) — verbatim text, marks never interpreted (`*hi*` is four
67    /// characters, not emphasis).
68    Plaintext(String),
69    /// A non-content field's canonical value, verbatim — the schema-free
70    /// transport read a `Document` returns, delivered here with schema authority.
71    Value(QuillValue),
72}
73
74/// A [`Document`] bound to its [`QuillConfig`] for typed reads. Construct with
75/// [`Quill::reader`](crate::Quill::reader). Reads target the main card; use
76/// [`card`](Self::card) for a composable card. The read twin of
77/// [`TypedWriter`](crate::TypedWriter).
78pub struct TypedReader<'a> {
79    config: &'a QuillConfig,
80    doc: &'a Document,
81}
82
83impl<'a> TypedReader<'a> {
84    /// Bind `doc` to `config`. Prefer [`Quill::reader`](crate::Quill::reader).
85    pub fn new(config: &'a QuillConfig, doc: &'a Document) -> Self {
86        Self { config, doc }
87    }
88
89    /// Read a main-card field, interpreted by its declared type — `richtext` to
90    /// markdown ([`ReadValue::Markdown`]), `plaintext` to literal text
91    /// ([`ReadValue::Plaintext`]), every other type verbatim
92    /// ([`ReadValue::Value`]). `Ok(None)` when the field is absent;
93    /// [`EditError::UnknownField`] for a name the schema does not declare (a typo,
94    /// as on the write side); [`EditError::FieldRichtextDecode`] when a content
95    /// field holds a value that does not decode (a scalar an opaque
96    /// [`store_field`](crate::Card::store_field) wrote).
97    pub fn get(&self, name: &str) -> Result<Option<ReadValue>, EditError> {
98        read_field(self.doc.main(), Some(&self.config.main.fields), name)
99    }
100
101    /// The main body's markdown projection — the quill-free body read
102    /// ([`Card::body_markdown`](crate::Card::body_markdown)). A body's type is a
103    /// format fact, not a schema fact, so this consults no schema and never
104    /// raises; the body is never absent.
105    pub fn get_body(&self) -> String {
106        self.doc.main().body_markdown()
107    }
108
109    /// A schema-bound reader for the composable card at `index`. The card's
110    /// `$kind` resolves its [`CardSchema`]; an unknown kind carries no schema, so
111    /// every field name on it is undeclared and reads with
112    /// [`EditError::UnknownField`] (read such a card verbatim through
113    /// [`Card::payload`]). [`EditError::IndexOutOfRange`] when `index` is out of
114    /// range — a boundary error, not an absent field, as the card write verbs
115    /// treat it.
116    pub fn card(&self, index: usize) -> Result<CardReader<'_>, EditError> {
117        let len = self.doc.cards().len();
118        let card = self
119            .doc
120            .card(index)
121            .ok_or(EditError::IndexOutOfRange { index, len })?;
122        let schema = card.kind().and_then(|k| self.config.card_kind(k));
123        Ok(CardReader { schema, card })
124    }
125}
126
127/// A single composable card bound to its [`CardSchema`], from
128/// [`TypedReader::card`]. Same `get` / `get_body` verbs as [`TypedReader`],
129/// reading the card at its bound index.
130pub struct CardReader<'a> {
131    schema: Option<&'a CardSchema>,
132    card: &'a Card,
133}
134
135impl CardReader<'_> {
136    /// The card's `$kind`, if any.
137    pub fn kind(&self) -> Option<&str> {
138        self.card.kind()
139    }
140
141    /// Read a field on this card, interpreted by its declared type — the card
142    /// twin of [`TypedReader::get`]. Resolves the field against the card's
143    /// [`CardSchema`]; a name the schema does not declare — or any name when the
144    /// card kind is unknown — reads with [`EditError::UnknownField`].
145    pub fn get(&self, name: &str) -> Result<Option<ReadValue>, EditError> {
146        read_field(self.card, self.schema.map(|s| &s.fields), name)
147    }
148
149    /// This card's body markdown — the card twin of [`TypedReader::get_body`],
150    /// quill-free and never raising.
151    pub fn get_body(&self) -> String {
152        self.card.body_markdown()
153    }
154}
155
156/// The shared read dispatch behind [`TypedReader::get`] and [`CardReader::get`]:
157/// resolve `name` against `fields_schema` (an unknown name, or every name when
158/// the whole schema is `None` — an unknown card kind — is
159/// [`EditError::UnknownField`]), then interpret by the field's declared type. A
160/// content field projects through its codec — `richtext` via
161/// [`Card::field_markdown`], `plaintext` via [`Card::field_plaintext`] — each
162/// carrying the projection's absent (`None`) / mismatch
163/// ([`EditError::FieldRichtextDecode`]) outcomes; every other type returns its
164/// canonical value verbatim, `None` when absent.
165fn read_field(
166    card: &Card,
167    fields_schema: Option<&IndexMap<String, FieldSchema>>,
168    name: &str,
169) -> Result<Option<ReadValue>, EditError> {
170    let schema = fields_schema
171        .and_then(|m| m.get(name))
172        .ok_or_else(|| EditError::UnknownField(name.to_string()))?;
173    match schema.r#type {
174        FieldType::RichText { .. } => project(card.field_markdown(name), name, ReadValue::Markdown),
175        FieldType::PlainText { .. } => {
176            project(card.field_plaintext(name), name, ReadValue::Plaintext)
177        }
178        _ => Ok(card
179            .payload()
180            .get(name)
181            .map(|v| ReadValue::Value(v.clone()))),
182    }
183}
184
185/// Lift a codec projection ([`Card::field_markdown`] / [`Card::field_plaintext`])
186/// into a [`ReadValue`]: `None` absent, `Some(Ok)` wrapped by `wrap`, `Some(Err)`
187/// the [`EditError::FieldRichtextDecode`] mismatch naming `name`.
188fn project(
189    projection: Option<Result<String, RichtextDecodeError>>,
190    name: &str,
191    wrap: fn(String) -> ReadValue,
192) -> Result<Option<ReadValue>, EditError> {
193    match projection {
194        None => Ok(None),
195        Some(Ok(text)) => Ok(Some(wrap(text))),
196        Some(Err(e)) => Err(EditError::FieldRichtextDecode {
197            field: name.to_string(),
198            message: e.into_message(),
199        }),
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use crate::document::Document;
207    use crate::version::QuillReference;
208    use std::str::FromStr;
209
210    const QUILL_YAML: &str = "\
211quill:
212  name: memo
213  backend: typst
214  version: 1.0.0
215  description: Reader test quill
216main:
217  fields:
218    subject:
219      type: richtext
220      inline: true
221    note:
222      type: plaintext
223    qty:
224      type: integer
225card_kinds:
226  note:
227    fields:
228      body:
229        type: richtext
230";
231
232    fn config() -> QuillConfig {
233        QuillConfig::from_yaml(QUILL_YAML).expect("valid quill")
234    }
235
236    fn blank_doc() -> Document {
237        Document::new(QuillReference::from_str("memo@1.0.0").unwrap())
238    }
239
240    // Build a document through the writer, then read it back through the view.
241    fn seeded_doc(config: &QuillConfig) -> Document {
242        let mut doc = blank_doc();
243        {
244            let mut w = crate::TypedWriter::new(config, &mut doc);
245            w.set("subject", "Hello **world**").unwrap();
246            w.set("qty", "3").unwrap();
247            w.add_card("note", [("body", "a *card*")], None, None).unwrap();
248        }
249        doc
250    }
251
252    #[test]
253    fn richtext_field_projects_to_markdown() {
254        let config = config();
255        let doc = seeded_doc(&config);
256        let view = TypedReader::new(&config, &doc);
257        assert_eq!(
258            view.get("subject").unwrap(),
259            Some(ReadValue::Markdown("Hello **world**".to_string()))
260        );
261    }
262
263    #[test]
264    fn plaintext_field_projects_to_literal_text() {
265        let config = config();
266        let mut doc = blank_doc();
267        {
268            let mut w = crate::TypedWriter::new(&config, &mut doc);
269            // Marks are literal under plaintext: `*hi*` is verbatim, not emphasis.
270            w.set("note", "a *literal* line").unwrap();
271        }
272        let view = TypedReader::new(&config, &doc);
273        assert_eq!(
274            view.get("note").unwrap(),
275            Some(ReadValue::Plaintext("a *literal* line".to_string()))
276        );
277    }
278
279    #[test]
280    fn scalar_field_returns_canonical_value() {
281        let config = config();
282        let doc = seeded_doc(&config);
283        let view = TypedReader::new(&config, &doc);
284        assert_eq!(
285            view.get("qty").unwrap(),
286            Some(ReadValue::Value(QuillValue::from_json(serde_json::json!(3))))
287        );
288    }
289
290    #[test]
291    fn absent_field_returns_none() {
292        let config = config();
293        let doc = blank_doc();
294        let view = TypedReader::new(&config, &doc);
295        assert_eq!(view.get("subject").unwrap(), None);
296        assert_eq!(view.get("qty").unwrap(), None);
297    }
298
299    #[test]
300    fn unknown_field_name_raises() {
301        let config = config();
302        let doc = blank_doc();
303        let view = TypedReader::new(&config, &doc);
304        assert!(matches!(
305            view.get("nope"),
306            Err(EditError::UnknownField(name)) if name == "nope"
307        ));
308    }
309
310    #[test]
311    fn richtext_field_holding_scalar_raises_mismatch() {
312        let config = config();
313        let mut doc = blank_doc();
314        // An opaque write puts a bare number under the `subject` richtext field.
315        doc.main_mut()
316            .store_field("subject", QuillValue::from_json(serde_json::json!(3)))
317            .unwrap();
318        let view = TypedReader::new(&config, &doc);
319        assert!(matches!(
320            view.get("subject"),
321            Err(EditError::FieldRichtextDecode { field, .. }) if field == "subject"
322        ));
323    }
324
325    #[test]
326    fn card_field_reads_through_kind_schema() {
327        let config = config();
328        let doc = seeded_doc(&config);
329        let view = TypedReader::new(&config, &doc);
330        let card = view.card(0).unwrap();
331        assert_eq!(card.kind(), Some("note"));
332        assert_eq!(
333            card.get("body").unwrap(),
334            Some(ReadValue::Markdown("a *card*".to_string()))
335        );
336        assert!(matches!(card.get("nope"), Err(EditError::UnknownField(_))));
337    }
338
339    #[test]
340    fn card_out_of_range_raises() {
341        let config = config();
342        let doc = blank_doc();
343        let view = TypedReader::new(&config, &doc);
344        assert!(matches!(
345            view.card(9),
346            Err(EditError::IndexOutOfRange { index: 9, len: 0 })
347        ));
348    }
349
350    #[test]
351    fn body_read_is_quill_free() {
352        let config = config();
353        let mut doc = blank_doc();
354        doc.main_mut().revise_body("A **body**.").unwrap();
355        let view = TypedReader::new(&config, &doc);
356        assert_eq!(view.get_body(), "A **body**.");
357    }
358}