Skip to main content

quillmark_core/document/
payload.rs

1//! Unified payload representation.
2//!
3//! A [`Payload`] is the typed representation of a card-yaml block's full
4//! YAML content. It carries, in source order, as variants of a single
5//! [`PayloadItem`] enum:
6//!
7//! - **System metadata**: typed `$quill` / `$kind` / `$ext` / `$seed`
8//!   entries.
9//! - **User fields**: `key: value` pairs with an optional `!must_fill` flag.
10//! - **Comments**: own-line or trailing inline, attached to whichever
11//!   item they immediately follow at emit time.
12//!
13//! The unified item list is the canonical storage of the block; treating
14//! `$` entries as just another variant means a comment adjacent to a `$`
15//! line round-trips through the same mechanism as a comment adjacent to a
16//! user field. No "metadata region" vs "payload region" routing decision is
17//! ever made: there is only the source-ordered list.
18//!
19//! ## Comments at every level
20//!
21//! Top-level YAML comments (own-line and trailing inline) live as
22//! `PayloadItem::Comment` entries interleaved with fields and `$` items.
23//! Comments **inside** a structured value (mapping or sequence) live on
24//! the [`PayloadItem::Field`] / [`PayloadItem::Meta`] that owns that
25//! value, as a `nested_comments` slice with paths relative to the
26//! field's value tree. One storage surface, scoped to the item that
27//! "owns" each comment: no sidecar Vec hanging off `Payload`.
28//!
29//! ## Two faces
30//!
31//! [`Payload`] exposes both ordered iteration (over the raw items vec) and
32//! map-keyed access (`get`, `iter`, `insert`, `remove`). The map-style
33//! accessors filter to [`PayloadItem::Field`] only: they intentionally
34//! don't expose `$` entries because typed `$` access has dedicated methods
35//! (`quill`, `kind`, `ext`, `seed`, `set_quill`, `set_kind`, `set_ext`,
36//! `set_seed`).
37//!
38//! The map-style accessors present the payload as a key/value map of user
39//! data, while comment preservation and `$` access ride on the same
40//! underlying storage.
41
42use indexmap::IndexMap;
43use serde_json::{Map as JsonMap, Value as JsonValue};
44
45use super::prescan::{CommentPathSegment, NestedComment};
46use crate::value::QuillValue;
47use crate::version::QuillReference;
48
49/// Which out-of-band system-metadata map a [`PayloadItem::Meta`] carries.
50///
51/// `$ext` and `$seed` are the same shape: an opaque `Map<String, Value>` that
52/// never reaches the plate JSON and round-trips through Markdown and the storage
53/// DTO, so the live model represents them as one variant discriminated by this
54/// key. They differ only in their canonical sort rank, whether they are
55/// root-only, and (downstream of storage) whether the seeding layer interprets
56/// them: `$ext` is opaque; `$seed` is read by [`crate::SeedOverlay::from_json`].
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58#[non_exhaustive]
59pub enum MetaKey {
60    /// `$ext`: opaque out-of-band consumer state (editor renames, agent
61    /// annotations). Allowed on any card.
62    Ext,
63    /// `$seed`: per-card-kind seed overlays. **Root-only** (like `$quill`).
64    Seed,
65}
66
67impl MetaKey {
68    /// The literal source key (`"$ext"` / `"$seed"`).
69    pub fn as_str(self) -> &'static str {
70        match self {
71            MetaKey::Ext => "$ext",
72            MetaKey::Seed => "$seed",
73        }
74    }
75
76    /// Parse the source key (`"$ext"` / `"$seed"`), or `None` for any other key.
77    pub fn from_key_str(key: &str) -> Option<Self> {
78        match key {
79            "$ext" => Some(MetaKey::Ext),
80            "$seed" => Some(MetaKey::Seed),
81            _ => None,
82        }
83    }
84
85    /// Canonical sort rank among typed `$` entries (after `$kind`).
86    fn rank(self) -> u8 {
87        match self {
88            MetaKey::Ext => 2,
89            MetaKey::Seed => 3,
90        }
91    }
92
93    /// `true` when the key may appear on the root card only (rejected on
94    /// composable cards), like `$quill`.
95    pub fn is_root_only(self) -> bool {
96        matches!(self, MetaKey::Seed)
97    }
98}
99
100/// One entry in a [`Payload`]: a typed `$` system metadata entry, a user
101/// field, or a comment line.
102///
103/// `PayloadItem` is the live in-memory model; it is intentionally **not**
104/// `Serialize`/`Deserialize`. Storage uses the versioned DTOs in
105/// `document::dto`, and bindings translate to their own wire types.
106#[derive(Debug, Clone, PartialEq)]
107#[non_exhaustive]
108pub enum PayloadItem {
109    /// `$quill` system metadata, holding the parsed quill reference.
110    Quill { reference: QuillReference },
111    /// `$kind` system metadata: the card's kind name.
112    Kind { value: String },
113    /// `$ext` / `$seed` system metadata: an opaque mapping (discriminated by
114    /// [`MetaKey`]) reserved for out-of-band data. Never emitted into the plate
115    /// JSON, always round-trips through Markdown and the storage DTO.
116    /// `nested_comments` carries YAML comments inside the mapping; paths are
117    /// **relative** to the value tree (the `$ext` / `$seed` key itself is not
118    /// part of the path). `$seed` is additionally interpreted by the seeding
119    /// layer; see [`crate::SeedOverlay::from_json`] and [`crate::Quill::seed_card`].
120    Meta {
121        key: MetaKey,
122        value: JsonMap<String, JsonValue>,
123        nested_comments: Vec<NestedComment>,
124    },
125    /// A user-defined YAML field, optionally tagged `!must_fill`.
126    ///
127    /// `nested_comments` carries YAML comments inside the field's value
128    /// (only meaningful when the value is a mapping or sequence); paths
129    /// are **relative** to the field's value tree (the field's key is
130    /// not part of the path).
131    Field {
132        key: String,
133        value: QuillValue,
134        /// `true` when the field was written as `key: !must_fill <value>` or
135        /// `key: !must_fill` in source.
136        fill: bool,
137        nested_comments: Vec<NestedComment>,
138    },
139    /// A YAML comment. Text excludes the leading `#` and one optional space.
140    ///
141    /// `inline` distinguishes own-line comments (`# text` on a line by
142    /// itself) from trailing inline comments (`field: value # text`). An
143    /// inline comment attaches to the item that immediately precedes it
144    /// in the items vector; if no such item exists at emit time (orphan)
145    /// it degrades to an own-line comment.
146    Comment { text: String, inline: bool },
147}
148
149impl PayloadItem {
150    /// Build a plain (non-fill) field entry with no nested comments.
151    pub fn field(key: impl Into<String>, value: QuillValue) -> Self {
152        PayloadItem::Field {
153            key: key.into(),
154            value,
155            fill: false,
156            nested_comments: Vec::new(),
157        }
158    }
159
160    /// Borrow the field/meta nested-comments slice. Returns `&[]` for
161    /// variants that don't carry nested comments.
162    pub fn nested_comments(&self) -> &[NestedComment] {
163        match self {
164            PayloadItem::Field {
165                nested_comments, ..
166            }
167            | PayloadItem::Meta {
168                nested_comments, ..
169            } => nested_comments,
170            _ => &[],
171        }
172    }
173
174    pub fn comment(text: impl Into<String>) -> Self {
175        PayloadItem::Comment {
176            text: text.into(),
177            inline: false,
178        }
179    }
180
181    pub fn comment_inline(text: impl Into<String>) -> Self {
182        PayloadItem::Comment {
183            text: text.into(),
184            inline: true,
185        }
186    }
187
188    /// Canonical sort rank for typed `$` entries: `$quill` < `$kind` <
189    /// `$ext` < `$seed`. Returns `None` for user fields and comments,
190    /// which are positioned by source order and never reshuffled.
191    fn meta_rank(&self) -> Option<u8> {
192        match self {
193            PayloadItem::Quill { .. } => Some(0),
194            PayloadItem::Kind { .. } => Some(1),
195            PayloadItem::Meta { key, .. } => Some(key.rank()),
196            _ => None,
197        }
198    }
199}
200
201/// Ordered, comment-preserving payload of a card-yaml block.
202///
203/// Contains the block's `$` entries, user fields, and comments interleaved
204/// in source order. See the module docs for the full design.
205#[derive(Debug, Clone, PartialEq, Default)]
206pub struct Payload {
207    items: Vec<PayloadItem>,
208}
209
210impl Payload {
211    /// Create an empty `Payload`.
212    pub fn new() -> Self {
213        Self::default()
214    }
215
216    /// Build from an `IndexMap` of user fields. No `$` entries, no
217    /// comments, no fill markers.
218    pub fn from_index_map(map: IndexMap<String, QuillValue>) -> Self {
219        let items = map
220            .into_iter()
221            .map(|(key, value)| PayloadItem::Field {
222                key,
223                value,
224                fill: false,
225                nested_comments: Vec::new(),
226            })
227            .collect();
228        Self { items }
229    }
230
231    /// Build from a pre-computed item list (parser and DTO entry point).
232    pub fn from_items(items: Vec<PayloadItem>) -> Self {
233        Self { items }
234    }
235
236    /// Build from a pre-computed item list plus a flat absolute-path
237    /// `nested_comments` Vec, partitioning the latter onto the matching
238    /// [`PayloadItem::Field`] / [`PayloadItem::Meta`] items.
239    ///
240    /// The first segment of each comment's `container_path` must be a
241    /// `Key(field)` matching a Field or Meta (`$ext` / `$seed`) entry in `items`;
242    /// that first segment is stripped and the remainder attached to the
243    /// owning item. Comments whose first segment matches nothing in
244    /// `items` are dropped silently: this can only arise from a
245    /// hand-crafted storage DTO that references a non-existent field.
246    pub(crate) fn from_items_with_flat_nested(
247        mut items: Vec<PayloadItem>,
248        nested_comments: Vec<NestedComment>,
249    ) -> Self {
250        for nc in nested_comments {
251            let Some((first, rest)) = nc.container_path.split_first() else {
252                // Empty path can't address any user field; drop.
253                continue;
254            };
255            let target_key = match first {
256                CommentPathSegment::Key(k) => k.clone(),
257                CommentPathSegment::Index(_) => continue,
258            };
259
260            let relative = NestedComment {
261                container_path: rest.to_vec(),
262                position: nc.position,
263                text: nc.text,
264                inline: nc.inline,
265            };
266
267            // `$ext` / `$seed` are encoded with their literal key at the head
268            // of the path; everything else is a user field.
269            let slot = if let Some(meta_key) = MetaKey::from_key_str(&target_key) {
270                items.iter_mut().find_map(|i| match i {
271                    PayloadItem::Meta {
272                        key,
273                        nested_comments,
274                        ..
275                    } if *key == meta_key => Some(nested_comments),
276                    _ => None,
277                })
278            } else {
279                items.iter_mut().find_map(|i| match i {
280                    PayloadItem::Field {
281                        key,
282                        nested_comments,
283                        ..
284                    } if key == &target_key => Some(nested_comments),
285                    _ => None,
286                })
287            };
288            if let Some(slot) = slot {
289                slot.push(relative);
290            }
291        }
292        Self { items }
293    }
294
295    /// Walk every Field/Meta item and yield each nested comment with its
296    /// path re-prefixed by the owning item's key (`$ext` / `$seed` for Meta,
297    /// the field key for Field). Used by the storage DTO conversion to
298    /// flatten the per-item storage back to the wire format's
299    /// payload-level sidecar.
300    pub(crate) fn flat_nested_comments(&self) -> Vec<NestedComment> {
301        let mut out = Vec::new();
302        for item in &self.items {
303            let (prefix, comments) = match item {
304                PayloadItem::Field {
305                    key,
306                    nested_comments,
307                    ..
308                } => (key.clone(), nested_comments),
309                PayloadItem::Meta {
310                    key,
311                    nested_comments,
312                    ..
313                } => (key.as_str().to_string(), nested_comments),
314                _ => continue,
315            };
316            for nc in comments {
317                let mut path = Vec::with_capacity(nc.container_path.len() + 1);
318                path.push(CommentPathSegment::Key(prefix.clone()));
319                path.extend(nc.container_path.iter().cloned());
320                out.push(NestedComment {
321                    container_path: path,
322                    position: nc.position,
323                    text: nc.text.clone(),
324                    inline: nc.inline,
325                });
326            }
327        }
328        out
329    }
330
331    // ── Item-level access ───────────────────────────────────────────────────
332
333    /// Ordered iterator over raw items (`$` entries, fields, comments).
334    pub fn items(&self) -> &[PayloadItem] {
335        &self.items
336    }
337
338    /// Mutable access to the raw item list. Callers must preserve the
339    /// invariants (at most one `Quill`/`Kind`/`Id`/`Ext`, no duplicate
340    /// field keys, every field name matches `[A-Za-z_][A-Za-z0-9_]*`): use
341    /// the typed mutators when in doubt.
342    pub fn items_mut(&mut self) -> &mut [PayloadItem] {
343        &mut self.items
344    }
345
346    /// Remove the first item matching `pred` and return it. The typed
347    /// removers (`take_meta`, `remove`) wrap this and destructure
348    /// the returned variant, which `pred` guarantees.
349    fn take_item(&mut self, pred: impl Fn(&PayloadItem) -> bool) -> Option<PayloadItem> {
350        let pos = self.items.iter().position(pred)?;
351        Some(self.items.remove(pos))
352    }
353
354    // ── Typed `$` access ────────────────────────────────────────────────────
355
356    /// The `$quill` reference, if declared.
357    pub fn quill(&self) -> Option<&QuillReference> {
358        self.items.iter().find_map(|i| match i {
359            PayloadItem::Quill { reference } => Some(reference),
360            _ => None,
361        })
362    }
363
364    /// The `$kind` value, if declared.
365    pub fn kind(&self) -> Option<&str> {
366        self.items.iter().find_map(|i| match i {
367            PayloadItem::Kind { value } => Some(value.as_str()),
368            _ => None,
369        })
370    }
371
372    /// The map for the given out-of-band meta key, if declared.
373    pub(crate) fn meta(&self, want: MetaKey) -> Option<&JsonMap<String, JsonValue>> {
374        self.items.iter().find_map(|i| match i {
375            PayloadItem::Meta { key, value, .. } if *key == want => Some(value),
376            _ => None,
377        })
378    }
379
380    /// The `$ext` map, if declared. The map is opaque: Quillmark does not
381    /// interpret its contents and never emits them into the plate JSON.
382    pub fn ext(&self) -> Option<&JsonMap<String, JsonValue>> {
383        self.meta(MetaKey::Ext)
384    }
385
386    /// The raw `$seed` map (keyed by card-kind), if declared. The seeding
387    /// layer interprets it; it never reaches the plate JSON. For a parsed,
388    /// per-kind overlay, index this map by kind and pass the entry to
389    /// [`crate::SeedOverlay::from_json`].
390    pub fn seed(&self) -> Option<&JsonMap<String, JsonValue>> {
391        self.meta(MetaKey::Seed)
392    }
393
394    /// Set or replace the `$quill` entry. Inserts at canonical position
395    /// (before any `$kind` / `$ext` / `$seed`) when adding. Comments are
396    /// untouched.
397    pub fn set_quill(&mut self, reference: QuillReference) {
398        self.upsert_meta(PayloadItem::Quill { reference });
399    }
400
401    /// Set or replace the `$kind` entry. Same insertion rules as
402    /// [`set_quill`](Self::set_quill).
403    pub fn set_kind(&mut self, kind: impl Into<String>) {
404        self.upsert_meta(PayloadItem::Kind { value: kind.into() });
405    }
406
407    /// Set or replace an out-of-band meta entry at its canonical position.
408    /// Nested comments on a replaced entry are dropped (the new value tree
409    /// may not contain matching positions).
410    pub(crate) fn set_meta(&mut self, key: MetaKey, value: JsonMap<String, JsonValue>) {
411        self.upsert_meta(PayloadItem::Meta {
412            key,
413            value,
414            nested_comments: Vec::new(),
415        });
416    }
417
418    /// Set or replace the `$ext` entry. Same insertion rules as
419    /// [`set_quill`](Self::set_quill); the canonical position is after
420    /// `$quill` / `$kind` and before any user field.
421    ///
422    /// Nested comments on a replaced `$ext` entry are dropped (the new value
423    /// tree may not contain matching positions).
424    pub fn set_ext(&mut self, value: JsonMap<String, JsonValue>) {
425        self.set_meta(MetaKey::Ext, value);
426    }
427
428    /// Set or replace the `$seed` entry. Inserted at the canonical position
429    /// (after `$quill` / `$kind` / `$ext`, before any user field).
430    /// Nested comments on a replaced `$seed` are dropped, like
431    /// [`set_ext`](Self::set_ext).
432    pub fn set_seed(&mut self, value: JsonMap<String, JsonValue>) {
433        self.set_meta(MetaKey::Seed, value);
434    }
435
436    /// Remove an out-of-band meta entry, returning the previous map if any.
437    /// Any nested comments attached to the entry are dropped.
438    pub(crate) fn take_meta(&mut self, want: MetaKey) -> Option<JsonMap<String, JsonValue>> {
439        match self.take_item(|i| matches!(i, PayloadItem::Meta { key, .. } if *key == want))? {
440            PayloadItem::Meta { value, .. } => Some(value),
441            _ => unreachable!(),
442        }
443    }
444
445    /// Remove the `$ext` entry, returning the previous map if any. Any
446    /// nested comments attached to the entry are dropped.
447    pub fn take_ext(&mut self) -> Option<JsonMap<String, JsonValue>> {
448        self.take_meta(MetaKey::Ext)
449    }
450
451    /// Remove the `$seed` entry, returning the previous map if any. Any
452    /// nested comments attached to the entry are dropped.
453    pub fn take_seed(&mut self) -> Option<JsonMap<String, JsonValue>> {
454        self.take_meta(MetaKey::Seed)
455    }
456
457    fn upsert_meta(&mut self, new: PayloadItem) {
458        let new_rank = new
459            .meta_rank()
460            .expect("upsert_meta only accepts $-typed items");
461        for slot in self.items.iter_mut() {
462            if slot.meta_rank() == Some(new_rank) {
463                *slot = new;
464                return;
465            }
466        }
467        let insert_at = self
468            .items
469            .iter()
470            .position(|i| matches!(i.meta_rank(), Some(r) if r > new_rank))
471            .unwrap_or_else(|| {
472                // No higher-ranked `$` item; insert after the last lower
473                // (or equal-rank-impossible) `$` item, before any non-`$`
474                // entry. This keeps the `$quill < $kind < $ext` ordering
475                // while not displacing user fields.
476                self.items
477                    .iter()
478                    .rposition(|i| matches!(i.meta_rank(), Some(r) if r < new_rank))
479                    .map(|p| p + 1)
480                    .unwrap_or(0)
481            });
482        self.items.insert(insert_at, new);
483    }
484
485    // ── User-field access (map-style, `$` entries filtered out) ─────────────
486
487    /// Iterator over user `(key, &value)` pairs. Excludes `$` entries and
488    /// comments; preserves source order.
489    pub fn iter(&self) -> impl Iterator<Item = (&String, &QuillValue)> + '_ {
490        self.items.iter().filter_map(|item| match item {
491            PayloadItem::Field { key, value, .. } => Some((key, value)),
492            _ => None,
493        })
494    }
495
496    /// Iterator over user field keys.
497    pub fn keys(&self) -> impl Iterator<Item = &String> + '_ {
498        self.items.iter().filter_map(|item| match item {
499            PayloadItem::Field { key, .. } => Some(key),
500            _ => None,
501        })
502    }
503
504    /// Number of *user-field* items (`$` entries and comments excluded).
505    pub fn len(&self) -> usize {
506        self.items
507            .iter()
508            .filter(|item| matches!(item, PayloadItem::Field { .. }))
509            .count()
510    }
511
512    /// `true` when there are no user-field items.
513    pub fn is_empty(&self) -> bool {
514        self.len() == 0
515    }
516
517    /// Look up a user-field value by key. `$` entries are not visible via
518    /// this accessor: use [`quill`](Self::quill) / [`kind`](Self::kind) /
519    /// [`ext`](Self::ext) / [`seed`](Self::seed).
520    pub fn get(&self, key: &str) -> Option<&QuillValue> {
521        self.items.iter().find_map(|item| match item {
522            PayloadItem::Field { key: k, value, .. } if k == key => Some(value),
523            _ => None,
524        })
525    }
526
527    /// `true` if a user field with this key is present.
528    pub fn contains_key(&self, key: &str) -> bool {
529        self.get(key).is_some()
530    }
531
532    /// `true` if a user field with this key is marked `!must_fill`.
533    pub fn is_fill(&self, key: &str) -> bool {
534        self.items.iter().any(|item| match item {
535            PayloadItem::Field { key: k, fill, .. } => k == key && *fill,
536            _ => false,
537        })
538    }
539
540    /// Insert or update a user field, clearing any `!must_fill` marker.
541    /// Preserves position for an existing key; appends a new one. `$` entries
542    /// and comments are untouched; replacing a field discards its
543    /// `nested_comments` (the new value tree may not carry matching positions).
544    ///
545    /// Validates the field name and value depth
546    /// ([`validate_field`](super::edit::validate_field)) at this boundary, so
547    /// the "a constructed document cannot be invalid" invariant holds even for
548    /// the direct `Payload` path reachable through
549    /// [`Card::payload_mut`](super::Card::payload_mut). Pre-validated callers
550    /// (typed commit, all-or-nothing batches) use `insert_unchecked` to skip the
551    /// redundant check.
552    pub fn insert(
553        &mut self,
554        key: impl Into<String>,
555        value: QuillValue,
556    ) -> Result<Option<QuillValue>, super::edit::FieldViolation> {
557        let key = key.into();
558        super::edit::validate_field(&key, value.as_json())?;
559        Ok(self.insert_item(key, value, false))
560    }
561
562    /// Insert or update a user field and mark it a `!must_fill` placeholder;
563    /// same rules and boundary validation as [`insert`](Self::insert).
564    pub fn insert_fill(
565        &mut self,
566        key: impl Into<String>,
567        value: QuillValue,
568    ) -> Result<Option<QuillValue>, super::edit::FieldViolation> {
569        let key = key.into();
570        super::edit::validate_field(&key, value.as_json())?;
571        Ok(self.insert_item(key, value, true))
572    }
573
574    /// [`insert`](Self::insert) without the field-invariant check. `pub(crate)`
575    /// for callers that have already validated the exact stored `(name, value)`:
576    /// `resolve_field_write` and the batch setters that validate the whole
577    /// batch before applying any of it.
578    pub(crate) fn insert_unchecked(
579        &mut self,
580        key: impl Into<String>,
581        value: QuillValue,
582    ) -> Option<QuillValue> {
583        self.insert_item(key.into(), value, false)
584    }
585
586    /// Insert or replace field `key` with `value`, setting its fill marker.
587    /// Position-preserving for an existing key, append otherwise.
588    fn insert_item(&mut self, key: String, value: QuillValue, fill: bool) -> Option<QuillValue> {
589        for item in self.items.iter_mut() {
590            if let PayloadItem::Field {
591                key: k,
592                value: v,
593                fill: item_fill,
594                nested_comments,
595            } = item
596            {
597                if k == &key {
598                    let old = std::mem::replace(v, value);
599                    *item_fill = fill;
600                    nested_comments.clear();
601                    return Some(old);
602                }
603            }
604        }
605        self.items.push(PayloadItem::Field {
606            key,
607            value,
608            fill,
609            nested_comments: Vec::new(),
610        });
611        None
612    }
613
614    /// Remove a user field by key, returning its value. Comments and `$`
615    /// entries are untouched.
616    pub fn remove(&mut self, key: &str) -> Option<QuillValue> {
617        match self.take_item(|item| matches!(item, PayloadItem::Field { key: k, .. } if k == key))? {
618            PayloadItem::Field { value, .. } => Some(value),
619            _ => unreachable!(),
620        }
621    }
622
623    /// Project the user-field portion into an `IndexMap<String, QuillValue>`.
624    /// Comments, fill markers, and `$` entries are dropped. Preserves order.
625    pub fn to_index_map(&self) -> IndexMap<String, QuillValue> {
626        let mut map = IndexMap::new();
627        for item in &self.items {
628            if let PayloadItem::Field { key, value, .. } = item {
629                map.insert(key.clone(), value.clone());
630            }
631        }
632        map
633    }
634}
635
636impl<'a> IntoIterator for &'a Payload {
637    type Item = (&'a String, &'a QuillValue);
638    type IntoIter = std::iter::FilterMap<
639        std::slice::Iter<'a, PayloadItem>,
640        fn(&'a PayloadItem) -> Option<(&'a String, &'a QuillValue)>,
641    >;
642
643    fn into_iter(self) -> Self::IntoIter {
644        fn filter(item: &PayloadItem) -> Option<(&String, &QuillValue)> {
645            match item {
646                PayloadItem::Field { key, value, .. } => Some((key, value)),
647                _ => None,
648            }
649        }
650        self.items.iter().filter_map(filter)
651    }
652}
653
654#[cfg(test)]
655mod tests {
656    use super::*;
657
658    fn qv(s: &str) -> QuillValue {
659        QuillValue::from_json(serde_json::json!(s))
660    }
661
662    #[test]
663    fn insert_new_appends_after_meta() {
664        let mut fm = Payload::new();
665        fm.set_quill("foo@0.1".parse().unwrap());
666        fm.set_kind("main");
667        fm.insert("title", qv("Hello")).unwrap();
668        let last = fm.items().last().unwrap();
669        assert!(matches!(last, PayloadItem::Field { key, .. } if key == "title"));
670    }
671
672    #[test]
673    fn insert_existing_preserves_position() {
674        let mut fm = Payload::new();
675        fm.insert("a", qv("1")).unwrap();
676        fm.insert("b", qv("2")).unwrap();
677        fm.insert("a", qv("updated")).unwrap();
678        let keys: Vec<&String> = fm.keys().collect();
679        assert_eq!(keys, vec!["a", "b"]);
680        assert_eq!(fm.get("a").unwrap().as_str(), Some("updated"));
681    }
682
683    #[test]
684    fn insert_clears_fill() {
685        let mut fm = Payload::new();
686        fm.insert_fill("k", qv("placeholder")).unwrap();
687        assert!(fm.is_fill("k"));
688        fm.insert("k", qv("user value")).unwrap();
689        assert!(!fm.is_fill("k"));
690    }
691
692    #[test]
693    fn insert_enforces_the_field_invariant() {
694        use super::super::edit::FieldViolation;
695
696        // A malformed name is refused: `payload_mut().insert(...)` cannot seat
697        // an invalid field in a "constructed" document.
698        let mut fm = Payload::new();
699        assert_eq!(fm.insert("bad name", qv("v")), Err(FieldViolation::InvalidName));
700        assert_eq!(fm.insert("$id", qv("v")), Err(FieldViolation::InvalidName));
701        assert_eq!(
702            fm.insert_fill("bad name", qv("v")),
703            Err(FieldViolation::InvalidName)
704        );
705
706        // Over-deep value.
707        let mut deep = serde_json::json!(0);
708        for _ in 0..(crate::document::limits::MAX_YAML_DEPTH + 5) {
709            deep = serde_json::json!([deep]);
710        }
711        assert_eq!(
712            fm.insert("field", QuillValue::from_json(deep)),
713            Err(FieldViolation::TooDeep)
714        );
715
716        // Nothing was applied on any rejection.
717        assert!(fm.items().is_empty());
718
719        // The unchecked path is the deliberate escape hatch: no validation.
720        fm.insert_unchecked("bad name", qv("v"));
721        assert_eq!(fm.items().len(), 1);
722    }
723
724    #[test]
725    fn map_style_iter_skips_meta_and_comments() {
726        let mut fm = Payload::new();
727        fm.set_quill("foo@0.1".parse().unwrap());
728        fm.set_kind("main");
729        let _ = fm.insert("title", qv("Hello"));
730        let items = std::mem::take(&mut fm).items().to_vec();
731        // Reconstruct with an interleaved comment.
732        let mut items_with_comment = items;
733        items_with_comment.insert(2, PayloadItem::comment("c"));
734        let fm = Payload::from_items(items_with_comment);
735        let pairs: Vec<(String, String)> = fm
736            .iter()
737            .map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_string()))
738            .collect();
739        assert_eq!(pairs, vec![("title".to_string(), "Hello".to_string())]);
740        // But the typed access still works:
741        assert_eq!(fm.kind(), Some("main"));
742    }
743
744    #[test]
745    fn set_quill_inserts_at_position_zero() {
746        let mut fm = Payload::new();
747        fm.set_kind("main");
748        fm.set_quill("foo@0.1".parse().unwrap());
749        assert!(matches!(fm.items()[0], PayloadItem::Quill { .. }));
750        assert!(matches!(fm.items()[1], PayloadItem::Kind { .. }));
751    }
752
753    #[test]
754    fn set_replaces_in_place_preserving_comments() {
755        let mut fm = Payload::from_items(vec![
756            PayloadItem::Quill {
757                reference: "foo@0.1".parse().unwrap(),
758            },
759            PayloadItem::comment_inline("trailing"),
760            PayloadItem::Kind {
761                value: "main".into(),
762            },
763        ]);
764        fm.set_quill("bar@0.2".parse().unwrap());
765        assert_eq!(fm.quill().unwrap().to_string(), "bar@0.2");
766        assert_eq!(fm.items().len(), 3);
767        assert!(matches!(fm.items()[1], PayloadItem::Comment { .. }));
768    }
769
770    #[test]
771    fn remove_leaves_comments_and_meta_alone() {
772        let mut fm = Payload::from_items(vec![
773            PayloadItem::Quill {
774                reference: "q".parse().unwrap(),
775            },
776            PayloadItem::Kind {
777                value: "main".into(),
778            },
779            PayloadItem::comment("header"),
780            PayloadItem::field("a", qv("1")),
781            PayloadItem::comment("mid"),
782            PayloadItem::field("b", qv("2")),
783        ]);
784        let removed = fm.remove("a").unwrap();
785        assert_eq!(removed.as_str(), Some("1"));
786        assert!(matches!(fm.items()[0], PayloadItem::Quill { .. }));
787        assert!(matches!(fm.items()[1], PayloadItem::Kind { .. }));
788        let comments: Vec<&str> = fm
789            .items()
790            .iter()
791            .filter_map(|item| match item {
792                PayloadItem::Comment { text, .. } => Some(text.as_str()),
793                _ => None,
794            })
795            .collect();
796        assert_eq!(comments, vec!["header", "mid"]);
797    }
798}