quillmark_core/region.rs
1//! Schema-field geometry, queried from a compiled
2//! [`LiveSession`](crate::LiveSession) via
3//! [`regions`](crate::LiveSession::regions) and
4//! [`field_at`](crate::LiveSession::field_at).
5//!
6//! A region ties a rectangle on the rendered page to the **quill schema field**
7//! that produced it — the address the document author already uses to refer to
8//! that field (the same address the Typst plate reads as `data.*` and the
9//! pdfform binder resolves against `compile_data`). The two directions a
10//! consumer navigates get two queries: `regions` answers *field → rectangle*
11//! (scroll to / highlight the focused field), `field_at` answers *point →
12//! field* (click a rendered field → focus it in the editor).
13//!
14//! Three producers feed regions, all keyed on the schema path:
15//!
16//! - **Content fields** (a richtext body, a `richtext[]` element, a card's
17//! content field) are tracked by the **spans** their glyphs carry: the
18//! backend evaluates each one's value at its own generated call site and
19//! records the site's byte window, so every glyph of that content resolves
20//! back to its field — through *any* placement context, including a package
21//! that rebuilds the content (a `show`-rule pass that captures paragraphs
22//! into a state buffer and re-emits them), because the origin rides the
23//! glyph, not a sibling marker a rebuild could drop. A field that is blank
24//! or draws nothing (an empty or whitespace-only body) has no inked extent
25//! to bound and surfaces no region — present-but-empty is not the same as
26//! placed.
27//! - **Direct scalar references** — every `data.<field>` / `data.at("field")`
28//! expression in the plate is its own tracked site: the interpolated
29//! value's glyphs carry a span at or around that reference expression. A
30//! scalar shown in both a header and a footer surfaces both sites, because
31//! two source expressions are two origins; a reference wrapped in an
32//! expression (`#upper(data.subject)`) attributes the whole expression's
33//! ink to the field as long as it is the expression's only reference. Not
34//! tracked: an expression mixing several fields (`data.from + ", " + rank`
35//! has no single owner), a value laundered through an intermediate binding
36//! (`#let s = data.x` … `#s`), and card scalars read from the per-card
37//! loop variable (`card.from` is *one* expression site shared by every card
38//! instance — span data holds no per-instance identity; bind a widget for
39//! those).
40//! - **Form-field widgets** carry a schema path explicitly: pdfform binds it
41//! from the form mapping; a Typst `form-field` binds it from its `field:`
42//! argument. A widget that binds none produces **no** region — its backend
43//! identifier (the `/T` widget name) is not a schema address, so there is
44//! nothing for a consumer to route to. Only schema-addressable fields surface
45//! a region.
46//!
47//! **First placement only.** A content value placed at two sites surfaces one
48//! region set — its first placement's — because span data cannot distinguish
49//! "package chrome interrupting one placement" from "a second placement of
50//! the same value", and a spanning union would claim the ink between them.
51//! The first placement is one region per page it touches, in page order, so
52//! highlighting covers continuation pages — page marginals (headers, footers,
53//! page numbers) between one page's body and the next's do not end it, only a
54//! same-page interruption does: foreign ink within a page (a rebuild's
55//! numbering chrome) shrinks the region to the placement's true start rather
56//! than lying about extent. `field` is still not unique in the
57//! result: page fragments, several scalar reference sites, or tracked content
58//! plus a bound widget each surface independently.
59//! [`LiveSession::regions`](crate::LiveSession::regions) passes the backend's
60//! entries through; consumers group by `field`. Later placements stay
61//! reachable point-wise: [`field_at`](crate::LiveSession::field_at) resolves
62//! a click on *any* placement, since one concrete point identifies one drawn
63//! item whose origin is unambiguous.
64//!
65//! Regions are primarily a session-level query: the geometry is a property of
66//! the current compile, re-read from the session per edit without producing
67//! any byte artifact — the interactive-preview path (overlays over a
68//! `paint`-ed canvas) reads it that way. A one-shot byte render carries the
69//! same sidecar only on request ([`RenderOptions::regions`](crate::RenderOptions))
70//! for consumers without a live session (static SVG overlays, PDF
71//! post-processing, CI coverage probes). Either way regions are an overlay
72//! sidecar, never a compositing input: every canvas backend hands back a
73//! complete page raster, so nothing about the picture depends on reading a
74//! region. Empty for backends that place no schema fields.
75
76/// One schema field placement's extent on a rendered page.
77///
78/// `rect` is `[x0, y0, x1, y1]` in PDF points with a **bottom-left** origin —
79/// the same final geometry the stamp spine writes to the widget `/Rect`, so the
80/// region and the rendered field describe the identical box.
81///
82/// `field` is **not** unique within the `Vec` that
83/// [`LiveSession::regions`](crate::LiveSession::regions) returns: a content
84/// field breaks into one entry **per segment** (paragraph, heading, whole code
85/// fence) and per page each segment touches, a scalar referenced at several
86/// plate sites yields one per site, and tracked content plus a bound widget
87/// yields both. Consumers group by `field`; every entry routes to that field.
88/// The whole-field box is **derived** — the union of a page's `span`-bearing
89/// segment rects, so inter-paragraph whitespace stays uncovered (#829); the
90/// [`field_boxes`] helper (and
91/// [`LiveSession::field_boxes`](crate::LiveSession::field_boxes)) owns that
92/// union so consumers need not reimplement it.
93#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
94#[serde(rename_all = "camelCase")]
95pub struct RenderedRegion {
96 /// The field's plate-space schema address as the backend keys it —
97 /// `"signature_block"` or `"$cards.<kind>.<ordinal>.<field>"` (a per-kind
98 /// ordinal). This is the backend-native form; a binding that owns the
99 /// document's card kinds translates it to a canonical
100 /// [`DocPath`] at its boundary
101 /// ([`plate_addr_to_doc_path`]), so its consumers see one absolute-index
102 /// grammar. A core consumer reading `RenderedRegion` directly sees the
103 /// plate-space form.
104 pub field: String,
105 /// 0-based page index.
106 pub page: usize,
107 /// `[x0, y0, x1, y1]`, PDF points, bottom-left origin.
108 pub rect: [f32; 4],
109 /// The content slice this box covers: USV `[start, end)` into the field's
110 /// `Content` for content ink (one segment's range), `None` for a scalar
111 /// reference site or a widget — geometry with no content address. Additive
112 /// and optional: omitted from the wire when `None`.
113 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub span: Option<[usize; 2]>,
115}
116
117impl RenderedRegion {
118 /// Whether the point (`x`, `y`, PDF points, bottom-left origin) on `page`
119 /// falls inside this region, edges inclusive. The one point-in-region
120 /// predicate every `field_at` hit-test shares, so a click at a region
121 /// border resolves identically everywhere.
122 pub fn contains(&self, page: usize, x: f32, y: f32) -> bool {
123 self.page == page
124 && self.rect[0] <= x
125 && x <= self.rect[2]
126 && self.rect[1] <= y
127 && y <= self.rect[3]
128 }
129}
130
131/// The whole-field highlight boxes for `field`, derived from a region set: one
132/// union rect per page, over that field's **`span`-bearing** (content) regions.
133///
134/// This owns the subtle part [`regions`](crate::LiveSession::regions) leaves to
135/// consumers — filter by field, keep only the segment rects that carry a `span`,
136/// union per page, inherit first-placement-only from the input — so a
137/// "highlight the focused field" consumer never reimplements it and cannot
138/// reintroduce the field-level union the #829 disjointness invariant exists to
139/// prevent (the input is already striped; this unions the *bounding* box per
140/// page, so inter-paragraph whitespace still is not a separate box but the
141/// derived rect does bound it). Pass the output of
142/// [`LiveSession::regions`](crate::LiveSession::regions) (or a one-shot
143/// [`RenderOptions::regions`](crate::RenderOptions) sidecar); the convenience
144/// [`LiveSession::field_boxes`](crate::LiveSession::field_boxes) reads the
145/// session's own.
146///
147/// **Content only.** A scalar-reference site or a widget carries no `span`
148/// ([`RenderedRegion::span`] is `None`), so a field placed *only* as a scalar
149/// reference or a bound widget yields an empty result here — its highlight box
150/// is a single region's `rect`, read straight from the region set with no
151/// derivation. Each returned region carries the union `span`
152/// (`[min start, max end)` over the page's contributing segments);
153/// `page`-ascending.
154pub fn field_boxes(regions: &[RenderedRegion], field: &str) -> Vec<RenderedRegion> {
155 let mut by_page: Vec<RenderedRegion> = Vec::new();
156 for r in regions
157 .iter()
158 .filter(|r| r.field == field && r.span.is_some())
159 {
160 let span = r.span.expect("filtered to span-bearing");
161 match by_page.iter_mut().find(|acc| acc.page == r.page) {
162 Some(acc) => {
163 acc.rect[0] = acc.rect[0].min(r.rect[0]);
164 acc.rect[1] = acc.rect[1].min(r.rect[1]);
165 acc.rect[2] = acc.rect[2].max(r.rect[2]);
166 acc.rect[3] = acc.rect[3].max(r.rect[3]);
167 let s = acc.span.expect("union region carries a span");
168 acc.span = Some([s[0].min(span[0]), s[1].max(span[1])]);
169 }
170 None => by_page.push(RenderedRegion {
171 field: r.field.clone(),
172 page: r.page,
173 rect: r.rect,
174 span: Some(span),
175 }),
176 }
177 }
178 by_page.sort_by_key(|r| r.page);
179 by_page
180}
181
182// ── Address translation: plate-space geometry ⇄ DocPath ─────────────────────
183//
184// A backend keys a region on the **plate-space** address its compiled plate
185// composes (`$path` = `$cards.<kind>.<ordinal>.`, `crates/backends/typst`), a
186// grammar with a `$cards` sigil, dot separators, and **per-kind ordinals**.
187// That grammar is the template-author contract inside the plate and stays
188// there; it must not cross to a consumer, which speaks one canonical
189// [`DocPath`]. The session owns the translation, resolving the per-kind ordinal
190// to the document-array absolute index (and back) against the ordered card
191// kinds of the current compile — so `regions` / `fieldAt` / `positionAt` /
192// `locate` speak `DocPath`, never `$cards.` ordinals.
193
194use crate::path::{DocPath, DocSeg};
195
196/// The absolute document-array index of the `ord`-th (0-based) card of `kind`,
197/// scanning `card_kinds` (the current compile's ordered card kinds; `None` is a
198/// kindless card) in order. `None` when fewer than `ord + 1` cards of that kind
199/// exist.
200fn abs_card_index(card_kinds: &[Option<&str>], kind: &str, ord: usize) -> Option<usize> {
201 card_kinds
202 .iter()
203 .enumerate()
204 .filter(|(_, k)| **k == Some(kind))
205 .nth(ord)
206 .map(|(i, _)| i)
207}
208
209/// The per-kind ordinal of the card at absolute index `abs` — how many cards of
210/// the same kind precede it, matching the plate's `emit_cards` counter. `None`
211/// when `abs` is out of range or the card is kindless.
212fn per_kind_ordinal(card_kinds: &[Option<&str>], abs: usize) -> Option<usize> {
213 let kind = (*card_kinds.get(abs)?)?;
214 Some(
215 card_kinds[..abs]
216 .iter()
217 .filter(|k| **k == Some(kind))
218 .count(),
219 )
220}
221
222/// Translate a backend plate-space geometry address into a canonical
223/// [`DocPath`], resolving the per-kind ordinal to the absolute card index via
224/// `card_kinds`. The grammar handled is exactly what geometry emits: `$body`
225/// (main body), a bare `<field>` (main field), `$cards.<kind>.<ord>.<field>`
226/// (card field), and `$cards.<kind>.<ord>.$body` (card body). `None` for an
227/// address outside that grammar or one naming a card the kind list cannot
228/// place — the caller keeps the original string.
229/// Rewrite each region's plate-space `field` to its [`DocPath`] string — the
230/// translation [`RenderedRegion`] puts at a binding boundary. One funnel for
231/// every region a binding hands out, render sidecar and session query alike, so
232/// a consumer never sees the two address spaces mixed. An address outside the
233/// geometry grammar keeps its original string.
234pub fn regions_to_doc_path(
235 mut regions: Vec<RenderedRegion>,
236 card_kinds: &[Option<&str>],
237) -> Vec<RenderedRegion> {
238 for region in &mut regions {
239 if let Some(path) = plate_addr_to_doc_path(®ion.field, card_kinds) {
240 region.field = path.to_string();
241 }
242 }
243 regions
244}
245
246pub fn plate_addr_to_doc_path(addr: &str, card_kinds: &[Option<&str>]) -> Option<DocPath> {
247 if addr == "$body" {
248 return Some(DocPath::main_body());
249 }
250 if let Some(rest) = addr.strip_prefix("$cards.") {
251 let mut it = rest.splitn(3, '.');
252 let kind = it.next()?;
253 let ord: usize = it.next()?.parse().ok()?;
254 let tail = it.next()?;
255 let abs = abs_card_index(card_kinds, kind, ord)?;
256 let card = DocPath::card(Some(kind), abs);
257 return Some(if tail == "$body" {
258 card.body()
259 } else {
260 card.field(tail)
261 });
262 }
263 // A plate-space bare main field (`subject`) roots at `main` in `DocPath`
264 // space (`main.subject`), so a consumer always receives a parsed, rooted
265 // path. An unrecognized `$`-token (never a main field) does not translate.
266 if addr.starts_with('$') {
267 return None;
268 }
269 Some(DocPath::main().field(addr))
270}
271
272/// Translate a canonical [`DocPath`] geometry address back to the backend
273/// plate-space form (`main.body` → `$body`, `cards.<kind>[<abs>].<field>` →
274/// `$cards.<kind>.<ord>.<field>`), resolving the absolute card index to its
275/// per-kind ordinal via `card_kinds`. `None` when the path is not a geometry
276/// address (a document-model shape geometry never keys) or names a card the
277/// kind list cannot place. The inverse of [`plate_addr_to_doc_path`], for the
278/// `field`-taking queries (`locate`, `fieldBoxes`).
279pub fn doc_path_to_plate_addr(path: &DocPath, card_kinds: &[Option<&str>]) -> Option<String> {
280 match path.segs() {
281 [DocSeg::Main, DocSeg::Body] => Some("$body".to_string()),
282 [DocSeg::Main, DocSeg::Field { name }] => Some(name.clone()),
283 [DocSeg::Card {
284 kind: Some(kind),
285 index,
286 }, rest @ ..] => {
287 // The path must actually name the card that sits at `index`.
288 if card_kinds.get(*index).copied().flatten() != Some(kind.as_str()) {
289 return None;
290 }
291 let ord = per_kind_ordinal(card_kinds, *index)?;
292 match rest {
293 [DocSeg::Field { name }] => Some(format!("$cards.{kind}.{ord}.{name}")),
294 [DocSeg::Body] => Some(format!("$cards.{kind}.{ord}.$body")),
295 _ => None,
296 }
297 }
298 _ => None,
299 }
300}
301
302/// How precisely a [`ContentHit::pos`] resolved — the marker a caret UI reads to
303/// decide whether to trust the offset. The value is never sub-cluster; the two
304/// variants distinguish the finest this API offers from the segment floor it
305/// degrades to.
306#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
307#[serde(rename_all = "camelCase")]
308pub enum HitGranularity {
309 /// Cluster-exact: `pos` is the first content char of the grapheme cluster
310 /// under the point. The finest resolution — a char that escaped to several
311 /// generated bytes (`*`→`\*`, `你`→3, the `//`→`\/\/` coupling) still floors
312 /// to its cluster's first char, so this is *not* sub-character. A caret UI
313 /// can place the caret at `pos` directly.
314 Cluster,
315 /// Segment-floored: the point landed on origin-less ink (list markers,
316 /// numbering, a multi-line code fence's interior — spans that resolve to no
317 /// single run), so `pos` degraded to the containing segment's content start
318 /// rather than a wrong finer position. A caret UI should treat `pos` as the
319 /// segment it selected, not a within-segment caret.
320 Segment,
321}
322
323/// A resolved point → content position: the schema field a click landed in and
324/// the USV offset into that field's `Content`. The forward
325/// [`position_at`](crate::LiveSession::position_at) direction, paired with
326/// [`locate`](crate::LiveSession::locate) (content position → caret rect).
327///
328/// `pos` is **cluster-exact, not sub-character**: a hit inside a char that
329/// escaped to several generated bytes (`*`→`\*`, `你`→3, the `//`→`\/\/`
330/// coupling) floors to that cluster's first content char. A click on
331/// origin-less ink (list markers, numbering, a multi-line code fence's interior
332/// — spans that resolve to no single run) degrades to the containing segment's
333/// content start rather than a wrong finer position, and a click off all content
334/// ink resolves to nothing. [`granularity`](Self::granularity) reports which of
335/// those two happened, so a caret UI need not guess.
336#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
337#[serde(rename_all = "camelCase")]
338pub struct ContentHit {
339 /// The content field's schema path (same address space as
340 /// [`RenderedRegion::field`]).
341 pub field: String,
342 /// USV offset into the field's `Content`.
343 pub pos: usize,
344 /// Whether [`pos`](Self::pos) is cluster-exact or floored to the segment
345 /// start ([`HitGranularity`]). `None` when the backend does not report it (a
346 /// hit straight from a backend with no source map, or an older wire payload).
347 /// Additive-optional: omitted from the wire when `None`.
348 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub granularity: Option<HitGranularity>,
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 #[test]
357 fn region_round_trips_through_json() {
358 let region = RenderedRegion {
359 field: "full_name".to_string(),
360 page: 0,
361 rect: [180.0, 715.0, 520.0, 735.0],
362 span: Some([12, 34]),
363 };
364 let json = serde_json::to_string(®ion).unwrap();
365 assert!(json.contains("\"field\":\"full_name\""), "{json}");
366 assert!(json.contains("\"span\":[12,34]"), "{json}");
367 let back: RenderedRegion = serde_json::from_str(&json).unwrap();
368 assert_eq!(back, region);
369 }
370
371 /// `span` is omitted when `None` and defaults back on read — the
372 /// additive-optional discipline that lets a scalar/widget region (no content
373 /// address) parse the same as a content region carrying a span.
374 #[test]
375 fn optional_span_omitted_when_none() {
376 let region = RenderedRegion {
377 field: "subject".to_string(),
378 page: 0,
379 rect: [1.0, 2.0, 3.0, 4.0],
380 span: None,
381 };
382 let json = serde_json::to_string(®ion).unwrap();
383 assert!(!json.contains("span"), "scalar region omits span: {json}");
384 let back: RenderedRegion = serde_json::from_str(&json).unwrap();
385 assert_eq!(back, region);
386 }
387
388 #[test]
389 fn content_hit_round_trips_through_json() {
390 let hit = ContentHit {
391 field: "body".to_string(),
392 pos: 42,
393 granularity: Some(HitGranularity::Cluster),
394 };
395 let json = serde_json::to_string(&hit).unwrap();
396 assert!(json.contains("\"field\":\"body\"") && json.contains("\"pos\":42"));
397 assert!(json.contains("\"granularity\":\"cluster\""), "{json}");
398 let back: ContentHit = serde_json::from_str(&json).unwrap();
399 assert_eq!(back, hit);
400
401 // The segment-floored variant serializes to its own tag, so a caret UI
402 // can tell a trusted cluster offset from a floored one.
403 let seg = ContentHit {
404 field: "body".to_string(),
405 pos: 7,
406 granularity: Some(HitGranularity::Segment),
407 };
408 let json = serde_json::to_string(&seg).unwrap();
409 assert!(json.contains("\"granularity\":\"segment\""), "{json}");
410 assert_eq!(serde_json::from_str::<ContentHit>(&json).unwrap(), seg);
411 }
412
413 /// `granularity` omits when `None` and defaults back on read — the
414 /// additive-optional discipline, so a hit straight from a backend (no source
415 /// map) parses the same as the earlier hit shape lacking it.
416 #[test]
417 fn content_hit_omits_optionals_when_none() {
418 let hit = ContentHit {
419 field: "body".to_string(),
420 pos: 42,
421 granularity: None,
422 };
423 let json = serde_json::to_string(&hit).unwrap();
424 assert!(
425 !json.contains("granularity"),
426 "unreported granularity omitted: {json}"
427 );
428 let back: ContentHit = serde_json::from_str(&json).unwrap();
429 assert_eq!(back, hit);
430 }
431
432 fn content(field: &str, page: usize, rect: [f32; 4], span: [usize; 2]) -> RenderedRegion {
433 RenderedRegion {
434 field: field.to_string(),
435 page,
436 rect,
437 span: Some(span),
438 }
439 }
440
441 /// `field_boxes` unions a page's span-bearing segment rects into one box and
442 /// ignores other fields — the whole-field highlight consumers used to derive
443 /// by hand. The union `span` bounds `[min start, max end)`, and each page
444 /// gets its own box, page-ascending.
445 #[test]
446 fn field_boxes_unions_span_bearing_segments_per_page() {
447 let regions = vec![
448 content("$body", 0, [10.0, 700.0, 200.0, 720.0], [0, 12]),
449 content("$body", 0, [10.0, 660.0, 260.0, 680.0], [13, 40]),
450 content("$body", 1, [10.0, 700.0, 150.0, 720.0], [41, 55]),
451 content("subject", 0, [10.0, 740.0, 90.0, 752.0], [0, 5]),
452 ];
453 let boxes = field_boxes(®ions, "$body");
454 assert_eq!(boxes.len(), 2, "one box per page $body touches");
455 assert_eq!(boxes[0].page, 0);
456 assert_eq!(boxes[0].rect, [10.0, 660.0, 260.0, 720.0], "page-0 union");
457 assert_eq!(boxes[0].span, Some([0, 40]), "page-0 union span");
458 assert_eq!(boxes[1].page, 1);
459 assert_eq!(boxes[1].rect, [10.0, 700.0, 150.0, 720.0]);
460 }
461
462 /// A field placed only as a scalar reference or widget (no `span`) yields no
463 /// derived content box — its highlight is a single region's `rect`, read
464 /// straight from the set.
465 #[test]
466 fn field_boxes_empty_for_span_less_field() {
467 let regions = vec![RenderedRegion {
468 field: "subject".to_string(),
469 page: 0,
470 rect: [10.0, 740.0, 90.0, 752.0],
471 span: None,
472 }];
473 assert!(field_boxes(®ions, "subject").is_empty());
474 }
475
476 // ── Plate-space ⇄ DocPath translation ────────────────────────────────────
477
478 /// Two `note` cards interleaved with one `annotation`: the per-kind ordinal
479 /// is not the absolute index once kinds interleave, so the two grammars
480 /// genuinely differ and the kind list is load-bearing.
481 const KINDS: &[Option<&str>] = &[Some("note"), Some("annotation"), Some("note")];
482
483 fn to_doc(addr: &str) -> Option<String> {
484 plate_addr_to_doc_path(addr, KINDS).map(|p| p.to_string())
485 }
486 fn to_plate(path: &str) -> Option<String> {
487 doc_path_to_plate_addr(&path.parse().unwrap(), KINDS)
488 }
489
490 #[test]
491 fn plate_to_docpath_resolves_the_absolute_index() {
492 // The 2nd `note` (ordinal 1) sits at absolute index 2.
493 assert_eq!(to_doc("$cards.note.1.on").as_deref(), Some("cards.note[2].on"));
494 // The 1st `note` (ordinal 0) is absolute 0; the `annotation` is absolute 1.
495 assert_eq!(to_doc("$cards.note.0.on").as_deref(), Some("cards.note[0].on"));
496 assert_eq!(
497 to_doc("$cards.annotation.0.text").as_deref(),
498 Some("cards.annotation[1].text")
499 );
500 // Bodies and main.
501 assert_eq!(to_doc("$body").as_deref(), Some("main.body"));
502 assert_eq!(
503 to_doc("$cards.note.1.$body").as_deref(),
504 Some("cards.note[2].body")
505 );
506 // A plate-space bare main field roots at `main` in DocPath space.
507 assert_eq!(to_doc("signature_block").as_deref(), Some("main.signature_block"));
508 }
509
510 #[test]
511 fn docpath_to_plate_is_the_inverse() {
512 for plate in [
513 "$body",
514 "signature_block",
515 "$cards.note.0.on",
516 "$cards.note.1.on",
517 "$cards.annotation.0.text",
518 "$cards.note.1.$body",
519 ] {
520 let doc = to_doc(plate).unwrap();
521 assert_eq!(to_plate(&doc).as_deref(), Some(plate), "round-trip {plate}");
522 }
523 }
524
525 #[test]
526 fn translation_rejects_unplaceable_and_foreign_shapes() {
527 // A 3rd `note` (ordinal 2) does not exist — only two notes.
528 assert_eq!(to_doc("$cards.note.2.on"), None);
529 // A DocPath whose kind disagrees with the slot does not translate back.
530 assert_eq!(
531 doc_path_to_plate_addr(&"cards.annotation[0].x".parse().unwrap(), KINDS),
532 None
533 );
534 // A document-model shape geometry never keys (nested main field).
535 assert_eq!(
536 doc_path_to_plate_addr(&"recipients[0].name".parse().unwrap(), KINDS),
537 None
538 );
539 }
540}