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 /// Quill schema field path, e.g. `"signature_block"` or
97 /// `"$cards.indorsement.1.from"` — the author-facing field address (the
98 /// card form is kind + 0-based ordinal, `$cards.<kind>.<n>.<field>`), not
99 /// any backend widget name.
100 pub field: String,
101 /// 0-based page index.
102 pub page: usize,
103 /// `[x0, y0, x1, y1]`, PDF points, bottom-left origin.
104 pub rect: [f32; 4],
105 /// The content slice this box covers: USV `[start, end)` into the field's
106 /// `Content` for content ink (one segment's range), `None` for a scalar
107 /// reference site or a widget — geometry with no content address. Additive
108 /// and optional: omitted from the wire when `None`.
109 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub span: Option<[usize; 2]>,
111}
112
113impl RenderedRegion {
114 /// Whether the point (`x`, `y`, PDF points, bottom-left origin) on `page`
115 /// falls inside this region, edges inclusive. The one point-in-region
116 /// predicate every `field_at` hit-test shares, so a click at a region
117 /// border resolves identically everywhere.
118 pub fn contains(&self, page: usize, x: f32, y: f32) -> bool {
119 self.page == page
120 && self.rect[0] <= x
121 && x <= self.rect[2]
122 && self.rect[1] <= y
123 && y <= self.rect[3]
124 }
125}
126
127/// The whole-field highlight boxes for `field`, derived from a region set: one
128/// union rect per page, over that field's **`span`-bearing** (content) regions.
129///
130/// This owns the subtle part [`regions`](crate::LiveSession::regions) leaves to
131/// consumers — filter by field, keep only the segment rects that carry a `span`,
132/// union per page, inherit first-placement-only from the input — so a
133/// "highlight the focused field" consumer never reimplements it and cannot
134/// reintroduce the field-level union the #829 disjointness invariant exists to
135/// prevent (the input is already striped; this unions the *bounding* box per
136/// page, so inter-paragraph whitespace still is not a separate box but the
137/// derived rect does bound it). Pass the output of
138/// [`LiveSession::regions`](crate::LiveSession::regions) (or a one-shot
139/// [`RenderOptions::regions`](crate::RenderOptions) sidecar); the convenience
140/// [`LiveSession::field_boxes`](crate::LiveSession::field_boxes) reads the
141/// session's own.
142///
143/// **Content only.** A scalar-reference site or a widget carries no `span`
144/// ([`RenderedRegion::span`] is `None`), so a field placed *only* as a scalar
145/// reference or a bound widget yields an empty result here — its highlight box
146/// is a single region's `rect`, read straight from the region set with no
147/// derivation. Each returned region carries the union `span`
148/// (`[min start, max end)` over the page's contributing segments);
149/// `page`-ascending.
150pub fn field_boxes(regions: &[RenderedRegion], field: &str) -> Vec<RenderedRegion> {
151 let mut by_page: Vec<RenderedRegion> = Vec::new();
152 for r in regions
153 .iter()
154 .filter(|r| r.field == field && r.span.is_some())
155 {
156 let span = r.span.expect("filtered to span-bearing");
157 match by_page.iter_mut().find(|acc| acc.page == r.page) {
158 Some(acc) => {
159 acc.rect[0] = acc.rect[0].min(r.rect[0]);
160 acc.rect[1] = acc.rect[1].min(r.rect[1]);
161 acc.rect[2] = acc.rect[2].max(r.rect[2]);
162 acc.rect[3] = acc.rect[3].max(r.rect[3]);
163 let s = acc.span.expect("union region carries a span");
164 acc.span = Some([s[0].min(span[0]), s[1].max(span[1])]);
165 }
166 None => by_page.push(RenderedRegion {
167 field: r.field.clone(),
168 page: r.page,
169 rect: r.rect,
170 span: Some(span),
171 }),
172 }
173 }
174 by_page.sort_by_key(|r| r.page);
175 by_page
176}
177
178/// How precisely a [`ContentHit::pos`] resolved — the marker a caret UI reads to
179/// decide whether to trust the offset. The value is never sub-cluster; the two
180/// variants distinguish the finest this API offers from the segment floor it
181/// degrades to.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
183#[serde(rename_all = "camelCase")]
184pub enum HitGranularity {
185 /// Cluster-exact: `pos` is the first content char of the grapheme cluster
186 /// under the point. The finest resolution — a char that escaped to several
187 /// generated bytes (`*`→`\*`, `你`→3, the `//`→`\/\/` coupling) still floors
188 /// to its cluster's first char, so this is *not* sub-character. A caret UI
189 /// can place the caret at `pos` directly.
190 Cluster,
191 /// Segment-floored: the point landed on origin-less ink (list markers,
192 /// numbering, a multi-line code fence's interior — spans that resolve to no
193 /// single run), so `pos` degraded to the containing segment's content start
194 /// rather than a wrong finer position. A caret UI should treat `pos` as the
195 /// segment it selected, not a within-segment caret.
196 Segment,
197}
198
199/// A resolved point → content position: the schema field a click landed in and
200/// the USV offset into that field's `Content`. The forward
201/// [`position_at`](crate::LiveSession::position_at) direction, paired with
202/// [`locate`](crate::LiveSession::locate) (content position → caret rect).
203///
204/// `pos` is **cluster-exact, not sub-character**: a hit inside a char that
205/// escaped to several generated bytes (`*`→`\*`, `你`→3, the `//`→`\/\/`
206/// coupling) floors to that cluster's first content char. A click on
207/// origin-less ink (list markers, numbering, a multi-line code fence's interior
208/// — spans that resolve to no single run) degrades to the containing segment's
209/// content start rather than a wrong finer position, and a click off all content
210/// ink resolves to nothing. [`granularity`](Self::granularity) reports which of
211/// those two happened, so a caret UI need not guess.
212#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
213#[serde(rename_all = "camelCase")]
214pub struct ContentHit {
215 /// The content field's schema path (same address space as
216 /// [`RenderedRegion::field`]).
217 pub field: String,
218 /// USV offset into the field's `Content`.
219 pub pos: usize,
220 /// Whether [`pos`](Self::pos) is cluster-exact or floored to the segment
221 /// start ([`HitGranularity`]). `None` when the backend does not report it (a
222 /// hit straight from a backend with no source map, or an older wire payload).
223 /// Additive-optional: omitted from the wire when `None`.
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub granularity: Option<HitGranularity>,
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231
232 #[test]
233 fn region_round_trips_through_json() {
234 let region = RenderedRegion {
235 field: "full_name".to_string(),
236 page: 0,
237 rect: [180.0, 715.0, 520.0, 735.0],
238 span: Some([12, 34]),
239 };
240 let json = serde_json::to_string(®ion).unwrap();
241 assert!(json.contains("\"field\":\"full_name\""), "{json}");
242 assert!(json.contains("\"span\":[12,34]"), "{json}");
243 let back: RenderedRegion = serde_json::from_str(&json).unwrap();
244 assert_eq!(back, region);
245 }
246
247 /// `span` is omitted when `None` and defaults back on read — the
248 /// additive-optional discipline that lets a scalar/widget region (no content
249 /// address) parse the same as a content region carrying a span.
250 #[test]
251 fn optional_span_omitted_when_none() {
252 let region = RenderedRegion {
253 field: "subject".to_string(),
254 page: 0,
255 rect: [1.0, 2.0, 3.0, 4.0],
256 span: None,
257 };
258 let json = serde_json::to_string(®ion).unwrap();
259 assert!(!json.contains("span"), "scalar region omits span: {json}");
260 let back: RenderedRegion = serde_json::from_str(&json).unwrap();
261 assert_eq!(back, region);
262 }
263
264 #[test]
265 fn content_hit_round_trips_through_json() {
266 let hit = ContentHit {
267 field: "body".to_string(),
268 pos: 42,
269 granularity: Some(HitGranularity::Cluster),
270 };
271 let json = serde_json::to_string(&hit).unwrap();
272 assert!(json.contains("\"field\":\"body\"") && json.contains("\"pos\":42"));
273 assert!(json.contains("\"granularity\":\"cluster\""), "{json}");
274 let back: ContentHit = serde_json::from_str(&json).unwrap();
275 assert_eq!(back, hit);
276
277 // The segment-floored variant serializes to its own tag, so a caret UI
278 // can tell a trusted cluster offset from a floored one.
279 let seg = ContentHit {
280 field: "body".to_string(),
281 pos: 7,
282 granularity: Some(HitGranularity::Segment),
283 };
284 let json = serde_json::to_string(&seg).unwrap();
285 assert!(json.contains("\"granularity\":\"segment\""), "{json}");
286 assert_eq!(serde_json::from_str::<ContentHit>(&json).unwrap(), seg);
287 }
288
289 /// `granularity` omits when `None` and defaults back on read — the
290 /// additive-optional discipline, so a hit straight from a backend (no source
291 /// map) parses the same as the earlier hit shape lacking it.
292 #[test]
293 fn content_hit_omits_optionals_when_none() {
294 let hit = ContentHit {
295 field: "body".to_string(),
296 pos: 42,
297 granularity: None,
298 };
299 let json = serde_json::to_string(&hit).unwrap();
300 assert!(
301 !json.contains("granularity"),
302 "unreported granularity omitted: {json}"
303 );
304 let back: ContentHit = serde_json::from_str(&json).unwrap();
305 assert_eq!(back, hit);
306 }
307
308 fn content(field: &str, page: usize, rect: [f32; 4], span: [usize; 2]) -> RenderedRegion {
309 RenderedRegion {
310 field: field.to_string(),
311 page,
312 rect,
313 span: Some(span),
314 }
315 }
316
317 /// `field_boxes` unions a page's span-bearing segment rects into one box and
318 /// ignores other fields — the whole-field highlight consumers used to derive
319 /// by hand. The union `span` bounds `[min start, max end)`, and each page
320 /// gets its own box, page-ascending.
321 #[test]
322 fn field_boxes_unions_span_bearing_segments_per_page() {
323 let regions = vec![
324 content("$body", 0, [10.0, 700.0, 200.0, 720.0], [0, 12]),
325 content("$body", 0, [10.0, 660.0, 260.0, 680.0], [13, 40]),
326 content("$body", 1, [10.0, 700.0, 150.0, 720.0], [41, 55]),
327 content("subject", 0, [10.0, 740.0, 90.0, 752.0], [0, 5]),
328 ];
329 let boxes = field_boxes(®ions, "$body");
330 assert_eq!(boxes.len(), 2, "one box per page $body touches");
331 assert_eq!(boxes[0].page, 0);
332 assert_eq!(boxes[0].rect, [10.0, 660.0, 260.0, 720.0], "page-0 union");
333 assert_eq!(boxes[0].span, Some([0, 40]), "page-0 union span");
334 assert_eq!(boxes[1].page, 1);
335 assert_eq!(boxes[1].rect, [10.0, 700.0, 150.0, 720.0]);
336 }
337
338 /// A field placed only as a scalar reference or widget (no `span`) yields no
339 /// derived content box — its highlight is a single region's `rect`, read
340 /// straight from the set.
341 #[test]
342 fn field_boxes_empty_for_span_less_field() {
343 let regions = vec![RenderedRegion {
344 field: "subject".to_string(),
345 page: 0,
346 rect: [10.0, 740.0, 90.0, 752.0],
347 span: None,
348 }];
349 assert!(field_boxes(®ions, "subject").is_empty());
350 }
351}