quillmark_core/document/edit.rs
1//! Typed mutators for [`Document`] and [`Card`] with invariant enforcement.
2//!
3//! Every successful mutator leaves the document with every user field name
4//! matching `[a-z_][a-z0-9_]*` and every composable `$kind` passing
5//! `meta::is_valid_kind_name`, so the result is safely serializable via
6//! [`Document::to_plate_json`]. Mutators never modify `warnings` — those
7//! are immutable parse-time observations.
8//!
9//! Payload/body mutators live on [`Card`] (`set_field`, `set_fill`,
10//! `remove_field`, `set_ext`, `remove_ext`, `set_ext_namespace`,
11//! `remove_ext_namespace`, `replace_body`); [`Document`] keeps
12//! document-level ops (quill-ref, push/insert/remove/move card).
13//!
14//! The `$ext` mutators are unguarded: `$ext` is an opaque mapping that
15//! never reaches the plate JSON backends consume, so there is no field-name
16//! or kind invariant to enforce — only that the value is a mapping, which
17//! the types already guarantee.
18
19use unicode_normalization::UnicodeNormalization;
20
21use crate::document::meta::{validate_composable_kind, CardKindError};
22use crate::document::{Card, Document, Payload};
23use crate::value::QuillValue;
24use crate::version::QuillReference;
25
26/// `true` if `name` matches `[a-z_][a-z0-9_]*` after NFC normalisation.
27pub fn is_valid_field_name(name: &str) -> bool {
28 let normalized: String = name.nfc().collect();
29 if normalized.is_empty() {
30 return false;
31 }
32 let mut chars = normalized.chars();
33 let first = chars.next().unwrap();
34 if !first.is_ascii_lowercase() && first != '_' {
35 return false;
36 }
37 for ch in chars {
38 if !ch.is_ascii_lowercase() && !ch.is_ascii_digit() && ch != '_' {
39 return false;
40 }
41 }
42 true
43}
44
45/// Errors returned by document and card mutators.
46#[derive(Debug, Clone, PartialEq, thiserror::Error)]
47pub enum EditError {
48 #[error("invalid field name '{0}': must match [a-z_][a-z0-9_]*")]
49 InvalidFieldName(String),
50
51 #[error("invalid card kind '{0}': must match [a-z_][a-z0-9_]*")]
52 InvalidKindName(String),
53
54 #[error("card kind 'main' is reserved for the document root")]
55 ReservedKind,
56
57 #[error("index {index} is out of range (len = {len})")]
58 IndexOutOfRange { index: usize, len: usize },
59}
60
61impl Document {
62 pub fn set_quill_ref(&mut self, reference: QuillReference) {
63 self.main_mut().payload_mut().set_quill(reference);
64 }
65
66 pub fn card_mut(&mut self, index: usize) -> Option<&mut Card> {
67 self.cards_mut().get_mut(index)
68 }
69
70 pub fn push_card(&mut self, card: Card) {
71 self.cards_vec_mut().push(card);
72 }
73
74 /// Insert a composable card at `index` (`index > len` → [`EditError::IndexOutOfRange`]).
75 pub fn insert_card(&mut self, index: usize, card: Card) -> Result<(), EditError> {
76 let len = self.cards().len();
77 if index > len {
78 return Err(EditError::IndexOutOfRange { index, len });
79 }
80 self.cards_vec_mut().insert(index, card);
81 Ok(())
82 }
83
84 pub fn remove_card(&mut self, index: usize) -> Option<Card> {
85 if index >= self.cards().len() {
86 return None;
87 }
88 Some(self.cards_vec_mut().remove(index))
89 }
90
91 /// Replace the `$kind` of the composable card at `index`.
92 ///
93 /// Only the `$kind` metadata changes; the payload and body are untouched
94 /// (field-bag semantics). Old-schema fields linger in the bag; new-schema
95 /// fields are absent until set explicitly. Schema migration is the caller's
96 /// responsibility — this is a structural primitive.
97 ///
98 /// Returns [`EditError::IndexOutOfRange`], [`EditError::InvalidKindName`],
99 /// or [`EditError::ReservedKind`] on constraint violations.
100 pub fn set_card_kind(
101 &mut self,
102 index: usize,
103 new_kind: impl Into<String>,
104 ) -> Result<(), EditError> {
105 let new_kind = new_kind.into();
106 validate_composable_kind(&new_kind).map_err(|e| match e {
107 CardKindError::InvalidName => EditError::InvalidKindName(new_kind.clone()),
108 CardKindError::Reserved => EditError::ReservedKind,
109 })?;
110 let len = self.cards().len();
111 let card = self
112 .card_mut(index)
113 .ok_or(EditError::IndexOutOfRange { index, len })?;
114 card.payload_mut().set_kind(new_kind);
115 Ok(())
116 }
117
118 /// Move card at `from` to position `to`. No-op when `from == to`.
119 /// Either index out of range → [`EditError::IndexOutOfRange`].
120 pub fn move_card(&mut self, from: usize, to: usize) -> Result<(), EditError> {
121 let len = self.cards().len();
122 if from >= len {
123 return Err(EditError::IndexOutOfRange { index: from, len });
124 }
125 if to >= len {
126 return Err(EditError::IndexOutOfRange { index: to, len });
127 }
128 if from == to {
129 return Ok(());
130 }
131 let card = self.cards_vec_mut().remove(from);
132 self.cards_vec_mut().insert(to, card);
133 Ok(())
134 }
135}
136
137impl Card {
138 /// Create a composable card with the given kind, no fields, and an empty body.
139 pub fn new(kind: impl Into<String>) -> Result<Self, EditError> {
140 let kind = kind.into();
141 validate_composable_kind(&kind).map_err(|e| match e {
142 CardKindError::InvalidName => EditError::InvalidKindName(kind.clone()),
143 CardKindError::Reserved => EditError::ReservedKind,
144 })?;
145 let mut payload = Payload::new();
146 payload.set_kind(kind);
147 Ok(Card::from_parts(payload, String::new()))
148 }
149
150 /// Set a payload field, clearing any `!fill` marker on that key.
151 ///
152 /// Returns [`EditError::InvalidFieldName`] when `name` does not match
153 /// `[a-z_][a-z0-9_]*`.
154 pub fn set_field(&mut self, name: &str, value: QuillValue) -> Result<(), EditError> {
155 if !is_valid_field_name(name) {
156 return Err(EditError::InvalidFieldName(name.to_string()));
157 }
158 self.payload_mut().insert(name.to_string(), value);
159 Ok(())
160 }
161
162 /// Set a payload field and mark it as a `!fill` placeholder.
163 /// `Null` emits as `key: !fill`; scalars/sequences as `key: !fill <value>`.
164 /// Same validation as [`Card::set_field`].
165 pub fn set_fill(&mut self, name: &str, value: QuillValue) -> Result<(), EditError> {
166 if !is_valid_field_name(name) {
167 return Err(EditError::InvalidFieldName(name.to_string()));
168 }
169 self.payload_mut().insert_fill(name.to_string(), value);
170 Ok(())
171 }
172
173 /// Remove a payload field; returns `Ok(None)` if the name is absent.
174 /// Same validation as [`Card::set_field`].
175 pub fn remove_field(&mut self, name: &str) -> Result<Option<QuillValue>, EditError> {
176 if !is_valid_field_name(name) {
177 return Err(EditError::InvalidFieldName(name.to_string()));
178 }
179 Ok(self.payload_mut().remove(name))
180 }
181
182 /// Replace the card's opaque `$ext` map wholesale, inserting it at the
183 /// canonical position (after `$quill`/`$kind`/`$id`, before user fields)
184 /// when none existed. Passing an empty map records an explicit `$ext: {}`.
185 ///
186 /// `$ext` carries out-of-band consumer state (editor renames, agent
187 /// annotations, …) and is stripped from [`Document::to_plate_json`], so a
188 /// write here can never affect a render. Any nested comments attached to a
189 /// replaced `$ext` are dropped.
190 pub fn set_ext(&mut self, value: serde_json::Map<String, serde_json::Value>) {
191 self.payload_mut().set_ext(value);
192 }
193
194 /// Remove the card's `$ext` map *entirely*, returning the previous map if
195 /// present. This is a blunt escape hatch — it discards every namespace
196 /// (`$ext.presentation`, `$ext.agent`, …) at once. To clear consumer
197 /// state, prefer [`Card::remove_ext_namespace`], which drops only your
198 /// own slot and leaves sibling consumers' state intact.
199 pub fn remove_ext(&mut self) -> Option<serde_json::Map<String, serde_json::Value>> {
200 self.payload_mut().take_ext()
201 }
202
203 /// Merge `value` into the card's `$ext` map under `namespace`, creating
204 /// the map when absent and replacing any existing value at that key.
205 ///
206 /// This is the recommended way to write `$ext`: it preserves sibling
207 /// namespaces, so independent consumers keying on their own slot
208 /// (`$ext.presentation`, `$ext.agent`, …) don't clobber each other.
209 pub fn set_ext_namespace(&mut self, namespace: impl Into<String>, value: serde_json::Value) {
210 let mut map = self.payload_mut().take_ext().unwrap_or_default();
211 map.insert(namespace.into(), value);
212 self.payload_mut().set_ext(map);
213 }
214
215 /// Remove `namespace` from the card's `$ext` map, returning the value
216 /// that was stored there (or `None` when the map or the key was absent).
217 ///
218 /// This is the recommended way to clear `$ext` state: it is the
219 /// namespace-scoped inverse of [`Card::set_ext_namespace`] and preserves
220 /// sibling namespaces, where [`Card::remove_ext`] would wipe them all.
221 /// When removing the last namespace empties the map, the `$ext` entry is
222 /// dropped entirely (not left as `$ext: {}`), so
223 /// `set_ext_namespace(ns, v)` followed by `remove_ext_namespace(ns)`
224 /// restores a card that had no `$ext` to its original state.
225 pub fn remove_ext_namespace(&mut self, namespace: &str) -> Option<serde_json::Value> {
226 let mut map = self.payload_mut().take_ext()?;
227 let removed = map.remove(namespace);
228 if !map.is_empty() {
229 self.payload_mut().set_ext(map);
230 }
231 removed
232 }
233
234 pub fn replace_body(&mut self, body: impl Into<String>) {
235 self.overwrite_body(body.into());
236 }
237}