leaf_ffi/lib.rs
1//! leaf-ffi — the Swift / C-ABI frontend binding for leaf.
2//!
3//! This is the native-Apple analogue of `leaf-wasm`: it takes `leaf-core`'s
4//! frontend-neutral [`Doc`] — the byte-offset caret model and the AST→glyph
5//! [`VisualMap`] — and exposes it across a C ABI (via UniFFI) in the shape an
6//! AppKit/SwiftUI renderer wants. Core stays the single source of truth for the
7//! text, the caret math, and the offset⇄position mapping; the Swift side only
8//! paints glyphs and forwards key/mouse events back in, exactly as the TUI, gpui,
9//! and wasm frontends do.
10//!
11//! ## The boundary is style *runs*, not glyphs
12//!
13//! [`Doc::build_visual`] resolves the document to rows of per-character glyphs,
14//! each tagged with a semantic [`Role`] and the author's emphasis. Sending one
15//! object per character would make every keystroke O(document) in boundary
16//! crossings. Instead [`LeafDoc::view`] coalesces each row's glyphs into maximal
17//! **runs** of identical style and ships those — a handful of records per line.
18//! The Swift renderer maps each run's `role` to a font/size/weight and its
19//! emphasis flags to traits, the native counterpart of the TUI's `to_ratatui`
20//! and the web's CSS class.
21//!
22//! ## Core owns the grid; Swift owns the pixels
23//!
24//! Core lays a row out in whole character *columns* (a terminal-cell measure),
25//! and every offset⇄position method speaks that grid. It deliberately does *not*
26//! dictate presentation. So a native renderer is *proportional* — body text in a
27//! real family, headings by **size** and weight, code in a monospace panel — and
28//! never multiplies `col × cell_width`. It lets `NSLayoutManager` / Core Text
29//! shape each row, places the caret at [`DocView::caret_ch`] (a UTF-16 offset,
30//! which is exactly what `NSAttributedString` and `NSTextView` count in), and
31//! hit-tests a click through `characterIndex(for:)`, feeding the resulting
32//! row + UTF-16 offset back through [`LeafDoc::click_ch`]. Core measures nothing
33//! in pixels; Swift positions nothing in the model.
34//!
35//! ## Threading
36//!
37//! A UniFFI object is handed to Swift as a reference-counted handle whose methods
38//! take `&self`, so the [`Doc`] lives behind a [`Mutex`]. Every call locks, edits
39//! or reads, and returns a fresh [`DocView`] — one boundary crossing both mutates
40//! and repaints, same as the wasm frontend. Drive it from the main thread.
41
42use std::sync::{Arc, Mutex};
43
44use leaf_core::style::{Baseline, Role, Style as LStyle};
45use leaf_core::wysiwyg::text_width;
46use leaf_core::{
47 Alignment, BlockKind, Capabilities as CoreCapabilities, ColorScheme, Doc, Format, InlineKind,
48 LineFlow as CoreLineFlow, MarkColor as CoreMarkColor, MarkupMode as CoreMarkupMode,
49 MediaKind as CoreMediaKind, View, VisualMap,
50};
51use unicode_segmentation::UnicodeSegmentation;
52
53// Linked, not used: see the dependency's note in Cargo.toml. The `as _` is
54// what makes rustc treat the crate as referenced and carry its objects into
55// the staticlib.
56use resvg_uniffi as _;
57
58uniffi::setup_scaffolding!();
59
60/// A parse failure constructing a document — the only fallible entry point. Every
61/// other method is infallible (it operates on an already-parsed model), so they
62/// return a [`DocView`] directly.
63#[derive(Debug, thiserror::Error, uniffi::Error)]
64pub enum LeafError {
65 /// The `format` string handed to [`LeafDoc::new`] wasn't one leaf understands.
66 #[error("unknown format: {name}")]
67 UnknownFormat { name: String },
68 /// `leaf-core` failed to parse `source` as the requested format.
69 #[error("parse error: {message}")]
70 Parse { message: String },
71}
72
73/// A selection cited out of the source — the text, a little of what
74/// surrounded it, and the byte range it came from. The FFI shape of
75/// `leaf_core::Quote`; see [`LeafDoc::selection_quote`].
76#[derive(uniffi::Record)]
77pub struct SelectionQuote {
78 /// The selected source, verbatim.
79 pub exact: String,
80 /// What immediately preceded it — empty at the document's start.
81 pub prefix: String,
82 /// What immediately followed it — empty at the document's end.
83 pub suffix: String,
84 /// Byte offset in the source where the selection begins.
85 pub start: u64,
86 /// Byte offset where it ends (exclusive).
87 pub end: u64,
88}
89
90/// A host-painted range of the source — an annotation's footprint, a search
91/// hit. The FFI shape of `leaf_core::Highlight`; see
92/// [`LeafDoc::set_highlights`].
93#[derive(uniffi::Record)]
94pub struct Highlight {
95 /// Byte offset in the source where the wash begins.
96 pub start: u64,
97 /// Byte offset where it ends (exclusive).
98 pub end: u64,
99 /// The host's name for it, handed back on activation. Opaque to leaf.
100 pub id: String,
101 /// A rendering hint (`#RRGGBB`), or `None` for the theme's default wash.
102 pub color: Option<String>,
103 /// A margin glyph's name (an SF Symbol, for this binding's frontends), or
104 /// `None` for wash-only ink. The marker — not the wash — is what
105 /// activates a highlight; see `leaf_core::Highlight::marker`.
106 pub marker: Option<String>,
107}
108
109/// One maximal span of same-styled glyphs on a visual row — the unit the Swift
110/// renderer turns into a single styled attributed-string run.
111#[derive(uniffi::Record)]
112pub struct Run {
113 /// The run's text, glyphs concatenated in column order.
114 pub text: String,
115 /// The glyph's semantic role as a renderer class id: `body`, `h1`…`h6`,
116 /// `code`, `link`, `mark`, `list`, `quote`, `rule`.
117 pub role: String,
118 pub bold: bool,
119 pub italic: bool,
120 pub underline: bool,
121 pub strike: bool,
122 /// Raised off the baseline and drawn smaller — a footnote reference's `[1]`,
123 /// or an author's `^x^`. Mutually exclusive with [`sub`](Self::sub); core's
124 /// `Baseline` is one value, and these are its two non-default cases flattened
125 /// to the flag shape the rest of this record is spelled in.
126 pub sup: bool,
127 /// Lowered off the baseline and drawn smaller — an author's `~x~`.
128 pub sub: bool,
129 /// The byte offset in the source this run's first glyph came from.
130 ///
131 /// What a run *means*, as opposed to how it looks: a `link` role says a span
132 /// is drawn as a link but not where it points, and the only way back to that
133 /// is the source. A frontend drawing part of the document somewhere the caret
134 /// isn't — a footnote's text in a popover — pairs this with
135 /// [`LeafDoc::link_destination_at`] or [`LeafDoc::footnote_at`] to make those
136 /// runs followable.
137 ///
138 /// The alternative was for a frontend to count its way along the row's text
139 /// and ask [`LeafDoc::offset_for_pos`], which means converting between three
140 /// units that only agree on ASCII: this is a byte offset, the run's text is
141 /// characters, and a row's column is a *display* cell (a wide CJK glyph is
142 /// two). Handing the offset over is exact, O(1), and needs none of that.
143 ///
144 /// `0` for the runs of the source view, whose rows are split from raw text
145 /// rather than laid out from glyphs.
146 pub src: u32,
147 /// Whether this run lies inside the active selection — so the renderer can
148 /// paint a selection background without re-deriving it from offsets.
149 pub sel: bool,
150 /// The id of the host highlight covering this run, if one does — see
151 /// [`LeafDoc::set_highlights`]. A highlight splits a run the way the
152 /// selection does, so a wash begins and ends exactly on its bytes.
153 pub hl: Option<String>,
154 /// That highlight's rendering hint (`#RRGGBB`, or `None` for the theme's
155 /// default wash), carried beside the id so a renderer needs no lookup.
156 pub hl_color: Option<String>,
157 /// The colour the author named on a `mark` run — `"red"`, `"orange"`,
158 /// `"yellow"`, `"green"`, `"blue"`, `"purple"`, `"brown"` — or absent for a
159 /// plain `==highlight==` and for every other role.
160 ///
161 /// A *name*, unlike [`hl_color`](Self::hl_color)'s `#RRGGBB`, and that is
162 /// the difference between the two: a host highlight's colour is the host's
163 /// own choice and arrives as a value to paint, while this one is the
164 /// document's word for it and the renderer picks the wash. It rides beside
165 /// `role` rather than folding into it (`"mark-red"`) so a renderer that
166 /// knows nothing about colours still draws the run as the highlight it is.
167 pub mark_color: Option<String>,
168}
169
170/// Where a locator lands — what [`LeafDoc::locate`] answers with, and the FFI
171/// mirror of [`leaf_core::Landing`].
172///
173/// A span rather than an offset because the two things a host does with a
174/// locator want different halves of it: following one puts a caret at `start`,
175/// while peeking at one draws the rows between `start` and `end`. Only the first
176/// can be recovered from an offset alone.
177#[derive(uniffi::Record)]
178pub struct LandingView {
179 /// The first byte of the block the locator names — where a caret goes.
180 pub start: u32,
181 /// One past its last byte, so the pair maps through `pos_for_offset` to the
182 /// rendered rows the block occupies, the way [`FootnoteView`]'s pair does.
183 pub end: u32,
184}
185
186impl From<leaf_core::Landing> for LandingView {
187 fn from(l: leaf_core::Landing) -> Self {
188 LandingView {
189 start: l.start as u32,
190 end: l.end as u32,
191 }
192 }
193}
194
195/// A footnote reference and the note it names — what [`LeafDoc::footnote_at`]
196/// answers with. The FFI mirror of [`leaf_core::FootnoteRef`].
197///
198/// A reference whose definition the document is missing still comes back, with
199/// its `label` and no `text`: that a `[^99]` names nothing is a thing to tell
200/// the reader, and it is not the same as the caret standing on no reference at
201/// all (which is `None`).
202#[derive(uniffi::Record)]
203pub struct FootnoteView {
204 /// The reference's label — the `1` of `[^1]`, without the `^` or brackets.
205 pub label: String,
206 /// The note's body as source text, or `None` when nothing defines it.
207 pub text: Option<String>,
208 /// The byte offset the note's body starts at, for a "go to note" that moves
209 /// the caret there. `None` alongside a `None` `text`.
210 pub offset: Option<u32>,
211 /// Where the body ends, exclusive. With `offset` this bounds the note, so a
212 /// frontend can map the pair through `pos_for_offset` to the *rendered rows*
213 /// it occupies and draw those — the note with its markup resolved, rather
214 /// than the asterisks and backticks `text` carries. `None` alongside a
215 /// `None` `offset`.
216 pub end: Option<u32>,
217}
218
219impl From<leaf_core::FootnoteRef> for FootnoteView {
220 fn from(f: leaf_core::FootnoteRef) -> Self {
221 FootnoteView {
222 label: f.label,
223 text: f.text,
224 offset: f.offset.map(|o| o as u32),
225 end: f.end.map(|o| o as u32),
226 }
227 }
228}
229
230/// A footnote definition and the reference that sends a reader to it — what
231/// [`LeafDoc::footnote_definition_at_caret`] answers with, and the FFI mirror of
232/// [`leaf_core::FootnoteDef`].
233///
234/// The other half of [`FootnoteView`]'s round trip: that one carries a reader
235/// down to the note, this one carries them back up. A definition nothing cites
236/// still comes back, with its `label` and no `offset`, for the reason an
237/// undefined reference does — "nothing refers to this note" is worth saying.
238#[derive(uniffi::Record)]
239pub struct FootnoteDefView {
240 /// The definition's label — the `1` of `[^1]: …`, spelled exactly as
241 /// [`FootnoteView::label`] spells the same footnote's.
242 pub label: String,
243 /// The byte offset the first reference starts at, for a "back to reference"
244 /// that moves the caret there. `None` for a note nothing refers to.
245 pub offset: Option<u32>,
246}
247
248impl From<leaf_core::FootnoteDef> for FootnoteDefView {
249 fn from(f: leaf_core::FootnoteDef) -> Self {
250 FootnoteDefView {
251 label: f.label,
252 offset: f.offset.map(|o| o as u32),
253 }
254 }
255}
256
257/// One visual line: its styled runs plus the row-level flags a frontend draws
258/// chrome from.
259#[derive(uniffi::Record)]
260pub struct Row {
261 pub runs: Vec<Run>,
262 /// Drawn but holds no caret (a table rule, a block-gap blank line): the
263 /// renderer skips it for click/caret math. See [`leaf_core::VRow`].
264 pub decoration: bool,
265 /// A fenced/indented code-block line — the renderer draws a tinted, bordered
266 /// panel around each maximal run of these.
267 pub code: bool,
268 /// A fenced block's language, carried on the block's first code row only.
269 pub code_lang: Option<String>,
270 /// A `:::name{.class}` directive-container line — the renderer draws a
271 /// tinted panel around each maximal run of these, the `code` recipe. See
272 /// [`leaf_core::VRow::directive`].
273 pub directive: bool,
274 /// A directive container's space-joined `.class` attrs, carried on the
275 /// block's first row only. See [`leaf_core::VRow::directive_label`].
276 pub directive_label: Option<String>,
277 /// The heading level (1–6) if this row belongs to a heading block, else
278 /// `None`. A proportional renderer sizes the *whole* row from this so an
279 /// inline `` `code` `` run inside a heading still reads at the heading's size.
280 pub heading: Option<u8>,
281 /// What this row divides, on the blank rows a block boundary is drawn with
282 /// and `None` everywhere else — so `boundary != nil` is exactly "this row is
283 /// a drawn block boundary". A frontend spaces a boundary by the pair it
284 /// falls between (the margin above a heading is wider than the one between
285 /// two paragraphs); the *height* is the frontend's, the *kind* is core's.
286 /// See [`leaf_core::Boundary`].
287 pub boundary: Option<Boundary>,
288}
289
290/// What a drawn block boundary separates. The FFI mirror of
291/// [`leaf_core::Boundary`].
292#[derive(uniffi::Record)]
293pub struct Boundary {
294 pub above: BlockClass,
295 pub below: BlockClass,
296}
297
298/// The block kinds core tells apart — the vocabulary a [`Boundary`] is spelled
299/// in. The FFI mirror of [`leaf_core::BlockClass`]; `Other` covers every kind
300/// core doesn't separate out, so a frontend's `match` stays exhaustive as the
301/// list grows.
302#[derive(uniffi::Enum)]
303pub enum BlockClass {
304 Paragraph,
305 Heading,
306 /// A whole list. Core draws no boundary row *between* two items of one list,
307 /// tight or loose, so an `ListItem`↔`ListItem` pair never reaches a frontend.
308 List,
309 ListItem,
310 Quote,
311 Code,
312 Table,
313 Media,
314 Directive,
315 Rule,
316 Footnote,
317 Other,
318}
319
320impl From<leaf_core::BlockClass> for BlockClass {
321 fn from(k: leaf_core::BlockClass) -> Self {
322 use leaf_core::BlockClass as K;
323 match k {
324 K::Paragraph => BlockClass::Paragraph,
325 K::Heading => BlockClass::Heading,
326 K::List => BlockClass::List,
327 K::ListItem => BlockClass::ListItem,
328 K::Quote => BlockClass::Quote,
329 K::Code => BlockClass::Code,
330 K::Table => BlockClass::Table,
331 K::Media => BlockClass::Media,
332 K::Directive => BlockClass::Directive,
333 K::Rule => BlockClass::Rule,
334 K::Footnote => BlockClass::Footnote,
335 K::Other => BlockClass::Other,
336 }
337 }
338}
339
340/// One *visual line* of a table cell: its styled runs and the source offsets
341/// bounding it. A cell is usually one line, but an in-cell hard break (an inline
342/// `<br>`) splits it into several — each its own line here, so the frontend
343/// shapes and caret-maps them independently (the byte↔UTF-16 offset math a cell
344/// needs holds within a line, which carries no break). The runs are *unwrapped*:
345/// column width — and any soft wrap within it — is the frontend's to decide.
346#[derive(uniffi::Record)]
347pub struct TableCellLineView {
348 pub runs: Vec<Run>,
349 /// The source offsets bounding this line's content — the caret home at its
350 /// start and the stop just past its end.
351 pub start: u32,
352 pub end: u32,
353}
354
355/// One cell of a table's structural grid: its content as one or more visual
356/// lines, the column alignment its text honours, and the source range the whole
357/// cell occupies (where a click or the caret lands).
358#[derive(uniffi::Record)]
359pub struct TableCellView {
360 /// The cell's lines, in order — one unless an in-cell `<br>` splits it.
361 pub lines: Vec<TableCellLineView>,
362 /// `"left"`, `"right"`, `"center"`, or `"default"`.
363 pub align: String,
364 /// The source offsets bounding the cell's content — the caret anchors a
365 /// click in the cell resolves to.
366 pub start: u32,
367 pub end: u32,
368}
369
370/// One row of a table's structural grid; a header row draws bold and is ruled
371/// off from the body below it.
372#[derive(uniffi::Record)]
373pub struct TableRowView {
374 pub head: bool,
375 pub cells: Vec<TableCellView>,
376}
377
378/// A table described *structurally* rather than as the monospace box-glyph
379/// picture that spells it in [`DocView::rows`]. A proportional renderer draws its
380/// own grid from this — columns sized to content, real borders — and SKIPS the
381/// picture rows in `[start_row, end_row)`. The two describe the same cells at the
382/// same source offsets, so the caret lands identically either way. See
383/// [`leaf_core::TableInfo`].
384#[derive(uniffi::Record)]
385pub struct TableView {
386 /// The [`DocView::rows`] indices the box-drawn picture occupies — the rows a
387 /// grid-drawing frontend skips.
388 pub start_row: u32,
389 pub end_row: u32,
390 pub grid: Vec<TableRowView>,
391}
392
393/// A leaf directive (`::name{…}`) — a standalone block with no body, drawn in
394/// [`DocView::rows`] as a one-row `⧉ name` placeholder. A frontend that knows
395/// the host app's vocabulary reads this and paints the real thing over the rows
396/// in `[start_row, end_row)` — a web view for diaryx's `::embed{src=…}`, say —
397/// exactly as a grid-drawing one replaces a [`TableView`]'s picture rows. One
398/// that doesn't just paints the placeholder, which is already framed by the
399/// directive panel chrome.
400///
401/// Core resolves nothing here and neither does this layer: the vocabulary
402/// belongs to the app. See [`leaf_core::DirectiveInfo`].
403#[derive(uniffi::Record)]
404pub struct DirectiveView {
405 /// The [`DocView::rows`] indices the placeholder occupies.
406 pub start_row: u32,
407 pub end_row: u32,
408 /// The directive's type (`embed`, `toc`, `vis`), no leading colons.
409 pub name: String,
410 /// Its `[label]` text, or empty — what the placeholder row shows.
411 pub label: String,
412 /// Its `{…}` attributes in source order. A bare attribute (`{public}`) has an
413 /// empty value, which a consumer reads as a flag.
414 pub attrs: Vec<DirectiveAttr>,
415}
416
417/// One `{key=value}` attribute of a [`DirectiveView`]. A record rather than a
418/// tuple because UniFFI has no tuple type; an absent value flattens to `""`,
419/// since a bare attribute is a flag and the distinction from `key=""` has no
420/// consumer on this side.
421#[derive(uniffi::Record)]
422pub struct DirectiveAttr {
423 pub key: String,
424 pub value: String,
425}
426
427/// What a block-level media placeholder is, so Swift knows which view to build
428/// over the rows core reserved: an `NSImageView`/`UIImageView`, or an
429/// `AVPlayerView` with or without a picture to show. The peer of
430/// [`leaf_core::MediaKind`].
431#[derive(uniffi::Enum)]
432pub enum MediaKind {
433 Image,
434 Video,
435 Audio,
436}
437
438/// One `<source>` alternative of a block media element — a candidate URL plus
439/// whichever of the two things HTML picks a `<source>` by: a media query
440/// (`<picture>`) or a MIME type (`<video>`/`<audio>`).
441///
442/// Unlike the web frontend, which hands the whole list to the browser and lets
443/// it choose, a native renderer usually wants [`MediaView::src`] — already
444/// resolved for the current appearance — and reaches in here only to pick a
445/// codec `AVFoundation` can actually play.
446#[derive(uniffi::Record)]
447pub struct MediaSourceView {
448 /// The `media="…"` query, or empty for an unconditional source.
449 pub media: String,
450 /// The candidate URL (a `<picture>` `srcset` or a `<video>`/`<audio>` `src`).
451 pub src: String,
452 /// The `type="…"` MIME (`"video/webm"`), or empty when none is declared.
453 pub mime: String,
454}
455
456/// One block-level image, video, or audio: which rows core reserved for it and
457/// what to build there. The peer of [`leaf_core::MediaInfo`], and the media
458/// analogue of [`DirectiveView`] — a frontend **skips the rows in
459/// `start_row..end_row`** and lays its own view over them, rather than painting
460/// the `🖼`/`🎬`/`🔊` placeholder glyphs core put there for a surface that can't.
461#[derive(uniffi::Record)]
462pub struct MediaView {
463 /// The [`DocView::rows`] indices the placeholder occupies.
464 pub start_row: u32,
465 pub end_row: u32,
466 /// Which of the three this is — the view to build.
467 pub kind: MediaKind,
468 /// The URL to load, already resolved against the current appearance (see
469 /// [`LeafDoc::set_dark_appearance`]). A relative path resolves against the
470 /// document's own directory, which core does not know — the host does.
471 /// Empty only when a `<video>`/`<audio>` named neither a `src` nor a
472 /// `<source>`, which is a broken document.
473 pub src: String,
474 /// A `<video>`'s poster frame URL, or empty. An image destination, so it
475 /// loads exactly as an image `src` does — worth showing before the movie is
476 /// ready, or in place of one that won't play.
477 pub poster: String,
478 /// The alt / fallback text, for the view's accessibility label.
479 pub alt: String,
480 /// The `<source>` alternatives in document order; empty for a plain image.
481 pub sources: Vec<MediaSourceView>,
482}
483
484/// A per-destination measured height, the way Swift reports one back — the input
485/// half of the loop [`LeafDoc::set_media_rows`] closes.
486#[derive(uniffi::Record)]
487pub struct MediaHeight {
488 /// The media's `src` as it appeared in the document, keying it to a
489 /// [`MediaView`].
490 pub destination: String,
491 /// How many visual rows the laid-out view needs.
492 pub rows: u32,
493}
494
495/// A whole rendered frame: the rows to paint, where the caret sits, and the
496/// toolbar state — everything the Swift side needs for one repaint, in one value.
497/// Returned by every view-producing method.
498#[derive(uniffi::Record)]
499pub struct DocView {
500 pub rows: Vec<Row>,
501 /// Tables described structurally, for a frontend that draws its own grid
502 /// instead of painting the box-glyph rows. Empty in the source view. Each
503 /// names the `rows` span its picture occupies, to be skipped.
504 pub tables: Vec<TableView>,
505 /// Leaf directives (`::name{…}`) described structurally, for a frontend that
506 /// paints what the host app's vocabulary makes of them instead of the `⧉`
507 /// placeholder row. Empty in the source view, where the directive is the
508 /// literal text the caret is editing.
509 pub directives: Vec<DirectiveView>,
510 /// Block-level images, videos, and audio described structurally, for a
511 /// frontend that lays real views over the rows core reserved instead of
512 /// painting the placeholder glyphs. Empty in the source view, where the
513 /// `` or `<video>` markup is the literal text being edited.
514 pub media: Vec<MediaView>,
515 /// The caret's row: an index into [`Self::rows`].
516 pub caret_row: u32,
517 /// The caret's display *column* within its row — core's grid position. Kept
518 /// for callers reasoning in columns; a proportional renderer wants
519 /// [`Self::caret_ch`] instead.
520 pub caret_col: u32,
521 /// The caret's offset within its row's text in **UTF-16 code units** — what
522 /// `NSAttributedString`/`NSTextView` count to. This is `caret_col` mapped
523 /// through the row's grapheme widths, so it lands the caret correctly past
524 /// wide glyphs (CJK, emoji) where a column and a character index diverge.
525 pub caret_ch: u32,
526 /// The caret's **source byte offset** — the coordinate a table cell is keyed
527 /// by (`TableCellView::start`/`end`), so a frontend drawing its own grid can
528 /// find which cell the caret sits in without the picture-row indices.
529 pub caret_src: u32,
530 /// Whether a (non-empty) selection is active.
531 pub has_selection: bool,
532 /// The selection's *fixed* end (the caret is the moving end), as a row and a
533 /// UTF-16 offset — so the renderer can restore a native selection with the
534 /// same direction the model has. Equal to the caret when `has_selection` is
535 /// false.
536 pub anchor_row: u32,
537 pub anchor_ch: u32,
538 /// Whether the buffer differs from the last saved bytes — for a "● modified"
539 /// affordance.
540 pub dirty: bool,
541 /// Whether there is a step to undo, and one to redo — what a native Edit
542 /// menu or an undo manager enables its items by. Both false on a read-only
543 /// document. See [`leaf_core::Doc::can_undo`] for the bound this is.
544 pub can_undo: bool,
545 pub can_redo: bool,
546 /// `"wysiwyg"` or `"source"`, for a view-toggle affordance.
547 pub view: String,
548 /// The heading level at the caret, if any — a toolbar lights H1…H6 from it.
549 pub heading: Option<u32>,
550 /// The inline marks active at the caret (`bold`, `italic`, `code`, …) — the
551 /// toolbar lights the matching buttons.
552 pub active: Vec<String>,
553 /// The destination of the link the caret stands in, or `None` — the toolbar
554 /// lights its Link button from it and seeds an edit of that link with it.
555 ///
556 /// It rides the frame rather than being a query a toolbar makes for itself
557 /// because a toolbar only redraws when the *state* changes: walking the caret
558 /// out of a link changes no mark, no heading, and no dirty flag, so a Link
559 /// button reading this by a call of its own would keep a stale light on. Same
560 /// reason `heading` is here and not asked for.
561 ///
562 /// Only a *parsed* link answers ([`LeafDoc::link_destination_at_caret`]);
563 /// a wikilink is literal text with no node behind it, and has nothing to
564 /// repoint — see `LinkTarget.swift`.
565 pub link: Option<String>,
566 /// The colour of the highlight the caret stands in — which swatch a colour
567 /// palette draws as the current one, and `None` both outside a highlight and
568 /// inside an uncoloured one.
569 ///
570 /// It rides the frame for `link`'s reason, and more sharply: walking from a
571 /// red highlight into a blue one changes no mark, no heading, no dirty flag
572 /// and no link, so a palette asking for itself would never be told to move
573 /// its checkmark.
574 ///
575 /// An enum rather than the name string [`Run::mark_color`] carries, because
576 /// the two are different questions. A run's colour is a *rendering* hint that
577 /// has to survive a name this build has never heard of (a newer twig's
578 /// eighth colour draws as a plain highlight rather than not at all); this is
579 /// the closed palette a control offers, and a name outside it is not a
580 /// swatch anyone can press.
581 pub mark_color: Option<MarkColor>,
582}
583
584/// The colour of a highlight — the closed palette [`LeafDoc::set_mark_color`]
585/// writes and [`DocView::mark_color`] reports.
586///
587/// Obsidian's spelling, which is twig's: a circle emoji straight after the
588/// opening `==`, so `==🔴 text==` is a highlight of `text` in [`MarkColor::Red`].
589/// The emoji is *spelling* rather than content — it never appears in the text a
590/// reader sees, and never in a [`Run`].
591#[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)]
592pub enum MarkColor {
593 Red,
594 Orange,
595 Yellow,
596 Green,
597 Blue,
598 Purple,
599 Brown,
600}
601
602impl From<CoreMarkColor> for MarkColor {
603 fn from(c: CoreMarkColor) -> Self {
604 match c {
605 CoreMarkColor::Red => MarkColor::Red,
606 CoreMarkColor::Orange => MarkColor::Orange,
607 CoreMarkColor::Yellow => MarkColor::Yellow,
608 CoreMarkColor::Green => MarkColor::Green,
609 CoreMarkColor::Blue => MarkColor::Blue,
610 CoreMarkColor::Purple => MarkColor::Purple,
611 CoreMarkColor::Brown => MarkColor::Brown,
612 }
613 }
614}
615
616impl From<MarkColor> for CoreMarkColor {
617 fn from(c: MarkColor) -> Self {
618 match c {
619 MarkColor::Red => CoreMarkColor::Red,
620 MarkColor::Orange => CoreMarkColor::Orange,
621 MarkColor::Yellow => CoreMarkColor::Yellow,
622 MarkColor::Green => CoreMarkColor::Green,
623 MarkColor::Blue => CoreMarkColor::Blue,
624 MarkColor::Purple => CoreMarkColor::Purple,
625 MarkColor::Brown => CoreMarkColor::Brown,
626 }
627 }
628}
629
630/// A visual position: a row index plus a UTF-16 offset within that row's text —
631/// the coordinate the geometry side (Core Text) draws from. Returned by
632/// [`LeafDoc::pos_for_offset`], the bridge from a source offset (what a
633/// `UITextPosition` wraps) to where it sits on screen.
634#[derive(uniffi::Record)]
635pub struct RowCol {
636 pub row: u32,
637 pub ch: u32,
638}
639
640/// The rows a source range covers, both ends **inclusive** — what a frontend
641/// slices out of a frame to draw a block somewhere other than where it sits: a
642/// footnote peek, a link peek, a landing flash. Returned by
643/// [`LeafDoc::row_range_for`].
644///
645/// Inclusive rather than half-open because the answer is "these rows", not "up
646/// to here": every caller wants `rows[first...last]`, and a `last` one past the
647/// end would be a second thing to get wrong at each of them. `last >= first`
648/// always, so the pair is never empty — a range with no visible byte still
649/// covers the row it opened on.
650#[derive(uniffi::Record)]
651pub struct RowRange {
652 pub first: u32,
653 pub last: u32,
654}
655
656/// Which formatting controls this document's format can spell — the toolbar's
657/// enabled state, one flag per button, from [`LeafDoc::capabilities`]. Mirrors
658/// [`leaf_core::Capabilities`], where the reasoning lives.
659///
660/// Its shape is a flat record of `Bool`s rather than a query taking a gesture
661/// because the Swift side wants exactly one crossing and a value it can hold in
662/// an `@Observable`: `let caps = doc.capabilities()`, then
663/// `.disabled(!caps.bold)` on each control.
664#[derive(uniffi::Record)]
665pub struct Capabilities {
666 pub bold: bool,
667 pub italic: bool,
668 pub code: bool,
669 pub mark: bool,
670 pub underline: bool,
671 pub strike: bool,
672 /// [`LeafDoc::set_mark_color`] — the highlight *palette*, which Markdown
673 /// spells and djot does not, though both spell the highlight itself. Gate
674 /// the swatches on this *and* on [`LeafDoc::caret_in_mark`], the way the grid
675 /// controls take `table` and `caret_in_table`: one is a fact about the
676 /// format, the other about where the caret is standing.
677 pub mark_color: bool,
678 pub superscript: bool,
679 pub subscript: bool,
680 /// Both [`LeafDoc::set_heading`] and [`LeafDoc::set_paragraph`] — they are
681 /// the same gesture in core and stand or fall together.
682 pub heading: bool,
683 pub blockquote: bool,
684 pub bullet_list: bool,
685 pub ordered_list: bool,
686 /// [`LeafDoc::toggle_task_item`], [`LeafDoc::toggle_task_checked`] and
687 /// [`LeafDoc::toggle_task_at`] — including a *tap* on a rendered checkbox,
688 /// which should not be live where the box cannot be spelled.
689 pub task: bool,
690 pub link: bool,
691 /// [`LeafDoc::insert_image`] and [`LeafDoc::insert_media`] both.
692 pub image: bool,
693 pub thematic_break: bool,
694 /// [`LeafDoc::insert_footnote`]. Markdown and djot spell the pair; HTML does
695 /// not, so the button goes rather than dims into a refusal.
696 pub footnote: bool,
697 pub code_language: bool,
698 /// The grid controls. Gate them on this *and* [`LeafDoc::caret_in_table`]:
699 /// this asks whether the format's tables are editable, that whether the
700 /// caret is in one.
701 pub table: bool,
702 /// Shift+Return inside a cell — [`LeafDoc::cell_line_break`].
703 pub cell_line_break: bool,
704}
705
706impl From<CoreCapabilities> for Capabilities {
707 fn from(c: CoreCapabilities) -> Self {
708 Self {
709 bold: c.bold,
710 italic: c.italic,
711 code: c.code,
712 mark: c.mark,
713 underline: c.underline,
714 strike: c.strike,
715 mark_color: c.mark_color,
716 superscript: c.superscript,
717 // `subscript` is a Swift keyword; uniffi escapes it in the generated
718 // binding (`caps.`subscript``), so the field keeps its real name
719 // here rather than wearing a suffix on both sides of the boundary.
720 subscript: c.subscript,
721 heading: c.heading,
722 blockquote: c.blockquote,
723 bullet_list: c.bullet_list,
724 ordered_list: c.ordered_list,
725 task: c.task,
726 link: c.link,
727 image: c.image,
728 thematic_break: c.thematic_break,
729 footnote: c.footnote,
730 code_language: c.code_language,
731 table: c.table,
732 cell_line_break: c.cell_line_break,
733 }
734 }
735}
736
737/// A table column's text alignment — the argument to
738/// [`LeafDoc::table_set_alignment`]. Mirrors twig's `Alignment`.
739#[derive(uniffi::Enum)]
740pub enum TableAlignment {
741 Default,
742 Left,
743 Right,
744 Center,
745}
746
747impl TableAlignment {
748 fn into_core(self) -> Alignment {
749 match self {
750 TableAlignment::Default => Alignment::Default,
751 TableAlignment::Left => Alignment::Left,
752 TableAlignment::Right => Alignment::Right,
753 TableAlignment::Center => Alignment::Center,
754 }
755 }
756}
757
758/// How much of the source markup the rich view exposes — the argument to
759/// [`LeafDoc::set_markup_mode`]. Mirrors [`leaf_core::MarkupMode`]; `None`
760/// is the default (the clean surface Diaryx ships, with typed syntax kept
761/// literal).
762///
763/// A single three-way ladder rather than a pair of toggles, because only three
764/// of the four combinations of its two axes — reveal the caret's delimiters,
765/// author markup from typing — are coherent. See [`leaf_core::MarkupMode`]
766/// for which one is left out and why.
767#[derive(uniffi::Enum)]
768pub enum MarkupMode {
769 None,
770 Shortcuts,
771 Full,
772}
773
774impl MarkupMode {
775 fn into_core(self) -> CoreMarkupMode {
776 match self {
777 MarkupMode::None => CoreMarkupMode::None,
778 MarkupMode::Shortcuts => CoreMarkupMode::Shortcuts,
779 MarkupMode::Full => CoreMarkupMode::Full,
780 }
781 }
782
783 fn from_core(mode: CoreMarkupMode) -> Self {
784 match mode {
785 CoreMarkupMode::None => MarkupMode::None,
786 CoreMarkupMode::Shortcuts => MarkupMode::Shortcuts,
787 CoreMarkupMode::Full => MarkupMode::Full,
788 }
789 }
790}
791
792/// How the rich view treats a soft break (a bare newline inside a paragraph) —
793/// the argument to [`LeafDoc::set_line_flow`]. Mirrors [`leaf_core::LineFlow`];
794/// `Fold` is the default (soft breaks reflow into the paragraph, as before).
795#[derive(uniffi::Enum)]
796pub enum LineFlow {
797 Fold,
798 Preserve,
799}
800
801impl LineFlow {
802 fn into_core(self) -> CoreLineFlow {
803 match self {
804 LineFlow::Fold => CoreLineFlow::Fold,
805 LineFlow::Preserve => CoreLineFlow::Preserve,
806 }
807 }
808
809 fn from_core(mode: CoreLineFlow) -> Self {
810 match mode {
811 CoreLineFlow::Fold => LineFlow::Fold,
812 CoreLineFlow::Preserve => LineFlow::Preserve,
813 }
814 }
815}
816
817/// A live leaf document bound for a native Apple frontend: `leaf_core::Doc` plus
818/// the wrap width the current viewport implies, behind a mutex. Constructed from
819/// an in-memory string and driven entirely through method calls — there is no
820/// filesystem behind it.
821#[derive(uniffi::Object)]
822pub struct LeafDoc {
823 inner: Mutex<Inner>,
824}
825
826/// The guarded state. Its methods assume the lock is held (they take `&mut
827/// self`); the [`LeafDoc`] exported wrappers acquire it, delegate, and return the
828/// resulting frame.
829struct Inner {
830 doc: Doc,
831 /// The wrap mode. `Some(cols)` wraps the map at that column budget (a terminal,
832 /// or a fixed-cell frontend); `None` builds it **unwrapped** — one row per block —
833 /// for a proportional GUI that wraps at its own pixel width. `build_visual`
834 /// caches on `(revision, width)`, so re-syncing when neither moved is free.
835 width: Option<usize>,
836 /// The host's current appearance, which a `<picture>`'s `prefers-color-scheme`
837 /// `<source>`s are matched against when resolving a block image's URL. Core
838 /// has no theme of its own, so this is AppKit/UIKit answering on its behalf;
839 /// defaults to light until the host calls
840 /// [`LeafDoc::set_dark_appearance`].
841 scheme: ColorScheme,
842}
843
844// SAFETY: `Doc` embeds a `twig::Editor`, which holds a `NonNull<TwigEditor>` and
845// is therefore `!Send`. UniFFI hands `LeafDoc` to Swift as a reference-counted
846// handle that must be `Send + Sync`, so `Inner` must be `Send`. This is sound
847// because:
848// 1. Every access goes through `LeafDoc::lock()` — the `Mutex` serializes all
849// reads and mutations, so there is never concurrent access to the handle.
850// 2. twig's editor handle owns a plain heap allocation with no thread-affinity
851// (no thread-locals, no per-thread state) — moving the pointer between
852// threads is fine as long as use is serialized, which (1) guarantees.
853// The intended usage is still main-thread-driven; this impl only permits the
854// handle to cross threads safely, it does not invite concurrent use.
855unsafe impl Send for Inner {}
856
857impl Inner {
858 /// Rebuild the visual map at the current width. Cheap (cached) when nothing
859 /// changed; the guard that lets every movement/click method assume a fresh
860 /// grid regardless of call order.
861 fn sync(&mut self) {
862 match self.width {
863 Some(w) => self.doc.build_visual(w),
864 None => self.doc.build_visual_unwrapped(),
865 }
866 }
867
868 /// The plain text of visual row `row` in the active view — the string the
869 /// renderer concatenates its runs into. Backs the column⇄UTF-16 mapping.
870 fn row_text(&self, row: usize) -> String {
871 match self.doc.view {
872 View::Wysiwyg => self
873 .doc
874 .vmap
875 .rows
876 .get(row)
877 .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
878 .unwrap_or_default(),
879 View::Source => self
880 .doc
881 .source
882 .split('\n')
883 .nth(row)
884 .unwrap_or("")
885 .to_string(),
886 }
887 }
888
889 /// The `(row, display-column)` a source offset sits at in the active view.
890 fn pos_of_offset(&self, off: usize) -> (usize, usize) {
891 match self.doc.view {
892 View::Wysiwyg => self.doc.vmap.pos_of_offset(off),
893 View::Source => {
894 let s = &self.doc.source;
895 // Walk back to a character boundary, not just into range. Every
896 // offset here arrives from a UI toolkit counting in its own
897 // units, so one landing mid-character is ordinary input — and
898 // slicing on it aborts the process across an FFI boundary that
899 // has no unwinding. `snap_stop` and `text_in_range` already do
900 // this; this was the one door left open.
901 let mut off = off.min(s.len());
902 while off > 0 && !s.is_char_boundary(off) {
903 off -= 1;
904 }
905 let row = s[..off].bytes().filter(|&b| b == b'\n').count();
906 let line_start = s[..off].rfind('\n').map_or(0, |i| i + 1);
907 (row, text_width(&s[line_start..off]))
908 }
909 }
910 }
911
912 /// The inclusive row span a source range occupies in the active view.
913 ///
914 /// The rich view defers to [`leaf_core::wysiwyg::VisualMap::row_range_for`],
915 /// where the reasoning lives. The source view has no hidden bytes at all —
916 /// every byte is drawn on the line it is written on — so counting newlines
917 /// is the whole answer, and the last row is the one holding the range's last
918 /// byte rather than the one past it.
919 fn row_range_for(&self, start: usize, end: usize) -> (usize, usize) {
920 match self.doc.view {
921 View::Wysiwyg => self.doc.vmap.row_range_for(start..end),
922 View::Source => {
923 let first = self.pos_of_offset(start).0;
924 let last = self.pos_of_offset(end.max(start.saturating_add(1)) - 1).0;
925 (first, last.max(first))
926 }
927 }
928 }
929
930 /// The source offset under a click at row `row`, `ch` UTF-16 units in.
931 fn offset_at(&mut self, row: usize, ch: usize) -> usize {
932 self.sync();
933 let col = utf16_to_col(&self.row_text(row), ch);
934 self.doc.click(row, col, false);
935 self.doc.caret
936 }
937
938 // ── position mapping for UITextInput (non-mutating; caret untouched) ───────
939 // These branch by view exactly as `pos_of_offset` does, so the WYSIWYG map and
940 // the raw-source grid each answer in their own coordinates.
941
942 /// The source offset of display column `col` on visual `row` — the inverse of
943 /// [`Self::pos_of_offset`] in column space.
944 fn offset_of_col(&self, row: usize, col: usize) -> usize {
945 match self.doc.view {
946 View::Wysiwyg => self.doc.vmap.offset_of_pos(row, col),
947 View::Source => {
948 let line = self.row_text(row);
949 let (mut c, mut b) = (0usize, 0usize);
950 for g in line.graphemes(true) {
951 if c >= col {
952 break;
953 }
954 c += text_width(g);
955 b += g.len();
956 }
957 self.source_line_start(row) + b
958 }
959 }
960 }
961
962 /// The byte offset where visual `row` begins in the source view.
963 fn source_line_start(&self, row: usize) -> usize {
964 self.doc
965 .source
966 .split('\n')
967 .take(row)
968 .map(|l| l.len() + 1)
969 .sum()
970 }
971
972 /// The next caret stop after `off`, or `None` at the end.
973 fn stop_after(&self, off: usize) -> Option<usize> {
974 match self.doc.view {
975 View::Wysiwyg => self.doc.vmap.stop_after(off),
976 View::Source => {
977 let s = &self.doc.source;
978 if off >= s.len() {
979 None
980 } else {
981 Some(
982 s[off..]
983 .grapheme_indices(true)
984 .nth(1)
985 .map_or(s.len(), |(i, _)| off + i),
986 )
987 }
988 }
989 }
990 }
991
992 /// The previous caret stop before `off`, or `None` at the start.
993 fn stop_before(&self, off: usize) -> Option<usize> {
994 match self.doc.view {
995 View::Wysiwyg => self.doc.vmap.stop_before(off),
996 View::Source => {
997 let s = &self.doc.source;
998 let off = off.min(s.len());
999 if off == 0 {
1000 None
1001 } else {
1002 s[..off].grapheme_indices(true).next_back().map(|(i, _)| i)
1003 }
1004 }
1005 }
1006 }
1007
1008 /// Snap `off` to a valid caret stop (WYSIWYG) / char boundary (source).
1009 fn snap_stop(&self, off: usize) -> usize {
1010 let s = &self.doc.source;
1011 let mut off = off.min(s.len());
1012 match self.doc.view {
1013 View::Wysiwyg => self.doc.vmap.snap_to_stop(off),
1014 View::Source => {
1015 while off > 0 && !s.is_char_boundary(off) {
1016 off -= 1;
1017 }
1018 off
1019 }
1020 }
1021 }
1022
1023 /// The navigable visual row above `row`, if any.
1024 fn nav_above(&self, row: usize) -> Option<usize> {
1025 match self.doc.view {
1026 View::Wysiwyg => self.doc.vmap.navigable_above(row),
1027 View::Source => (row > 0).then(|| row - 1),
1028 }
1029 }
1030
1031 /// The navigable visual row below `row`, if any.
1032 fn nav_below(&self, row: usize) -> Option<usize> {
1033 match self.doc.view {
1034 View::Wysiwyg => self.doc.vmap.navigable_below(row),
1035 View::Source => {
1036 let n = self.doc.source.split('\n').count();
1037 (row + 1 < n).then_some(row + 1)
1038 }
1039 }
1040 }
1041
1042 /// Resolve the current document to a renderable frame of style runs. Called
1043 /// for the first paint, on resize, and by every mutating wrapper so one
1044 /// boundary crossing both edits and repaints.
1045 fn view(&mut self) -> DocView {
1046 self.sync();
1047
1048 let (ss, se) = self.doc.selection().unwrap_or((usize::MAX, usize::MAX));
1049
1050 // The two views speak different grids — the WYSIWYG map's resolved glyphs
1051 // vs the raw source split on newlines — and `caret_pos` branches to match,
1052 // so the rows must too or the caret lands on the wrong text.
1053 let rows = match self.doc.view {
1054 View::Wysiwyg => wysiwyg_rows(&self.doc.vmap, ss, se, self.doc.highlights()),
1055 View::Source => source_rows(&self.doc.source, ss, se),
1056 };
1057 // Structural tables, for a proportional renderer that draws its own grid;
1058 // none in the source view (the caret rides raw pipe text there).
1059 let tables = match self.doc.view {
1060 View::Wysiwyg => wysiwyg_tables(&self.doc.vmap, ss, se, self.doc.highlights()),
1061 View::Source => Vec::new(),
1062 };
1063
1064 // Leaf directives, on the same terms as the tables above: structural in
1065 // the rich view, absent in the source view.
1066 let directives = match self.doc.view {
1067 View::Wysiwyg => wysiwyg_directives(&self.doc.vmap),
1068 View::Source => Vec::new(),
1069 };
1070
1071 // Block media, on the same terms again: only the rich view has
1072 // placeholder rows to lay a view over.
1073 let media = match self.doc.view {
1074 View::Wysiwyg => wysiwyg_media(&self.doc.vmap, self.scheme),
1075 View::Source => Vec::new(),
1076 };
1077
1078 let (caret_row, caret_col) = self.doc.caret_pos();
1079 // Map the caret's display column to a UTF-16 text offset so a native
1080 // renderer can place it past wide glyphs (see [`DocView::caret_ch`]).
1081 let caret_ch = col_to_utf16(&self.row_text(caret_row), caret_col);
1082 // The selection's fixed (anchor) end, in the same row/UTF-16 terms.
1083 let (has_selection, anchor_row, anchor_ch) = match self.doc.selection() {
1084 Some(_) => {
1085 let a = self.doc.anchor.unwrap_or(self.doc.caret);
1086 let (ar, ac) = self.pos_of_offset(a);
1087 (true, ar, col_to_utf16(&self.row_text(ar), ac))
1088 }
1089 None => (false, caret_row, caret_ch),
1090 };
1091 let heading = self.doc.current_heading_level();
1092 let active = self
1093 .doc
1094 .active_inline_marks()
1095 .iter()
1096 .map(|k| mark_id(k).to_string())
1097 .collect();
1098 let link = self.doc.link_destination_at_caret();
1099 let mark_color = self.doc.mark_color_at_caret().map(MarkColor::from);
1100
1101 DocView {
1102 rows,
1103 tables,
1104 directives,
1105 media,
1106 caret_row: caret_row as u32,
1107 caret_col: caret_col as u32,
1108 caret_ch: caret_ch as u32,
1109 caret_src: self.doc.caret.min(self.doc.source.len()) as u32,
1110 has_selection,
1111 anchor_row: anchor_row as u32,
1112 anchor_ch: anchor_ch as u32,
1113 dirty: self.doc.dirty,
1114 can_undo: self.doc.can_undo(),
1115 can_redo: self.doc.can_redo(),
1116 view: self.doc.view_name().to_string(),
1117 heading,
1118 active,
1119 link,
1120 mark_color,
1121 }
1122 }
1123}
1124
1125#[uniffi::export]
1126impl LeafDoc {
1127 /// Parse `source` as `format` (`"markdown"`/`"md"`, `"djot"`/`"dj"`,
1128 /// `"html"`, `"xml"`) into a live, untitled document.
1129 #[uniffi::constructor]
1130 pub fn new(source: String, format: String) -> Result<Arc<Self>, LeafError> {
1131 let format = match format.to_ascii_lowercase().as_str() {
1132 "markdown" | "md" => Format::Markdown,
1133 "djot" | "dj" => Format::Djot,
1134 "html" | "htm" => Format::Html,
1135 "xml" => Format::Xml,
1136 other => {
1137 return Err(LeafError::UnknownFormat {
1138 name: other.to_string(),
1139 });
1140 }
1141 };
1142 let doc = Doc::from_source(source, format).map_err(|e| LeafError::Parse {
1143 message: e.to_string(),
1144 })?;
1145 Ok(Arc::new(LeafDoc {
1146 inner: Mutex::new(Inner {
1147 doc,
1148 width: Some(80),
1149 scheme: ColorScheme::Light,
1150 }),
1151 }))
1152 }
1153
1154 /// Resolve the current document to a renderable frame — the first paint.
1155 pub fn view(&self) -> DocView {
1156 self.lock().view()
1157 }
1158
1159 /// Set the wrap width (in columns) the viewport implies and repaint. For a
1160 /// fixed-cell frontend (a terminal); a proportional GUI uses [`set_unwrapped`].
1161 pub fn set_width(&self, cols: u32) -> DocView {
1162 let mut g = self.lock();
1163 g.width = Some((cols as usize).max(1));
1164 g.view()
1165 }
1166
1167 /// Switch to **unwrapped** layout — one visual row per block, no column wrapping —
1168 /// and repaint. A proportional GUI calls this once at start-up, then wraps each
1169 /// row at its own pixel width (the caret/hit/selection geometry it derives from
1170 /// the pixel wrap; core still owns the caret model, in byte offsets). Idempotent
1171 /// and cheap to leave in place across edits.
1172 pub fn set_unwrapped(&self) -> DocView {
1173 let mut g = self.lock();
1174 g.width = None;
1175 g.view()
1176 }
1177
1178 /// Tell core whether the host is in a dark appearance, so a `<picture>`'s
1179 /// `prefers-color-scheme` `<source>`s resolve to the right banner. Call it
1180 /// from `viewDidChangeEffectiveAppearance` (AppKit) or
1181 /// `traitCollectionDidChange` (UIKit).
1182 ///
1183 /// Cheap to call repeatedly: resolving at the same appearance yields the same
1184 /// URLs, and a renderer keying its views by `src` tears nothing down.
1185 pub fn set_dark_appearance(&self, dark: bool) -> DocView {
1186 let mut g = self.lock();
1187 g.scheme = if dark {
1188 ColorScheme::Dark
1189 } else {
1190 ColorScheme::Light
1191 };
1192 g.view()
1193 }
1194
1195 /// Report how many visual rows each block media actually needs, measured from
1196 /// the views the renderer laid out, keyed by the media's `src`.
1197 ///
1198 /// Core does no I/O and can't know how tall a picture or a player is, so this
1199 /// is the only way a placeholder grows past its default single row. The loop
1200 /// is: lay out at the current reservation → measure → call this → repaint if
1201 /// it changed. Handing over the same measurements again is a no-op, so a
1202 /// renderer can report its current state each frame without diffing first.
1203 ///
1204 /// A frontend that lays media out in its own units and simply reserves the
1205 /// vertical space itself (the way the gpui GUI does with images) never needs
1206 /// to call this at all.
1207 pub fn set_media_rows(&self, heights: Vec<MediaHeight>) -> DocView {
1208 let mut g = self.lock();
1209 g.doc.set_media_rows(
1210 heights
1211 .into_iter()
1212 .map(|h| (h.destination, h.rows.max(1) as usize))
1213 .collect(),
1214 );
1215 g.view()
1216 }
1217
1218 /// Insert a block-level image, video, or audio at the caret. Any selection
1219 /// becomes the alt / fallback text. See [`leaf_core::Doc::insert_media`] for
1220 /// the markup each kind spells.
1221 pub fn insert_media(&self, kind: MediaKind, destination: String, alt: String) -> DocView {
1222 let mut g = self.lock();
1223 let kind = match kind {
1224 MediaKind::Image => CoreMediaKind::Image,
1225 MediaKind::Video => CoreMediaKind::Video,
1226 MediaKind::Audio => CoreMediaKind::Audio,
1227 };
1228 g.doc.insert_media(kind, &destination, &alt);
1229 g.view()
1230 }
1231
1232 /// Insert a thematic break (`---`) at the caret — the toolbar's Horizontal
1233 /// Rule button. See [`leaf_core::Doc::insert_thematic_break`] for how it
1234 /// handles a selection, a blank line, and the caret sitting mid-paragraph,
1235 /// mid-list, or inside a quote.
1236 pub fn insert_thematic_break(&self) -> DocView {
1237 let mut g = self.lock();
1238 g.doc.insert_thematic_break();
1239 g.view()
1240 }
1241
1242 /// The current source text — for a save (write to disk / iCloud / a document
1243 /// wrapper) or a source-view display.
1244 pub fn source(&self) -> String {
1245 self.lock().doc.source.clone()
1246 }
1247
1248 /// The selected text, if any — for a clipboard copy/cut.
1249 pub fn selected_text(&self) -> Option<String> {
1250 self.lock().doc.selected_text().map(str::to_string)
1251 }
1252
1253 /// The selection as a quote with up to `context` characters of what
1254 /// surrounded it, cut from the **source** — the shape a host that cites or
1255 /// annotates a passage wants, findable in the document again by plain
1256 /// string search. `None` when nothing is selected. See
1257 /// `leaf_core::Doc::selection_quote`.
1258 pub fn selection_quote(&self, context: u32) -> Option<SelectionQuote> {
1259 let g = self.lock();
1260 g.doc
1261 .selection_quote(context as usize)
1262 .map(|q| SelectionQuote {
1263 exact: q.exact,
1264 prefix: q.prefix,
1265 suffix: q.suffix,
1266 start: q.start as u64,
1267 end: q.end as u64,
1268 })
1269 }
1270
1271 /// Whether the document refuses to change — see `set_read_only`.
1272 pub fn read_only(&self) -> bool {
1273 self.lock().doc.read_only()
1274 }
1275
1276 /// Turn the read-only gate on or off — a *reading* surface over the same
1277 /// rendering, selection and navigation the editor has. Enforced in core at
1278 /// the three doors every mutation goes through, so a host that also quiets
1279 /// its input chrome is polishing, not protecting.
1280 pub fn set_read_only(&self, on: bool) -> DocView {
1281 let mut g = self.lock();
1282 g.doc.set_read_only(on);
1283 g.view()
1284 }
1285
1286 /// Replace the host-painted source ranges wholesale and repaint — see
1287 /// `leaf_core::Doc::set_highlights` for why it is a replace, and
1288 /// [`Highlight`] for what one is.
1289 pub fn set_highlights(&self, highlights: Vec<Highlight>) -> DocView {
1290 let mut g = self.lock();
1291 let hls = highlights
1292 .into_iter()
1293 .map(|h| leaf_core::Highlight {
1294 start: h.start as usize,
1295 end: h.end as usize,
1296 id: h.id,
1297 color: h.color,
1298 marker: h.marker,
1299 })
1300 .collect();
1301 g.doc.set_highlights(hls);
1302 g.view()
1303 }
1304
1305 /// The id of the highlight covering source `offset`, if one does — what a
1306 /// frontend asks when the reader activates a spot on the page.
1307 pub fn highlight_at(&self, offset: u32) -> Option<String> {
1308 self.lock()
1309 .doc
1310 .highlight_at(offset as usize)
1311 .map(|h| h.id.clone())
1312 }
1313
1314 /// The host-painted ranges as last set, sorted by start — what a frontend
1315 /// walks to lay out margin markers.
1316 pub fn highlights(&self) -> Vec<Highlight> {
1317 self.lock()
1318 .doc
1319 .highlights()
1320 .iter()
1321 .map(|h| Highlight {
1322 start: h.start as u64,
1323 end: h.end as u64,
1324 id: h.id.clone(),
1325 color: h.color.clone(),
1326 marker: h.marker.clone(),
1327 })
1328 .collect()
1329 }
1330
1331 /// Mark the buffer saved after the host persisted [`LeafDoc::source`] its own
1332 /// way — clears the dirty flag without touching a filesystem.
1333 pub fn mark_saved(&self) -> DocView {
1334 let mut g = self.lock();
1335 g.doc.mark_saved();
1336 g.view()
1337 }
1338
1339 // ── text input ───────────────────────────────────────────────────────────
1340
1341 pub fn insert(&self, text: String) -> DocView {
1342 let mut g = self.lock();
1343 g.doc.insert(&text);
1344 g.view()
1345 }
1346
1347 pub fn paste(&self, text: String) -> DocView {
1348 let mut g = self.lock();
1349 g.doc.paste(&text);
1350 g.view()
1351 }
1352
1353 pub fn newline(&self) -> DocView {
1354 let mut g = self.lock();
1355 g.doc.newline();
1356 g.view()
1357 }
1358
1359 /// Tab away from a table: indent the caret's line (or the selected lines) one
1360 /// level, nesting a list item under its sibling. The frontend calls this when
1361 /// [`LeafDoc::cell_tab`] declined because the caret isn't in a table.
1362 pub fn indent(&self) -> DocView {
1363 let mut g = self.lock();
1364 g.doc.indent();
1365 g.view()
1366 }
1367
1368 /// Shift+Tab away from a table: take one indent level back off the caret's
1369 /// line (or the selected lines), unnesting a list item. The mirror of
1370 /// [`LeafDoc::indent`].
1371 pub fn outdent(&self) -> DocView {
1372 let mut g = self.lock();
1373 g.doc.outdent();
1374 g.view()
1375 }
1376
1377 // ── table keys ────────────────────────────────────────────────────────────
1378 // Tab, Return, and Shift+Return take on table meanings when the caret is in
1379 // one. Each returns `Some(view)` when it acted as a table key and `None` when
1380 // the caret isn't in a table — the frontend then does the key's ordinary job
1381 // (indent, newline), so these keep their meaning everywhere else.
1382
1383 /// Tab (`forward`) / Shift+Tab hops to the next/previous cell; Tab past the
1384 /// last cell appends a fresh row and enters it.
1385 pub fn cell_tab(&self, forward: bool) -> Option<DocView> {
1386 let mut g = self.lock();
1387 g.sync();
1388 g.doc.cell_tab(forward).then(|| g.view())
1389 }
1390
1391 /// Return drops to the cell below in the same column, appending a row at the
1392 /// table's bottom.
1393 pub fn cell_return(&self) -> Option<DocView> {
1394 let mut g = self.lock();
1395 g.sync();
1396 g.doc.cell_return().then(|| g.view())
1397 }
1398
1399 /// Shift+Return inserts a hard line break *within* the current cell.
1400 pub fn cell_line_break(&self) -> Option<DocView> {
1401 let mut g = self.lock();
1402 g.sync();
1403 g.doc.cell_line_break().then(|| g.view())
1404 }
1405
1406 pub fn backspace(&self) -> DocView {
1407 let mut g = self.lock();
1408 g.doc.backspace();
1409 g.view()
1410 }
1411
1412 pub fn delete_forward(&self) -> DocView {
1413 let mut g = self.lock();
1414 g.doc.delete_forward();
1415 g.view()
1416 }
1417
1418 pub fn delete_word_back(&self) -> DocView {
1419 let mut g = self.lock();
1420 g.doc.delete_word_back();
1421 g.view()
1422 }
1423
1424 pub fn delete_word_forward(&self) -> DocView {
1425 let mut g = self.lock();
1426 g.doc.delete_word_forward();
1427 g.view()
1428 }
1429
1430 // ── caret movement ───────────────────────────────────────────────────────
1431 // Each syncs the grid first (movement reads the stop table / column layout),
1432 // moves, then repaints — `Inner::view` re-syncs but that's the cached no-op.
1433
1434 pub fn move_left(&self, extend: bool) -> DocView {
1435 let mut g = self.lock();
1436 g.sync();
1437 g.doc.move_left(extend);
1438 g.view()
1439 }
1440
1441 pub fn move_right(&self, extend: bool) -> DocView {
1442 let mut g = self.lock();
1443 g.sync();
1444 g.doc.move_right(extend);
1445 g.view()
1446 }
1447
1448 pub fn move_up(&self, extend: bool) -> DocView {
1449 let mut g = self.lock();
1450 g.sync();
1451 g.doc.move_up(extend);
1452 g.view()
1453 }
1454
1455 pub fn move_down(&self, extend: bool) -> DocView {
1456 let mut g = self.lock();
1457 g.sync();
1458 g.doc.move_down(extend);
1459 g.view()
1460 }
1461
1462 pub fn move_word_left(&self, extend: bool) -> DocView {
1463 let mut g = self.lock();
1464 g.sync();
1465 g.doc.move_word_left(extend);
1466 g.view()
1467 }
1468
1469 pub fn move_word_right(&self, extend: bool) -> DocView {
1470 let mut g = self.lock();
1471 g.sync();
1472 g.doc.move_word_right(extend);
1473 g.view()
1474 }
1475
1476 pub fn move_home(&self, extend: bool) -> DocView {
1477 let mut g = self.lock();
1478 g.sync();
1479 g.doc.move_home(extend);
1480 g.view()
1481 }
1482
1483 pub fn move_end(&self, extend: bool) -> DocView {
1484 let mut g = self.lock();
1485 g.sync();
1486 g.doc.move_end(extend);
1487 g.view()
1488 }
1489
1490 pub fn move_doc_start(&self, extend: bool) -> DocView {
1491 let mut g = self.lock();
1492 g.sync();
1493 g.doc.move_doc_start(extend);
1494 g.view()
1495 }
1496
1497 pub fn move_doc_end(&self, extend: bool) -> DocView {
1498 let mut g = self.lock();
1499 g.sync();
1500 g.doc.move_doc_end(extend);
1501 g.view()
1502 }
1503
1504 pub fn select_all(&self) -> DocView {
1505 let mut g = self.lock();
1506 g.doc.select_all();
1507 g.view()
1508 }
1509
1510 /// Place the caret from a click, in core's column grid: `row` indexes the
1511 /// visual [`Row`]s and `col` is the glyph column within it. Core clamps both
1512 /// to real caret stops. Prefer [`LeafDoc::click_ch`] from a proportional
1513 /// renderer.
1514 pub fn click(&self, row: u32, col: u32, extend: bool) -> DocView {
1515 let mut g = self.lock();
1516 g.sync();
1517 g.doc.click(row as usize, col as usize, extend);
1518 g.view()
1519 }
1520
1521 /// Place the caret from a click whose horizontal position is a **UTF-16
1522 /// offset** into the visual row's text — what `characterIndex(for:)` hands
1523 /// back. Converted to core's display column before clicking, so a proportional
1524 /// renderer never reasons about column widths itself.
1525 pub fn click_ch(&self, row: u32, ch: u32, extend: bool) -> DocView {
1526 let mut g = self.lock();
1527 g.sync();
1528 let col = utf16_to_col(&g.row_text(row as usize), ch as usize);
1529 g.doc.click(row as usize, col, extend);
1530 g.view()
1531 }
1532
1533 /// Select the word under a click (row, `ch`) — the double-click gesture.
1534 pub fn select_word_ch(&self, row: u32, ch: u32) -> DocView {
1535 let mut g = self.lock();
1536 let off = g.offset_at(row as usize, ch as usize);
1537 g.doc.select_word_at(off);
1538 g.view()
1539 }
1540
1541 /// Select the whole logical text block under a click (row, `ch`) — the
1542 /// triple-click gesture. Grabs the entire block even where it soft-wraps.
1543 pub fn select_block_ch(&self, row: u32, ch: u32) -> DocView {
1544 let mut g = self.lock();
1545 let off = g.offset_at(row as usize, ch as usize);
1546 g.doc.select_block_at(off);
1547 g.view()
1548 }
1549
1550 /// Mirror a native selection into the model: `[anchor, focus]` given as
1551 /// row + UTF-16 offset pairs. Each is resolved to a source offset the way a
1552 /// click is, then set as the selection's fixed and moving ends. A collapsed
1553 /// range (`anchor == focus`) just places the caret.
1554 pub fn set_selection(
1555 &self,
1556 anchor_row: u32,
1557 anchor_ch: u32,
1558 focus_row: u32,
1559 focus_ch: u32,
1560 ) -> DocView {
1561 let mut g = self.lock();
1562 let anchor = g.offset_at(anchor_row as usize, anchor_ch as usize);
1563 let focus = g.offset_at(focus_row as usize, focus_ch as usize);
1564 g.doc.place_caret(anchor, false);
1565 if anchor != focus {
1566 g.doc.place_caret(focus, true);
1567 }
1568 g.view()
1569 }
1570
1571 // ── rich clipboard (mirrors leaf-tui / leaf-gpui / leaf-wasm) ─────────────
1572
1573 /// The current selection rendered to HTML by twig — the rich flavor a copy
1574 /// writes alongside the plain [`LeafDoc::selected_text`]. `None` when nothing
1575 /// is selected.
1576 pub fn selection_html(&self) -> Option<String> {
1577 self.lock().doc.selection_html()
1578 }
1579
1580 /// Paste, preferring the clipboard's rich (`text/html`) flavor: twig parses
1581 /// `html` into the document's own markup and inserts it. Falls back to the
1582 /// plain `text` when there's no HTML or it doesn't parse.
1583 pub fn paste_rich(&self, html: Option<String>, text: String) -> DocView {
1584 let mut g = self.lock();
1585 let took = html.as_deref().is_some_and(|h| g.doc.paste_html(h));
1586 if !took {
1587 g.doc.paste(&text);
1588 }
1589 g.view()
1590 }
1591
1592 // ── formatting commands (mirror leaf-gpui's EditorCommand) ────────────────
1593
1594 pub fn toggle_bold(&self) -> DocView {
1595 let mut g = self.lock();
1596 g.doc.toggle(InlineKind::Strong);
1597 g.view()
1598 }
1599
1600 pub fn toggle_italic(&self) -> DocView {
1601 let mut g = self.lock();
1602 g.doc.toggle(InlineKind::Emph);
1603 g.view()
1604 }
1605
1606 pub fn toggle_code(&self) -> DocView {
1607 let mut g = self.lock();
1608 g.doc.toggle(InlineKind::Verbatim);
1609 g.view()
1610 }
1611
1612 pub fn toggle_mark(&self) -> DocView {
1613 let mut g = self.lock();
1614 g.doc.toggle(InlineKind::Mark);
1615 g.view()
1616 }
1617
1618 /// Whether the caret stands in a highlight — what a colour palette enables
1619 /// itself by, since a colour is a property of a highlight that already
1620 /// exists. The caret-side half of [`Capabilities::mark_color`].
1621 pub fn caret_in_mark(&self) -> bool {
1622 self.lock().doc.caret_in_mark()
1623 }
1624
1625 /// Colour the highlight at the caret, or clear its colour with `None`.
1626 ///
1627 /// Markdown only — `==🔴 text==` is its spelling and djot has none — and
1628 /// only where there is a highlight to colour: this does not make one, so a
1629 /// coloured highlight from bare text is [`LeafDoc::toggle_mark`] and then
1630 /// this, which is the order the button and its palette already sit in. Both
1631 /// refusals leave the document alone and say so in the status line.
1632 pub fn set_mark_color(&self, color: Option<MarkColor>) -> DocView {
1633 let mut g = self.lock();
1634 g.doc.set_mark_color(color.map(CoreMarkColor::from));
1635 g.view()
1636 }
1637
1638 /// One press of a colour swatch: colour the highlight at the caret, or —
1639 /// over a selection that isn't highlighted yet — highlight it and colour it,
1640 /// as **one** undo step.
1641 ///
1642 /// [`LeafDoc::set_mark_color`] is the exact gesture; this is the compound a
1643 /// toolbar presses, and it lives in core so that every frontend answers
1644 /// "what does a swatch mean over plain text" the same way. `None` clears the
1645 /// colour, and over an unhighlighted selection means simply "highlight
1646 /// this". A bare caret in no highlight is left alone.
1647 pub fn highlight(&self, color: Option<MarkColor>) -> DocView {
1648 let mut g = self.lock();
1649 g.doc.highlight(color.map(CoreMarkColor::from));
1650 g.view()
1651 }
1652
1653 pub fn toggle_underline(&self) -> DocView {
1654 let mut g = self.lock();
1655 g.doc.toggle(InlineKind::Insert);
1656 g.view()
1657 }
1658
1659 pub fn toggle_strike(&self) -> DocView {
1660 let mut g = self.lock();
1661 g.doc.toggle(InlineKind::Delete);
1662 g.view()
1663 }
1664
1665 pub fn set_paragraph(&self) -> DocView {
1666 let mut g = self.lock();
1667 g.doc.set_block(BlockKind::Paragraph);
1668 g.view()
1669 }
1670
1671 /// Toggle the current block to a heading of `level` (1–6); toggling the
1672 /// active level off returns it to a paragraph, per core.
1673 pub fn set_heading(&self, level: u32) -> DocView {
1674 let mut g = self.lock();
1675 g.doc.toggle_heading(level);
1676 g.view()
1677 }
1678
1679 pub fn toggle_blockquote(&self) -> DocView {
1680 let mut g = self.lock();
1681 g.doc.toggle_blockquote();
1682 g.view()
1683 }
1684
1685 pub fn toggle_list(&self, ordered: bool) -> DocView {
1686 let mut g = self.lock();
1687 g.doc.toggle_list(ordered);
1688 g.view()
1689 }
1690
1691 /// Tick or untick the task item at the caret. See
1692 /// [`leaf_core::Doc::toggle_task_checked`].
1693 pub fn toggle_task_checked(&self) -> DocView {
1694 let mut g = self.lock();
1695 g.doc.toggle_task_checked();
1696 g.view()
1697 }
1698
1699 /// Tick or untick the task item covering `offset` — a tap on a rendered
1700 /// checkbox, which must not drag the caret across the document to get there.
1701 pub fn toggle_task_at(&self, offset: u64) -> DocView {
1702 let mut g = self.lock();
1703 g.doc.toggle_task_at(offset as usize);
1704 g.view()
1705 }
1706
1707 /// Give the list item at the caret a checkbox, or take its checkbox away.
1708 pub fn toggle_task_item(&self) -> DocView {
1709 let mut g = self.lock();
1710 g.doc.toggle_task_item();
1711 g.view()
1712 }
1713
1714 /// Whether the item at the caret has a box and which way it faces — `None`
1715 /// for a plain list item or no item at all. Drives a toolbar's checked state.
1716 pub fn task_checked_at_caret(&self) -> Option<bool> {
1717 let mut g = self.lock();
1718 g.doc.task_checked_at_caret()
1719 }
1720
1721 /// Which of the formatting commands above this document's format can
1722 /// actually spell — one flag per control, for building the toolbar.
1723 ///
1724 /// Read once when a document opens: the answer depends only on the format,
1725 /// so it cannot change under an edit. Every command refuses on its own
1726 /// regardless — the model is the authority, not the toolbar — so a frontend
1727 /// that ignores this stays correct, it just offers buttons whose only effect
1728 /// is a line in the status bar.
1729 ///
1730 /// Don't collapse it to one flag. An HTML document takes ⌘B, ⌘I and inline
1731 /// code (its marks are a tag pair) while refusing every heading, list, quote
1732 /// and link, and Markdown refuses the underline djot spells — so a toolbar
1733 /// driven by [`Self::authorable`] alone would be wrong in both directions.
1734 pub fn capabilities(&self) -> Capabilities {
1735 self.lock().doc.capabilities().into()
1736 }
1737
1738 /// Whether this document's format offers *any* door in — `false` only for a
1739 /// wholly parse-only one (XML), where an app may as well open the file
1740 /// read-only and hide the formatting section outright. For anything finer,
1741 /// including whether to dim an individual button, use [`Self::capabilities`].
1742 pub fn authorable(&self) -> bool {
1743 self.lock().doc.authorable()
1744 }
1745
1746 // ── table editing ─────────────────────────────────────────────────────────
1747
1748 /// Whether the caret is inside a table — for enabling the table controls.
1749 /// Pair it with [`Capabilities::table`]: the caret is genuinely inside an
1750 /// HTML `<table>`, and the grid controls still cannot edit one.
1751 pub fn caret_in_table(&self) -> bool {
1752 self.lock().doc.caret_in_table()
1753 }
1754
1755 /// Insert an empty row below (`below`) or above the caret's row.
1756 pub fn table_insert_row(&self, below: bool) -> DocView {
1757 let mut g = self.lock();
1758 g.doc.table_insert_row(below);
1759 g.view()
1760 }
1761
1762 /// Delete the caret's row (not the header or the last body row).
1763 pub fn table_delete_row(&self) -> DocView {
1764 let mut g = self.lock();
1765 g.doc.table_delete_row();
1766 g.view()
1767 }
1768
1769 /// Insert an empty column right (`right`) or left of the caret's column.
1770 pub fn table_insert_column(&self, right: bool) -> DocView {
1771 let mut g = self.lock();
1772 g.doc.table_insert_column(right);
1773 g.view()
1774 }
1775
1776 /// Delete the caret's column (unless it is the only one).
1777 pub fn table_delete_column(&self) -> DocView {
1778 let mut g = self.lock();
1779 g.doc.table_delete_column();
1780 g.view()
1781 }
1782
1783 /// Set the caret's column to `alignment`.
1784 pub fn table_set_alignment(&self, alignment: TableAlignment) -> DocView {
1785 let mut g = self.lock();
1786 g.doc.table_set_alignment(alignment.into_core());
1787 g.view()
1788 }
1789
1790 /// Move the caret's row one place down (`down`) or up.
1791 pub fn table_move_row(&self, down: bool) -> DocView {
1792 let mut g = self.lock();
1793 g.doc.table_move_row(down);
1794 g.view()
1795 }
1796
1797 /// Move the caret's column one place right (`right`) or left.
1798 pub fn table_move_column(&self, right: bool) -> DocView {
1799 let mut g = self.lock();
1800 g.doc.table_move_column(right);
1801 g.view()
1802 }
1803
1804 pub fn insert_link(&self, destination: String) -> DocView {
1805 let mut g = self.lock();
1806 g.doc.insert_link(&destination);
1807 g.view()
1808 }
1809
1810 /// The destination of the link under the caret, if the caret is inside one —
1811 /// so a frontend can open it (⌘-click / "Open Link") or show it. `None` when the
1812 /// caret isn't on a link.
1813 pub fn link_destination_at_caret(&self) -> Option<String> {
1814 self.lock().doc.link_destination_at_caret()
1815 }
1816
1817 /// The destination of the link at byte offset `off` —
1818 /// [`link_destination_at_caret`](Self::link_destination_at_caret) for a place
1819 /// the caret isn't.
1820 ///
1821 /// What a frontend drawing part of the document *outside* the document asks:
1822 /// a footnote's text in a popover has link runs in it, and this is how those
1823 /// runs learn where they point, since a `Run` carries how a span looks and
1824 /// not what it means.
1825 pub fn link_destination_at(&self, off: u32) -> Option<String> {
1826 self.lock().doc.link_destination_at(off as usize)
1827 }
1828
1829 /// Where the locator `id` lands in this document — the `#v2` half of a
1830 /// `chapter.dj#v2`, resolved to the block it names. `None` when nothing here
1831 /// answers to it, which is a host's cue to open the document at its top
1832 /// rather than refuse to go.
1833 ///
1834 /// The query that gives a link finer granularity than the file. It reads an
1835 /// explicit `{#v1}`, a djot heading's minted id, or (for Markdown, which
1836 /// mints none) a heading's own words slugged — see [`leaf_core::Doc::locate`].
1837 ///
1838 /// Asked of *any* document, not only the open one: a host peeking at a
1839 /// citation builds a [`LeafDoc`] over the other file's bytes and asks this,
1840 /// which is what lets a hover show the verse instead of the filename.
1841 pub fn locate(&self, id: String) -> Option<LandingView> {
1842 self.lock().doc.locate(&id).map(LandingView::from)
1843 }
1844
1845 /// Write a footnote at the caret — the toolbar's Footnote button. Both the
1846 /// `[^1]` and the definition it needs go in as one edit (one undo takes both
1847 /// back), the label is the lowest number the document has free, and the caret
1848 /// is left **in the empty note** ready to type it. Gate the button on
1849 /// [`Capabilities::footnote`]; see [`leaf_core::Doc::insert_footnote`].
1850 pub fn insert_footnote(&self) -> DocView {
1851 let mut g = self.lock();
1852 g.doc.insert_footnote();
1853 g.view()
1854 }
1855
1856 /// The footnote reference under the caret, resolved to the note it names —
1857 /// so a frontend can show the note when a reader activates a `[1]`, instead
1858 /// of the nothing a reference click used to do. `None` when the caret isn't
1859 /// on a reference; see [`FootnoteView`] for the reference that resolved to
1860 /// no definition.
1861 pub fn footnote_at_caret(&self) -> Option<FootnoteView> {
1862 self.lock().doc.footnote_at_caret().map(FootnoteView::from)
1863 }
1864
1865 /// The footnote reference at byte offset `off`, resolved to the note it
1866 /// names — [`footnote_at_caret`](Self::footnote_at_caret) for a place the
1867 /// caret isn't.
1868 ///
1869 /// This is what a hover asks: a pointer resting on a `[1]` wants the note's
1870 /// text in a popover, and moving the caret to find out would yank the reader
1871 /// out of wherever they were typing.
1872 pub fn footnote_at(&self, off: u32) -> Option<FootnoteView> {
1873 self.lock()
1874 .doc
1875 .footnote_at(off as usize)
1876 .map(FootnoteView::from)
1877 }
1878
1879 /// The footnote definition the caret stands in, and where the reference that
1880 /// names it is — the return leg of [`footnote_at_caret`](Self::footnote_at_caret),
1881 /// so following a footnote is a round trip rather than a fall.
1882 ///
1883 /// `None` when the caret isn't in a definition, which is also how a frontend
1884 /// tells the two directions apart: the reference query answers up top, this
1885 /// one answers down in the notes, and never both at once.
1886 pub fn footnote_definition_at_caret(&self) -> Option<FootnoteDefView> {
1887 self.lock()
1888 .doc
1889 .footnote_definition_at_caret()
1890 .map(FootnoteDefView::from)
1891 }
1892
1893 pub fn undo(&self) -> DocView {
1894 let mut g = self.lock();
1895 g.doc.undo();
1896 g.view()
1897 }
1898
1899 pub fn redo(&self) -> DocView {
1900 let mut g = self.lock();
1901 g.doc.redo();
1902 g.view()
1903 }
1904
1905 /// Switch between the rendered WYSIWYG surface and the raw source.
1906 pub fn toggle_view(&self) -> DocView {
1907 let mut g = self.lock();
1908 g.doc.toggle_view();
1909 g.view()
1910 }
1911
1912 /// The current markup-exposure preference (see [`MarkupMode`]).
1913 pub fn markup_mode(&self) -> MarkupMode {
1914 MarkupMode::from_core(self.lock().doc.markup_mode())
1915 }
1916
1917 /// Set the markup-exposure preference. Returns a fresh view so a frontend
1918 /// can repaint — and under `Full` it must, because the returned view is the
1919 /// first one showing the caret's line raw. Diaryx leaves it at the `None`
1920 /// default.
1921 pub fn set_markup_mode(&self, mode: MarkupMode) -> DocView {
1922 let mut g = self.lock();
1923 g.doc.set_markup_mode(mode.into_core());
1924 g.view()
1925 }
1926
1927 /// The current soft-break flow preference (see [`LineFlow`]).
1928 pub fn line_flow(&self) -> LineFlow {
1929 LineFlow::from_core(self.lock().doc.line_flow())
1930 }
1931
1932 /// Set the soft-break flow preference. Returns a fresh view so a frontend
1933 /// can repaint: like the markup-exposure preference this one changes rendering
1934 /// immediately, laying preserved soft breaks out as their own rows.
1935 pub fn set_line_flow(&self, mode: LineFlow) -> DocView {
1936 let mut g = self.lock();
1937 g.doc.set_line_flow(mode.into_core());
1938 g.view()
1939 }
1940}
1941
1942// ── UITextInput support ──────────────────────────────────────────────────────
1943// A `UITextPosition` on the Swift side wraps a source byte offset; these are the
1944// offset↔geometry, stepping, and range-editing primitives the protocol needs.
1945// Queries never move the caret — they only read the (synced) visual map — so the
1946// system can probe positions freely while the model's selection stays put.
1947#[uniffi::export]
1948impl LeafDoc {
1949 /// The caret's source offset (the selection's moving end).
1950 pub fn caret_offset(&self) -> u32 {
1951 self.lock().doc.caret as u32
1952 }
1953
1954 /// The selection's fixed end (equals the caret when there's no selection).
1955 pub fn anchor_offset(&self) -> u32 {
1956 let g = self.lock();
1957 g.doc.anchor.unwrap_or(g.doc.caret) as u32
1958 }
1959
1960 /// The last caret stop in the document — `UITextInput.endOfDocument`.
1961 pub fn doc_end_offset(&self) -> u32 {
1962 let mut g = self.lock();
1963 g.sync();
1964 let end = g.doc.source.len();
1965 g.snap_stop(end) as u32
1966 }
1967
1968 /// Snap an arbitrary offset to the nearest valid caret stop.
1969 pub fn snap_offset(&self, off: u32) -> u32 {
1970 let mut g = self.lock();
1971 g.sync();
1972 g.snap_stop(off as usize) as u32
1973 }
1974
1975 /// Where a source offset sits on screen: its visual `(row, ch)`.
1976 pub fn pos_for_offset(&self, off: u32) -> RowCol {
1977 let mut g = self.lock();
1978 g.sync();
1979 let (row, col) = g.pos_of_offset(off as usize);
1980 let ch = col_to_utf16(&g.row_text(row), col);
1981 RowCol {
1982 row: row as u32,
1983 ch: ch as u32,
1984 }
1985 }
1986
1987 /// The rows a source range covers, inclusive — for drawing a block away
1988 /// from where it sits (a footnote peek, a link peek, a landing flash).
1989 ///
1990 /// Ask this rather than mapping `start` and `end - 1` through
1991 /// [`Self::pos_for_offset`]. That pair reads correctly and is wrong: a
1992 /// block's last byte is often *hidden* — a note or a paragraph ending in a
1993 /// link ends inside the link's destination — and `pos_for_offset` snaps a
1994 /// hidden offset forward to the next visible glyph, which for a trailing
1995 /// one is on the next block's row. A peek slicing that span drew the block
1996 /// after it too. `pos_for_offset`'s snap is right for a caret and wrong for
1997 /// a span; this is the question spans should be asking.
1998 pub fn row_range_for(&self, start: u32, end: u32) -> RowRange {
1999 let mut g = self.lock();
2000 g.sync();
2001 let (first, last) = g.row_range_for(start as usize, end as usize);
2002 RowRange {
2003 first: first as u32,
2004 last: last as u32,
2005 }
2006 }
2007
2008 /// The source offset at visual `(row, ch)` — the inverse of
2009 /// [`Self::pos_for_offset`], for hit-testing a point to a position.
2010 pub fn offset_for_pos(&self, row: u32, ch: u32) -> u32 {
2011 let mut g = self.lock();
2012 g.sync();
2013 let col = utf16_to_col(&g.row_text(row as usize), ch as usize);
2014 g.offset_of_col(row as usize, col) as u32
2015 }
2016
2017 /// Move `off` by `delta` caret stops (negative = left) — `position(from:offset:)`.
2018 pub fn step_offset(&self, off: u32, delta: i32) -> u32 {
2019 let mut g = self.lock();
2020 g.sync();
2021 let mut o = g.snap_stop(off as usize);
2022 if delta >= 0 {
2023 for _ in 0..delta {
2024 match g.stop_after(o) {
2025 Some(n) => o = n,
2026 None => break,
2027 }
2028 }
2029 } else {
2030 for _ in 0..(-delta) {
2031 match g.stop_before(o) {
2032 Some(p) => o = p,
2033 None => break,
2034 }
2035 }
2036 }
2037 o as u32
2038 }
2039
2040 /// The count of caret stops between two offsets (signed) — `offset(from:to:)`.
2041 pub fn distance_offset(&self, from: u32, to: u32) -> i32 {
2042 let mut g = self.lock();
2043 g.sync();
2044 let (from, to) = (from as usize, to as usize);
2045 let (mut a, b, sign) = if from <= to {
2046 (from, to, 1i32)
2047 } else {
2048 (to, from, -1i32)
2049 };
2050 a = g.snap_stop(a);
2051 let mut n = 0i32;
2052 while a < b {
2053 match g.stop_after(a) {
2054 Some(x) => {
2055 a = x;
2056 n += 1;
2057 }
2058 None => break,
2059 }
2060 }
2061 n * sign
2062 }
2063
2064 /// The UTF-16 index at which source offset `off` sits in the visible text —
2065 /// the string `text_in_range(0, doc_end_offset())` returns — which is the
2066 /// character space AppKit's `NSTextInputClient` and `NSAccessibility` speak.
2067 ///
2068 /// leaf's own handle is the source byte offset, and the two are not one
2069 /// scale apart: WYSIWYG hides delimiters, a block gap is spelled as one
2070 /// `\n`, and a character outside the BMP is two UTF-16 units. A frontend
2071 /// hands the system an `NSRange` converted with this and turns the ranges
2072 /// it gets back through `offset_for_utf16_index`, so Look Up, dictation, and
2073 /// VoiceOver all index the same text the frontend drew.
2074 pub fn utf16_index_for_offset(&self, off: u32) -> u32 {
2075 let mut g = self.lock();
2076 g.sync();
2077 let off = (off as usize).min(g.doc.source.len());
2078 match g.doc.view {
2079 View::Wysiwyg => g.doc.vmap.visible_utf16_len(0, off) as u32,
2080 View::Source => {
2081 let off = g.snap_stop(off);
2082 g.doc.source[..off].encode_utf16().count() as u32
2083 }
2084 }
2085 }
2086
2087 /// The inverse of `utf16_index_for_offset`: the source offset of the
2088 /// visible character at UTF-16 `index`, or the document's end stop at or
2089 /// past the end of the text. An index inside a surrogate pair resolves to
2090 /// the character that owns it, and one on the `\n` a block gap is spelled
2091 /// with to the stop at the end of the block before it. Always a caret stop.
2092 pub fn offset_for_utf16_index(&self, index: u32) -> u32 {
2093 let mut g = self.lock();
2094 g.sync();
2095 let len = g.doc.source.len();
2096 let end = g.snap_stop(len);
2097 let index = index as usize;
2098 match g.doc.view {
2099 // A block separator resolves to the gap offset, which is no stop;
2100 // snapping lands it on the row end before it, the stop a caret
2101 // standing "after the last character" already means.
2102 View::Wysiwyg => g
2103 .doc
2104 .vmap
2105 .offset_at_visible_utf16(end, index)
2106 .map_or(end, |o| g.snap_stop(o)) as u32,
2107 View::Source => {
2108 let mut seen = 0usize;
2109 for (i, ch) in g.doc.source.char_indices() {
2110 let n = ch.len_utf16();
2111 if index < seen + n {
2112 return i as u32;
2113 }
2114 seen += n;
2115 }
2116 end as u32
2117 }
2118 }
2119 }
2120
2121 /// The offset one navigable row up/down from `off`, keeping its column —
2122 /// `position(from:in: .up/.down)`. `None` at the top/bottom edge.
2123 pub fn vertical_offset(&self, off: u32, down: bool) -> Option<u32> {
2124 let mut g = self.lock();
2125 g.sync();
2126 let (row, col) = g.pos_of_offset(off as usize);
2127 let target = if down {
2128 g.nav_below(row)
2129 } else {
2130 g.nav_above(row)
2131 };
2132 target.map(|r| g.offset_of_col(r, col) as u32)
2133 }
2134
2135 /// The visible text between two offsets — `text(in:)`. In the WYSIWYG
2136 /// view this is *not* the raw source slice: a hidden inline-mark
2137 /// delimiter (`**`, `` ` ``, `_`) contributes nothing, matching what
2138 /// `distance_offset`/`step_offset` already count in this same offset
2139 /// space — while a genuine block boundary the range spans (a paragraph
2140 /// gap, a table rule, …) contributes one inserted `'\n'` that
2141 /// `distance_offset`/`step_offset` do *not* count (a block boundary costs
2142 /// caret motion zero stops there, by design — see
2143 /// `the_caret_skips_the_gap_between_two_paragraphs` in `leaf-core`'s
2144 /// `doc.rs`). So the relationship is
2145 /// `text_in_range(a, b).chars().count() >= distance_offset(a, b)`, not
2146 /// strict equality: the two agree exactly when `(a, b)` spans no block
2147 /// boundary, and `text_in_range` is never shorter, only ever as long or
2148 /// longer, when it does. That inequality is still what
2149 /// `UITextInput`'s own word/line tokenizer needs (see
2150 /// [`leaf_core::wysiwyg::VisualMap::visible_text`] for why): it only reads
2151 /// this string to find a boundary and converts the result back to a
2152 /// position via `position(from:offset:)`, which walks stops — the
2153 /// inserted character is never hit as one, it only keeps the tokenizer
2154 /// from reading two paragraphs' last/first words as a single run of
2155 /// letters. The source view has nothing hidden to begin with, so there
2156 /// this is still exactly the raw slice.
2157 pub fn text_in_range(&self, from: u32, to: u32) -> String {
2158 let mut g = self.lock();
2159 g.sync();
2160 let len = g.doc.source.len();
2161 let (mut a, mut b) = ((from as usize).min(len), (to as usize).min(len));
2162 if a > b {
2163 std::mem::swap(&mut a, &mut b);
2164 }
2165 match g.doc.view {
2166 View::Wysiwyg => g.doc.vmap.visible_text(a, b),
2167 View::Source => {
2168 let s = &g.doc.source;
2169 while a > 0 && !s.is_char_boundary(a) {
2170 a -= 1;
2171 }
2172 while b < s.len() && !s.is_char_boundary(b) {
2173 b += 1;
2174 }
2175 s[a..b].to_string()
2176 }
2177 }
2178 }
2179
2180 /// Set the selection to `[anchor, focus]` by source offsets — the setter behind
2181 /// `UITextInput.selectedTextRange` and handle dragging.
2182 pub fn set_selection_offsets(&self, anchor: u32, focus: u32) -> DocView {
2183 let mut g = self.lock();
2184 g.doc.place_caret(anchor as usize, false);
2185 if focus != anchor {
2186 g.doc.place_caret(focus as usize, true);
2187 }
2188 g.view()
2189 }
2190
2191 /// Select the exact source range `[start, end)`, snapping neither end to a
2192 /// visible caret stop — for a host painting a range it already knows the
2193 /// bytes of (a search hit, an annotation) rather than hit-testing a touch.
2194 ///
2195 /// `set_selection_offsets` above is the *other* verb: it goes through
2196 /// `place_caret`, which snaps, and is what a drag handle wants. This one
2197 /// takes the range as given, so a selection over `**needle**`'s inner word
2198 /// is the word and not one byte short of it.
2199 pub fn select_range(&self, start: u32, end: u32) -> DocView {
2200 let mut g = self.lock();
2201 g.doc.select_range(start as usize, end as usize);
2202 g.view()
2203 }
2204
2205 /// Replace the source range `[from, to]` with `text` — `replace(_:withText:)`.
2206 pub fn replace_range(&self, from: u32, to: u32, text: String) -> DocView {
2207 let mut g = self.lock();
2208 g.doc.place_caret(from as usize, false);
2209 if to != from {
2210 g.doc.place_caret(to as usize, true);
2211 }
2212 g.doc.insert(&text);
2213 g.view()
2214 }
2215}
2216
2217impl LeafDoc {
2218 /// Acquire the guard, recovering from a poisoned lock: a panic in `leaf-core`
2219 /// under one call shouldn't wedge the whole document handle for the app.
2220 fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
2221 self.inner.lock().unwrap_or_else(|p| p.into_inner())
2222 }
2223}
2224
2225/// The UTF-16 offset into `text` of display column `col`. Walks grapheme clusters
2226/// exactly as core measures columns ([`text_width`] per cluster), so a wide
2227/// cluster advances the column by its cells while the offset advances by its
2228/// UTF-16 length; the two coincide only on plain ASCII.
2229fn col_to_utf16(text: &str, col: usize) -> usize {
2230 let mut c = 0usize;
2231 let mut u = 0usize;
2232 for g in text.graphemes(true) {
2233 if c >= col {
2234 break;
2235 }
2236 c += text_width(g);
2237 u += g.chars().map(char::len_utf16).sum::<usize>();
2238 }
2239 u
2240}
2241
2242/// The display column of the grapheme boundary at or before UTF-16 offset `off`
2243/// — the inverse of [`col_to_utf16`], turning a native click position back into
2244/// core's column. Core then clamps the column to a real caret stop.
2245fn utf16_to_col(text: &str, off: usize) -> usize {
2246 let mut c = 0usize;
2247 let mut u = 0usize;
2248 for g in text.graphemes(true) {
2249 if u >= off {
2250 break;
2251 }
2252 u += g.chars().map(char::len_utf16).sum::<usize>();
2253 c += text_width(g);
2254 }
2255 c
2256}
2257
2258/// The renderer class id for a semantic role. Heading level is folded into the
2259/// id (`h1`…`h6`) so a single style rule per level applies.
2260fn role_name(r: Role) -> String {
2261 match r {
2262 Role::Body => "body".into(),
2263 Role::Heading(level) => format!("h{}", level.clamp(1, 6)),
2264 Role::Code => "code".into(),
2265 Role::Link => "link".into(),
2266 // The colour rides `Run::mark_color`, not the class id: a renderer that
2267 // styles `mark` and nothing else still draws a coloured highlight.
2268 Role::Mark(_) => "mark".into(),
2269 Role::ListMarker => "list".into(),
2270 Role::QuoteGutter => "quote".into(),
2271 Role::Rule => "rule".into(),
2272 Role::Image => "image".into(),
2273 Role::Delimiter => "delimiter".into(),
2274 }
2275}
2276
2277/// The toolbar id for an inline mark — kept in sync with the Swift button ids.
2278fn mark_id(kind: InlineKind) -> &'static str {
2279 match kind {
2280 InlineKind::Strong => "bold",
2281 InlineKind::Emph => "italic",
2282 InlineKind::Verbatim => "code",
2283 InlineKind::Mark => "mark",
2284 InlineKind::Insert => "underline",
2285 InlineKind::Delete => "strike",
2286 InlineKind::Superscript => "superscript",
2287 InlineKind::Subscript => "subscript",
2288 }
2289}
2290
2291/// The WYSIWYG rows: each visual row's glyphs coalesced into maximal runs of
2292/// identical `(style, selected)`. A glyph is selected when its source byte lies
2293/// in `[ss, se)`.
2294fn wysiwyg_rows(vmap: &VisualMap, ss: usize, se: usize, hls: &[leaf_core::Highlight]) -> Vec<Row> {
2295 vmap.rows
2296 .iter()
2297 .map(|vrow| {
2298 Row {
2299 runs: runs_of(&vrow.glyphs, ss, se, hls),
2300 decoration: vrow.decoration,
2301 code: vrow.code,
2302 code_lang: vrow.code_lang.clone(),
2303 directive: vrow.directive,
2304 directive_label: vrow.directive_label.clone(),
2305 // Straight off the row, not scanned out of its glyphs: an empty
2306 // heading has none to scan, and a renderer sizing the line by a
2307 // glyph's role drew `# ` at body height until it had text.
2308 heading: vrow.heading,
2309 boundary: vrow.boundary.map(|b| Boundary {
2310 above: b.above.into(),
2311 below: b.below.into(),
2312 }),
2313 }
2314 })
2315 .collect()
2316}
2317
2318/// Coalesce `glyphs` into maximal runs of identical `(style, selected)` — the
2319/// shared body of a row's runs and a table cell's runs. A glyph is selected when
2320/// its source byte lies in `[ss, se)`.
2321/// Split a cell's flat glyphs into its visual lines at the in-cell break glyphs
2322/// (`\n`, from a `<br>`), each with the source range it spans. A line runs from
2323/// its first glyph's offset to the break that ends it (`cell_end` for the last);
2324/// an empty line — a leading/trailing break, or an empty cell — collapses to a
2325/// single caret home. The break glyphs themselves are dropped (they hold no
2326/// caret), exactly as the monospace picture drops them.
2327fn cell_lines(
2328 glyphs: &[leaf_core::Glyph],
2329 cell_start: usize,
2330 cell_end: usize,
2331 ss: usize,
2332 se: usize,
2333 hls: &[leaf_core::Highlight],
2334) -> Vec<TableCellLineView> {
2335 let mut lines = Vec::new();
2336 let mut seg: Vec<leaf_core::Glyph> = Vec::new();
2337 // The current line's start offset: the cell's for the first line, then the
2338 // first real glyph after each break (`None` until that glyph is seen).
2339 let mut line_start: Option<usize> = Some(cell_start);
2340 for g in glyphs {
2341 if g.ch == '\n' {
2342 let start = line_start.unwrap_or(g.src);
2343 lines.push(TableCellLineView {
2344 runs: runs_of(&seg, ss, se, hls),
2345 start: start as u32,
2346 end: g.src as u32,
2347 });
2348 seg.clear();
2349 line_start = None;
2350 } else {
2351 if line_start.is_none() {
2352 line_start = Some(g.src);
2353 }
2354 seg.push(g.clone());
2355 }
2356 }
2357 lines.push(TableCellLineView {
2358 runs: runs_of(&seg, ss, se, hls),
2359 start: line_start.unwrap_or(cell_end) as u32,
2360 end: cell_end as u32,
2361 });
2362 lines
2363}
2364
2365fn runs_of(
2366 glyphs: &[leaf_core::Glyph],
2367 ss: usize,
2368 se: usize,
2369 hls: &[leaf_core::Highlight],
2370) -> Vec<Run> {
2371 // Which highlight (by index) covers a glyph — first by start when several
2372 // overlap, matching `Doc::highlight_at`. Part of the run key: a highlight
2373 // splits a run exactly the way the selection does, so its wash begins and
2374 // ends on its own bytes.
2375 let hl_of = |src: usize| hls.iter().position(|h| h.start <= src && src < h.end);
2376 let mut runs: Vec<Run> = Vec::new();
2377 let mut buf = String::new();
2378 // The style/selection/highlight key the run is accumulating, and the source
2379 // offset its first glyph came from — carried alongside rather than
2380 // re-derived, since a run's glyphs are contiguous but its *text* has no
2381 // offsets in it.
2382 let mut cur: Option<(LStyle, bool, Option<usize>, usize)> = None;
2383 for g in glyphs {
2384 let key = (g.style, g.src >= ss && g.src < se, hl_of(g.src));
2385 match cur {
2386 Some((style, sel, hl, _)) if (style, sel, hl) == key => buf.push(g.ch),
2387 _ => {
2388 if let Some((style, was_sel, hl, src)) = cur.take() {
2389 runs.push(make_run(
2390 std::mem::take(&mut buf),
2391 style,
2392 was_sel,
2393 hl.map(|i| &hls[i]),
2394 src,
2395 ));
2396 }
2397 cur = Some((key.0, key.1, key.2, g.src));
2398 buf.push(g.ch);
2399 }
2400 }
2401 }
2402 if let Some((style, was_sel, hl, src)) = cur {
2403 runs.push(make_run(buf, style, was_sel, hl.map(|i| &hls[i]), src));
2404 }
2405 runs
2406}
2407
2408/// The leaf directives of a WYSIWYG frame — each with the `rows` span its
2409/// placeholder occupies (to be painted over) and the name/attributes a frontend
2410/// resolves it by. The peer of [`wysiwyg_tables`] for a block that renders as a
2411/// thing rather than as text.
2412fn wysiwyg_directives(vmap: &VisualMap) -> Vec<DirectiveView> {
2413 vmap.directives
2414 .iter()
2415 .map(|d| DirectiveView {
2416 start_row: d.rows_span.start as u32,
2417 end_row: d.rows_span.end as u32,
2418 name: d.name.clone(),
2419 label: d.label.clone(),
2420 attrs: d
2421 .attrs
2422 .iter()
2423 .map(|(k, v)| DirectiveAttr {
2424 key: k.clone(),
2425 value: v.clone().unwrap_or_default(),
2426 })
2427 .collect(),
2428 })
2429 .collect()
2430}
2431
2432/// The block media of a WYSIWYG frame — each with the `rows` span its
2433/// placeholder occupies (to be laid over) and what to build there. The peer of
2434/// [`wysiwyg_directives`], with each URL already resolved under `scheme`.
2435///
2436/// Resolving here rather than in Swift keeps the one piece of `<picture>` logic
2437/// core owns (`prefers-color-scheme` matching) in core. The `<source>` list
2438/// still crosses untouched, so a renderer can additionally pick by MIME — which
2439/// codecs AVFoundation has is not something core can know.
2440fn wysiwyg_media(vmap: &VisualMap, scheme: ColorScheme) -> Vec<MediaView> {
2441 vmap.media
2442 .iter()
2443 .map(|m| MediaView {
2444 start_row: m.rows_span.start as u32,
2445 end_row: m.rows_span.end as u32,
2446 kind: match m.kind {
2447 CoreMediaKind::Image => MediaKind::Image,
2448 CoreMediaKind::Video => MediaKind::Video,
2449 CoreMediaKind::Audio => MediaKind::Audio,
2450 },
2451 src: m.resolve(scheme).to_string(),
2452 poster: m.poster.clone(),
2453 alt: m.alt.clone(),
2454 sources: m
2455 .sources
2456 .iter()
2457 .map(|s| MediaSourceView {
2458 media: s.media.clone(),
2459 src: s.srcset.clone(),
2460 mime: s.mime.clone(),
2461 })
2462 .collect(),
2463 })
2464 .collect()
2465}
2466
2467/// The structural tables of a WYSIWYG frame — each with the `rows` span its
2468/// box-glyph picture occupies (to be skipped) and its grid of styled cells.
2469fn wysiwyg_tables(
2470 vmap: &VisualMap,
2471 ss: usize,
2472 se: usize,
2473 hls: &[leaf_core::Highlight],
2474) -> Vec<TableView> {
2475 vmap.tables
2476 .iter()
2477 .map(|t| TableView {
2478 start_row: t.rows_span.start as u32,
2479 end_row: t.rows_span.end as u32,
2480 grid: t
2481 .grid
2482 .iter()
2483 .map(|row| TableRowView {
2484 head: row.head,
2485 cells: row
2486 .cells
2487 .iter()
2488 .map(|cell| TableCellView {
2489 lines: cell_lines(&cell.glyphs, cell.start, cell.end, ss, se, hls),
2490 align: align_name(cell.align),
2491 start: cell.start as u32,
2492 end: cell.end as u32,
2493 })
2494 .collect(),
2495 })
2496 .collect(),
2497 })
2498 .collect()
2499}
2500
2501/// The wire name for a cell's column alignment.
2502fn align_name(a: Alignment) -> String {
2503 match a {
2504 Alignment::Left => "left",
2505 Alignment::Right => "right",
2506 Alignment::Center => "center",
2507 Alignment::Default => "default",
2508 }
2509 .to_string()
2510}
2511
2512/// The source rows: the raw document split on `'\n'`, every line plain body text
2513/// with the `[ss, se)` selection carved out as its own run. Backs the source
2514/// view, whose caret rides raw byte offsets.
2515fn source_rows(source: &str, ss: usize, se: usize) -> Vec<Row> {
2516 let body = LStyle::default();
2517 let mut rows = Vec::new();
2518 let mut byte = 0usize;
2519
2520 for raw in source.split('\n') {
2521 let start = byte;
2522 let end = start + raw.len();
2523 // Selection overlap with this line, in line-local byte coordinates.
2524 let a = ss.clamp(start, end) - start;
2525 let b = se.clamp(start, end) - start;
2526
2527 // The source view's rows are split from raw text, so a run's offset is
2528 // simply where its slice starts — no glyphs to read one off.
2529 let mut runs = Vec::new();
2530 if a < b {
2531 if a > 0 {
2532 runs.push(make_run(raw[..a].to_string(), body, false, None, start));
2533 }
2534 runs.push(make_run(raw[a..b].to_string(), body, true, None, start + a));
2535 if b < raw.len() {
2536 runs.push(make_run(raw[b..].to_string(), body, false, None, start + b));
2537 }
2538 } else if !raw.is_empty() {
2539 runs.push(make_run(raw.to_string(), body, false, None, start));
2540 }
2541
2542 rows.push(Row {
2543 runs,
2544 decoration: false,
2545 code: false,
2546 code_lang: None,
2547 directive: false,
2548 directive_label: None,
2549 heading: None, // source view is raw text — no resolved heading rows
2550 boundary: None, // …and no resolved block structure to divide
2551 });
2552 byte = end + 1; // skip the '\n' that `split` consumed
2553 }
2554 rows
2555}
2556
2557/// Build a [`Run`] from an accumulated string and the core style it was drawn
2558/// with — the one place role and emphasis flags cross into the view shape.
2559fn make_run(
2560 text: String,
2561 style: LStyle,
2562 sel: bool,
2563 hl: Option<&leaf_core::Highlight>,
2564 src: usize,
2565) -> Run {
2566 Run {
2567 text,
2568 role: role_name(style.role),
2569 bold: style.bold,
2570 italic: style.italic,
2571 underline: style.underline,
2572 strike: style.strikethrough,
2573 sup: style.baseline == Baseline::Super,
2574 sub: style.baseline == Baseline::Sub,
2575 src: src as u32,
2576 sel,
2577 hl: hl.map(|h| h.id.clone()),
2578 hl_color: hl.and_then(|h| h.color.clone()),
2579 mark_color: mark_color_name(style.role),
2580 }
2581}
2582
2583/// The name of a `mark` role's colour, for [`Run::mark_color`]. `None` for a
2584/// plain highlight and for every other role — the same answer, because neither
2585/// has a colour to name.
2586fn mark_color_name(role: Role) -> Option<String> {
2587 match role {
2588 Role::Mark(c) => c.map(|c| c.name().to_string()),
2589 _ => None,
2590 }
2591}
2592
2593#[cfg(test)]
2594mod tests {
2595 use super::*;
2596
2597 fn doc(src: &str) -> Arc<LeafDoc> {
2598 LeafDoc::new(src.to_string(), "markdown".to_string()).unwrap()
2599 }
2600
2601 #[test]
2602 fn a_footnote_definition_ending_the_file_is_itself_not_a_copy() {
2603 // No trailing newline: twig closes the last block on the virtual newline
2604 // it supplies at EOF, so the block's `span.end` is one past the source.
2605 // The definition and the `section` whose bytes contain it then both
2606 // overran, both keyed the block cache as *empty*, and the definition was
2607 // served the section's rows — this rendered the heading a second time.
2608 let src = "A claim[^1] worth checking.\n\n# A heading with a reference[^1] in it\n\n[^1]: The first note.\n[^note]: A note with a word for a label.";
2609 let d = LeafDoc::new(src.to_string(), "djot".to_string()).unwrap();
2610 let text: Vec<String> = d
2611 .view()
2612 .rows
2613 .iter()
2614 .map(|r| r.runs.iter().map(|x| x.text.as_str()).collect())
2615 .collect();
2616 assert_eq!(
2617 text.last().map(String::as_str),
2618 Some("[note] A note with a word for a label."),
2619 "the last definition should render itself: {text:?}"
2620 );
2621 assert_eq!(
2622 text.iter()
2623 .filter(|t| t.contains("A heading with a reference"))
2624 .count(),
2625 1,
2626 "the heading should render exactly once: {text:?}"
2627 );
2628 }
2629
2630 #[test]
2631 fn an_empty_heading_crosses_the_boundary_carrying_its_level() {
2632 // What the toolbar's H1 leaves on a blank line: a heading with no text
2633 // yet. The renderer sizes a row by this field, so a `nil` here is a line
2634 // (and a caret) drawn at body height that jumps to heading height on the
2635 // first keystroke — the level can't be scanned out of the runs, because
2636 // an empty heading has none.
2637 let d = doc("body\n\n# \n");
2638 let v = d.view();
2639 let head = v.rows.last().expect("the heading's row");
2640 assert!(
2641 head.runs.iter().all(|r| r.text.is_empty()),
2642 "the `# ` marker is hidden"
2643 );
2644 assert_eq!(head.heading, Some(1));
2645 assert_eq!(
2646 v.rows[0].heading, None,
2647 "the paragraph above is not a heading"
2648 );
2649 }
2650
2651 #[test]
2652 fn typing_into_a_heading_made_on_a_blank_line_keeps_the_caret_on_its_row() {
2653 // The reported bug at the boundary the Swift renderer reads: with a blank
2654 // line under it, the caret came back on a row two below the heading it
2655 // was actually in, and the view drew it there.
2656 let d = doc("one\n\ntwo\n\n\n\n");
2657 let _ = d.click(4, 0, false); // the first of the two blank lines
2658 let _ = d.set_heading(1);
2659 let mut v = d.view();
2660 for c in "title".chars() {
2661 v = d.insert(c.to_string());
2662 }
2663 assert_eq!(d.source(), "one\n\ntwo\n\n# title\n\n");
2664 assert_eq!(
2665 (v.caret_row, v.caret_ch),
2666 (4, 5),
2667 "the caret is on the heading's row"
2668 );
2669 assert_eq!(v.rows[4].heading, Some(1));
2670 }
2671
2672 #[test]
2673 fn a_video_crosses_the_boundary_as_media_with_the_rows_to_lay_it_over() {
2674 // What the Swift renderer actually consumes: a row span to cover, a kind
2675 // to build a view from, and a URL to load. A frontend that skipped the
2676 // span would paint core's `🎬` placeholder underneath its own player.
2677 let d = doc("<video src=\"clip.mp4\" poster=\"still.png\" controls></video>\n");
2678 let v = d.view();
2679 assert_eq!(v.media.len(), 1);
2680 let m = &v.media[0];
2681 assert!(matches!(m.kind, MediaKind::Video));
2682 assert_eq!(m.src, "clip.mp4");
2683 assert_eq!(m.poster, "still.png");
2684 assert!(
2685 m.end_row > m.start_row,
2686 "the span must cover at least its label row"
2687 );
2688 }
2689
2690 #[test]
2691 fn a_pictures_dark_source_resolves_by_appearance() {
2692 // The one piece of `<picture>` logic core owns, exercised across the
2693 // boundary: the same document resolves to a different URL depending on
2694 // what the host said its appearance was.
2695 let d = doc(
2696 "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\
2697 <img src=\"l.svg\" alt=\"banner\"></picture>\n",
2698 );
2699 assert_eq!(d.view().media[0].src, "l.svg", "light by default");
2700 assert_eq!(d.set_dark_appearance(true).media[0].src, "d.svg");
2701 assert_eq!(d.set_dark_appearance(false).media[0].src, "l.svg");
2702 }
2703
2704 #[test]
2705 fn tapping_below_a_trailing_picture_and_typing_keeps_it_a_picture() {
2706 // The whole gesture, across the boundary, in the order the Apple frontend
2707 // performs it: the layout clamps a point below the last row onto the
2708 // picture's row and asks for the position past its label glyphs; that
2709 // offset becomes the selection; then a character arrives. Before the two
2710 // halves of this fix, the offset was the stop *in front of* the picture
2711 // and the character dissolved it into a paragraph with an inline image —
2712 // the photo stopped being drawn, and nothing said so.
2713 let d = doc("hi\n\n\n");
2714 let v = d.set_unwrapped();
2715 let row = v.media[0].start_row;
2716 let label: u32 = v.rows[row as usize]
2717 .runs
2718 .iter()
2719 .map(|r| r.text.encode_utf16().count() as u32)
2720 .sum();
2721
2722 let off = d.offset_for_pos(row, label);
2723 assert_eq!(
2724 off,
2725 "hi\n\n".len() as u32,
2726 "the stop past the picture"
2727 );
2728
2729 d.set_selection_offsets(off, off);
2730 let after = d.insert("x".to_string());
2731 assert_eq!(d.source(), "hi\n\n\n\nx\n");
2732 assert_eq!(after.media.len(), 1, "still a picture, one paragraph up");
2733 }
2734
2735 #[test]
2736 fn backspace_from_that_same_tap_takes_the_picture_whole() {
2737 // The other half of the same gesture, and the one that cost this project's
2738 // own test vault a photo: tap under the picture, press Backspace. That
2739 // offset is the stop past the markup, so a byte-step deleted the closing
2740 // paren and left the literal text `\n");
2742 d.set_unwrapped();
2743 let off = "hi\n\n".len() as u32;
2744 d.set_selection_offsets(off, off);
2745 let after = d.backspace();
2746 assert_eq!(d.source(), "hi\n");
2747 assert_eq!(after.media.len(), 0, "gone as a picture, not as bytes");
2748 let undone = d.undo();
2749 assert_eq!(d.source(), "hi\n\n\n");
2750 assert_eq!(
2751 undone.media.len(),
2752 1,
2753 "and one undo brings the picture back"
2754 );
2755 }
2756
2757 #[test]
2758 fn measured_heights_grow_the_reserved_span() {
2759 // The height loop: core reserves one row until the renderer measures the
2760 // real view and reports back, because core does no I/O and cannot know.
2761 let d = doc("\n");
2762 let before = &d.view().media[0];
2763 assert_eq!(
2764 before.end_row - before.start_row,
2765 1,
2766 "one row until measured"
2767 );
2768
2769 let after = d.set_media_rows(vec![MediaHeight {
2770 destination: "cat.png".to_string(),
2771 rows: 6,
2772 }]);
2773 let m = &after.media[0];
2774 assert_eq!(
2775 m.end_row - m.start_row,
2776 6,
2777 "the span grew to what was measured"
2778 );
2779 }
2780
2781 #[test]
2782 fn inserted_media_comes_straight_back_out_as_media() {
2783 // Round trip across the boundary, the pair that matters: what Swift asks
2784 // to insert, Swift sees on the very next frame.
2785 let d = doc("\n");
2786 let v = d.insert_media(
2787 MediaKind::Audio,
2788 "take.mp3".to_string(),
2789 "a take".to_string(),
2790 );
2791 assert_eq!(v.media.len(), 1);
2792 assert!(matches!(v.media[0].kind, MediaKind::Audio));
2793 assert_eq!(v.media[0].src, "take.mp3");
2794 assert_eq!(v.media[0].alt, "a take");
2795 }
2796
2797 #[test]
2798 fn the_source_view_publishes_no_media() {
2799 // In the source view the `<video>` markup is the literal text the caret
2800 // is editing — laying a player over it would cover what's being typed.
2801 let d = doc("<video src=\"clip.mp4\" controls></video>\n");
2802 assert_eq!(d.view().media.len(), 1);
2803 assert!(
2804 d.toggle_view().media.is_empty(),
2805 "no placeholders in the source view"
2806 );
2807 }
2808
2809 /// **A foreign caller's offset must never panic.** Every offset entering
2810 /// leaf comes from a UI toolkit that counts in its own units — UIKit hands
2811 /// back UTF-16 positions — so an offset landing mid-character is a normal
2812 /// thing to be handed, not a bug in the caller. Slicing on it aborts the
2813 /// process across the FFI boundary, where there is no unwinding to catch.
2814 ///
2815 /// Reproduces a real crash: `byte index 1236 is not a char boundary; it is
2816 /// inside '…'`.
2817 #[test]
2818 fn an_offset_inside_a_multibyte_char_does_not_panic() {
2819 let d = doc(
2820 "# April 02, 2026\n\nAn interesting thing AI said to me:\n\n> a person… who journals\n",
2821 );
2822 d.toggle_view(); // to the raw source view, where offsets index bytes directly
2823 let src = d.source();
2824 // The interior byte of the `…` — exactly the shape of the crash.
2825 let mid = src.find('…').expect("the ellipsis is in the fixture") + 1;
2826 assert!(
2827 !src.is_char_boundary(mid),
2828 "the fixture must be mid-character"
2829 );
2830
2831 // Every entry point that takes a raw source offset.
2832 let _ = d.pos_for_offset(mid as u32);
2833 let _ = d.vertical_offset(mid as u32, true);
2834 let _ = d.vertical_offset(mid as u32, false);
2835 let _ = d.snap_offset(mid as u32);
2836 let _ = d.step_offset(mid as u32, 1);
2837 let _ = d.step_offset(mid as u32, -1);
2838 let _ = d.distance_offset(0, mid as u32);
2839 let _ = d.text_in_range(0, mid as u32);
2840 let _ = d.set_selection_offsets(mid as u32, mid as u32);
2841 // And the caret must not come to rest inside the character either — a
2842 // mid-character caret is a later panic waiting for the next edit.
2843 let _ = d.replace_range(mid as u32, mid as u32, "x".to_string());
2844 assert!(
2845 d.source().is_char_boundary(d.caret_offset() as usize),
2846 "the caret must sit on a character boundary"
2847 );
2848 }
2849
2850 #[test]
2851 fn cell_lines_split_on_the_break_glyph_carrying_each_lines_source_range() {
2852 use leaf_core::Glyph;
2853 let g = |ch, src| Glyph {
2854 ch,
2855 style: LStyle::default(),
2856 src,
2857 stop: true,
2858 };
2859 // "a" at 10, a `<br>` at 11..15 (the break glyph), "b" at 15; cell 10..16.
2860 let glyphs = [g('a', 10), g('\n', 11), g('b', 15)];
2861 let lines = cell_lines(&glyphs, 10, 16, 0, 0, &[]);
2862 assert_eq!(lines.len(), 2, "one break makes two lines");
2863 assert_eq!(
2864 (lines[0].start, lines[0].end),
2865 (10, 11),
2866 "line 1 ends at the break"
2867 );
2868 assert_eq!(
2869 (lines[1].start, lines[1].end),
2870 (15, 16),
2871 "line 2 begins past it"
2872 );
2873 let text =
2874 |l: &TableCellLineView| l.runs.iter().map(|r| r.text.clone()).collect::<String>();
2875 assert_eq!(text(&lines[0]), "a");
2876 assert_eq!(text(&lines[1]), "b");
2877
2878 // A trailing break leaves an empty last line homed at the cell's end.
2879 let trailing = [g('a', 10), g('\n', 11)];
2880 let lines = cell_lines(&trailing, 10, 15, 0, 0, &[]);
2881 assert_eq!(lines.len(), 2);
2882 assert!(lines[1].runs.is_empty());
2883 assert_eq!((lines[1].start, lines[1].end), (15, 15));
2884
2885 // No break: one line spanning the whole cell.
2886 let plain = [g('P', 10), g('e', 11)];
2887 let lines = cell_lines(&plain, 10, 12, 0, 0, &[]);
2888 assert_eq!(lines.len(), 1);
2889 assert_eq!((lines[0].start, lines[0].end), (10, 12));
2890 }
2891
2892 fn row_text(v: &DocView, row: usize) -> String {
2893 v.rows[row].runs.iter().map(|r| r.text.clone()).collect()
2894 }
2895
2896 #[test]
2897 fn unwrapped_collapses_a_paragraph_to_one_row() {
2898 let d = doc("one two three four five six seven eight\n");
2899 let wrapped = d.set_width(10);
2900 let unwrapped = d.set_unwrapped();
2901 assert!(
2902 unwrapped.rows.len() < wrapped.rows.len(),
2903 "a narrow column wrap splits the paragraph; unwrapped keeps it whole"
2904 );
2905 assert!(
2906 (0..unwrapped.rows.len()).any(|i| row_text(&unwrapped, i).contains("eight")),
2907 "the whole paragraph, including its last word, sits on a single unwrapped row"
2908 );
2909 }
2910
2911 #[test]
2912 fn offsets_round_trip_when_unwrapped() {
2913 let d = doc("hello world\n");
2914 d.set_unwrapped();
2915 // offset -> (row, ch) -> offset is stable, so the pixel-wrapping frontend can
2916 // map between its visual lines and core's byte-offset caret model.
2917 let rc = d.pos_for_offset(6); // the 'w' of "world"
2918 assert_eq!(d.offset_for_pos(rc.row, rc.ch), 6);
2919 }
2920
2921 #[test]
2922 fn set_unwrapped_is_idempotent() {
2923 let d = doc("a paragraph of some length here\n");
2924 let first = d.set_unwrapped();
2925 let second = d.set_unwrapped();
2926 assert_eq!(first.rows.len(), second.rows.len());
2927 }
2928
2929 #[test]
2930 fn newline_on_last_list_item_before_a_blockquote_starts_a_new_item() {
2931 let src = "- one\n- two\n- three\n\n> quote\n";
2932 let d = doc(src);
2933 let off = (src.find("three").unwrap() + "three".len()) as u32; // end of "three" = 19
2934 d.set_selection_offsets(off, off);
2935 d.newline();
2936 let after = d.source();
2937 assert!(
2938 after.contains("- three\n- ") && after.contains("> quote"),
2939 "expected a new empty list item with the blockquote intact, got: {after:?}"
2940 );
2941 }
2942
2943 #[test]
2944 fn enter_on_an_empty_line_adds_one_newline_and_one_backspace_undoes_it() {
2945 let d = doc("hello\n");
2946 d.set_selection_offsets(5, 5);
2947 d.newline(); // paragraph "hello" → a paragraph break, caret on the empty line
2948 let after_para = d.source();
2949 let caret_para = d.caret_offset();
2950 d.newline(); // Enter on the empty line
2951 assert_eq!(
2952 d.source().len(),
2953 after_para.len() + 1,
2954 "an empty-line Enter adds a single newline, not another paragraph break"
2955 );
2956 d.backspace(); // a single Backspace restores the previous state
2957 assert_eq!(d.source(), after_para);
2958 assert_eq!(d.caret_offset(), caret_para);
2959 }
2960
2961 #[test]
2962 fn enter_in_a_nonempty_paragraph_still_opens_a_new_paragraph() {
2963 let d = doc("hello\n");
2964 d.set_selection_offsets(5, 5);
2965 let before = d.source().len();
2966 d.newline();
2967 assert_eq!(
2968 d.source().len(),
2969 before + 2,
2970 "a paragraph break is still \\n\\n"
2971 );
2972 }
2973
2974 #[test]
2975 fn link_destination_at_caret_reads_the_caret_link() {
2976 let d = doc("see [t](https://x.dev) ok\n");
2977 d.set_selection_offsets(5, 5); // caret on the link text "t"
2978 assert_eq!(
2979 d.link_destination_at_caret().as_deref(),
2980 Some("https://x.dev")
2981 );
2982 d.set_selection_offsets(0, 0); // caret on plain text
2983 assert_eq!(d.link_destination_at_caret(), None);
2984 }
2985
2986 #[test]
2987 fn the_frame_carries_the_caret_link_so_a_toolbar_can_light_and_seed_from_it() {
2988 // The reason it rides `DocView` rather than being asked for: stepping the
2989 // caret out of the link changes no other chrome fact on the frame, so a
2990 // toolbar that only redraws on a *changed* state would keep a stale light.
2991 let d = doc("see [t](https://x.dev) ok\n");
2992 d.set_selection_offsets(5, 5);
2993 let inside = d.view();
2994 assert_eq!(inside.link.as_deref(), Some("https://x.dev"));
2995 assert_eq!(inside.heading, None);
2996 assert!(inside.active.is_empty());
2997
2998 d.set_selection_offsets(0, 0);
2999 let outside = d.view();
3000 assert_eq!(outside.link, None);
3001 // Nothing else the frame reports moved with it.
3002 assert_eq!(outside.heading, inside.heading);
3003 assert_eq!(outside.active, inside.active);
3004 }
3005
3006 #[test]
3007 fn insert_footnote_crosses_and_leaves_the_caret_in_the_new_note() {
3008 // The button's round trip through the boundary: both halves written, and
3009 // a caret offset a host can type into without asking anything else.
3010 let d = doc("A claim and more.\n");
3011 d.set_selection_offsets(7, 7); // just past "A claim"
3012 d.insert_footnote();
3013 assert!(
3014 d.source().starts_with("A claim[^1] and more."),
3015 "{:?}",
3016 d.source()
3017 );
3018 assert!(d.source().contains("[^1]:"), "{:?}", d.source());
3019
3020 let note = d.footnote_at(9).expect("the reference just written");
3021 assert_eq!(note.label, "1");
3022 assert_eq!(
3023 d.caret_offset(),
3024 note.offset.expect("an empty note is still a place")
3025 );
3026 // …and the way back out is the same one a reader uses.
3027 assert_eq!(
3028 d.footnote_definition_at_caret().expect("in the note").label,
3029 "1"
3030 );
3031 }
3032
3033 #[test]
3034 fn a_highlight_is_coloured_at_the_caret_and_the_frame_says_which() {
3035 // The whole crossing a colour palette makes: press the swatch, and the
3036 // frame that comes back names the colour so the swatch can light.
3037 let d = doc("a word b\n");
3038 d.set_selection_offsets(2, 6);
3039 d.toggle_mark();
3040 assert_eq!(d.source(), "a ==word== b\n");
3041
3042 d.set_selection_offsets(5, 5); // inside the highlight
3043 assert!(d.caret_in_mark());
3044 let v = d.set_mark_color(Some(MarkColor::Red));
3045 assert_eq!(d.source(), "a ==🔴 word== b\n");
3046 assert_eq!(v.mark_color, Some(MarkColor::Red));
3047
3048 // And the way back: no colour, still a highlight.
3049 let v = d.set_mark_color(None);
3050 assert_eq!(d.source(), "a ==word== b\n");
3051 assert_eq!(v.mark_color, None);
3052 assert!(d.caret_in_mark());
3053 }
3054
3055 #[test]
3056 fn one_press_highlights_and_colours_and_one_undo_takes_it_back() {
3057 // What a toolbar swatch calls. The fold is core's, and it is what makes
3058 // the press reversible in one step rather than leaving an uncoloured
3059 // highlight behind.
3060 let d = doc("a word b\n");
3061 d.set_selection_offsets(2, 6);
3062 let v = d.highlight(Some(MarkColor::Purple));
3063 assert_eq!(d.source(), "a ==\u{1F7E3} word== b\n");
3064 assert_eq!(v.mark_color, Some(MarkColor::Purple));
3065
3066 d.undo();
3067 assert_eq!(d.source(), "a word b\n");
3068 }
3069
3070 #[test]
3071 fn the_palette_has_two_gates_and_they_ask_different_questions() {
3072 // `mark_color` is the format's answer and `caret_in_mark` the caret's.
3073 // A djot document spells the highlight and no colour for it, so the two
3074 // disagree there — which is the case a toolbar gating on either one
3075 // alone gets wrong.
3076 assert!(doc("x\n").capabilities().mark_color);
3077 let dj = LeafDoc::new("a {=word=} b\n".to_string(), "djot".to_string()).unwrap();
3078 assert!(dj.capabilities().mark, "djot writes the highlight");
3079 assert!(!dj.capabilities().mark_color, "and no colour on it");
3080 dj.set_selection_offsets(5, 5);
3081 assert!(dj.caret_in_mark(), "the caret is in one all the same");
3082
3083 let d = doc("a word b\n");
3084 d.set_selection_offsets(3, 3);
3085 assert!(!d.caret_in_mark(), "no highlight to colour here");
3086 assert_eq!(d.set_mark_color(Some(MarkColor::Blue)).mark_color, None);
3087 assert_eq!(d.source(), "a word b\n", "and nothing written");
3088 }
3089
3090 #[test]
3091 fn capabilities_answer_for_footnotes_the_way_the_format_does() {
3092 assert!(
3093 doc("x\n").capabilities().footnote,
3094 "markdown spells the pair"
3095 );
3096 let html = LeafDoc::new("<p>x</p>\n".to_string(), "html".to_string()).unwrap();
3097 assert!(
3098 !html.capabilities().footnote,
3099 "html has no footnote of its own"
3100 );
3101 }
3102
3103 #[test]
3104 fn footnote_at_caret_crosses_with_its_note_and_its_offset() {
3105 let d = doc("A claim[^1] and more.\n\n[^1]: the note\n");
3106 d.set_selection_offsets(9, 9); // caret on the reference's label
3107 let f = d
3108 .footnote_at_caret()
3109 .expect("the caret stands in a reference");
3110 assert_eq!(f.label, "1");
3111 assert_eq!(f.text.as_deref(), Some("the note"));
3112 // The note's first word — a byte the caret can actually rest on. The
3113 // definition's `[^1]:` marker is decoration with no stop of its own.
3114 assert_eq!(f.offset, Some(29));
3115 assert_eq!(f.end, Some(37));
3116
3117 d.set_selection_offsets(0, 0); // caret on plain text
3118 assert!(d.footnote_at_caret().is_none());
3119 }
3120
3121 #[test]
3122 fn footnote_at_crosses_for_an_offset_without_moving_the_caret() {
3123 // What a hover needs: the note under the pointer, and the caret left
3124 // exactly where the reader put it.
3125 let d = doc("A claim[^1] and more.\n\n[^1]: the note\n");
3126 d.set_selection_offsets(0, 0);
3127 let f = d.footnote_at(9).expect("offset 9 stands in the reference");
3128 assert_eq!(f.label, "1");
3129 assert_eq!(f.text.as_deref(), Some("the note"));
3130 assert_eq!(d.caret_offset(), 0, "asking must not move the caret");
3131 assert!(d.footnote_at(2).is_none(), "offset 2 is prose");
3132 }
3133
3134 #[test]
3135 fn footnote_definition_at_caret_crosses_with_the_way_back() {
3136 let d = doc("A claim[^1] and more.\n\n[^1]: the note\n");
3137 d.set_selection_offsets(30, 30); // caret inside the note's body
3138 let f = d
3139 .footnote_definition_at_caret()
3140 .expect("the caret stands in a definition");
3141 assert_eq!(f.label, "1");
3142 assert_eq!(f.offset, Some(9), "the reference's label");
3143
3144 // Disjoint from the reference query, which is what lets one gesture mean
3145 // "down" up top and "back up" down here.
3146 d.set_selection_offsets(9, 9);
3147 assert!(d.footnote_definition_at_caret().is_none());
3148 assert!(d.footnote_at_caret().is_some());
3149 }
3150
3151 /// The contract a peek is built on: a note's offsets map to rows whose runs
3152 /// are the note *rendered* — emphasis as an italic run, `` `code` `` as a
3153 /// code run, a link as a link run — so a frontend draws it the way the
3154 /// document draws it instead of showing the reader raw asterisks.
3155 #[test]
3156 fn a_notes_offsets_map_to_its_rendered_rows() {
3157 let src = "Claim[^a].\n\n[^a]: see *emphasis* and `code` and [a link](https://x.dev).\n";
3158 let d = doc(src);
3159 let view = d.set_unwrapped();
3160 d.set_selection_offsets(6, 6); // the reference's label
3161
3162 let f = d.footnote_at_caret().expect("a reference");
3163 let start = d.pos_for_offset(f.offset.expect("a note"));
3164 let end = d.pos_for_offset(f.end.expect("a note") - 1);
3165 assert_eq!(
3166 start.row, end.row,
3167 "a one-paragraph note is one unwrapped row"
3168 );
3169
3170 let row = &view.rows[start.row as usize];
3171 let runs: Vec<(&str, &str, bool)> = row
3172 .runs
3173 .iter()
3174 .map(|r| (r.role.as_str(), r.text.as_str(), r.italic))
3175 .collect();
3176 assert!(runs.contains(&("body", "emphasis", true)), "got {runs:?}");
3177 assert!(
3178 runs.iter()
3179 .any(|(role, text, _)| *role == "code" && *text == "code"),
3180 "got {runs:?}"
3181 );
3182 assert!(
3183 runs.iter()
3184 .any(|(role, text, _)| *role == "link" && *text == "a link"),
3185 "got {runs:?}"
3186 );
3187
3188 // The rendered row carries no markup characters at all — which is the
3189 // whole point, and what `text` (source bytes) deliberately still does.
3190 let rendered: String = row.runs.iter().map(|r| r.text.as_str()).collect();
3191 assert!(
3192 !rendered.contains('*') && !rendered.contains('`'),
3193 "got {rendered:?}"
3194 );
3195 assert!(
3196 f.text.as_deref().unwrap().contains('*'),
3197 "the source answer keeps them"
3198 );
3199
3200 // `ch` is where the body starts within the row — past the `[a] ` marker,
3201 // so a frontend that wants the note without its label can slice there.
3202 assert_eq!(row.runs[0].role, "list");
3203 assert_eq!(start.ch as usize, row.runs[0].text.chars().count());
3204
3205 // And each run says where it came from, which is how a link run drawn in
3206 // a popover learns where it points. `Run` otherwise says how a span
3207 // looks, never what it means.
3208 let link = row
3209 .runs
3210 .iter()
3211 .find(|r| r.role == "link")
3212 .expect("a link run");
3213 assert_eq!(
3214 d.link_destination_at(link.src).as_deref(),
3215 Some("https://x.dev"),
3216 "the run at {} is the link",
3217 link.src
3218 );
3219 }
3220
3221 /// The peek bug, in the shape it was actually found in: three notes, each
3222 /// ending in a link, which is what a real citation block looks like.
3223 ///
3224 /// `a_notes_offsets_map_to_its_rendered_rows` above uses a note ending in a
3225 /// visible `.`, so its last byte has a row of its own and `end - 1` reads
3226 /// right. Take the full stop away — end the note *with* the link, as a
3227 /// citation does — and the last byte falls inside the hidden destination,
3228 /// where `pos_for_offset` snaps forward onto the next note's row. Hovering
3229 /// `[^2]` peeked notes 2 *and* 3.
3230 #[test]
3231 fn a_note_ending_in_a_link_covers_its_own_row_and_no_other() {
3232 let src = "A[^1] B[^2] C[^3].\n\n\
3233 [^1]: https://en.wikipedia.org/wiki/Moravec%27s_paradox\n\n\
3234 [^2]: [\"How to Get Startup Ideas,\" Nov 2012](https://www.paulgraham.com/startupideas.html)\n\n\
3235 [^3]: [Alma 37:46](https://www.churchofjesuschrist.org/study/scriptures/bofm/alma/37?lang=eng&id=p46#p46)\n";
3236 let d = doc(src);
3237 let view = d.set_unwrapped();
3238
3239 // The caret in the [^2] reference, exactly as a hover resolves it.
3240 let off2 = src.find("[^2] C").unwrap() as u32 + 2;
3241 d.set_selection_offsets(off2, off2);
3242 let f = d.footnote_at_caret().expect("a reference");
3243 let (start, end) = (f.offset.expect("a note"), f.end.expect("a note"));
3244
3245 let span = d.row_range_for(start, end);
3246 assert_eq!(span.first, span.last, "one note is one unwrapped row");
3247
3248 // And what it draws is note 2 alone — the assertion the popover failed.
3249 let drawn: String = view.rows[span.first as usize]
3250 .runs
3251 .iter()
3252 .map(|r| r.text.as_str())
3253 .collect();
3254 assert!(drawn.contains("How to Get Startup Ideas"), "got {drawn:?}");
3255 assert!(
3256 !drawn.contains("Alma"),
3257 "note 3 leaked into the peek: {drawn:?}"
3258 );
3259
3260 // The old arithmetic, pinned as still wrong so nobody quietly restores
3261 // it: this is the failure `row_range_for` exists instead of.
3262 assert_ne!(
3263 d.pos_for_offset(end - 1).row,
3264 span.last,
3265 "the forward snap still leaves the note's row — that is the point",
3266 );
3267
3268 // Note 1 is a bare autolink, whose visible text *is* its URL, so it was
3269 // never affected and must not change.
3270 let off1 = src.find("[^1] B").unwrap() as u32 + 2;
3271 d.set_selection_offsets(off1, off1);
3272 let f1 = d.footnote_at_caret().expect("a reference");
3273 let one = d.row_range_for(f1.offset.unwrap(), f1.end.unwrap());
3274 assert_eq!(one.first, one.last);
3275 assert_ne!(one.first, span.first, "and it is a different note");
3276 }
3277
3278 /// A run's `src` is a byte offset core handed over, not something a frontend
3279 /// counted its way to — so multi-byte prose ahead of a link inside a note
3280 /// can't slide it.
3281 ///
3282 /// The offset is a *byte* offset while the run's text is characters and the
3283 /// row's columns are display cells; `src` is the only one of the three a
3284 /// frontend can use without converting between the other two.
3285 #[test]
3286 fn a_runs_source_offset_survives_multibyte_prose_ahead_of_it() {
3287 let src = "Claim[^a].\n\n[^a]: 日記 café [a link](https://x.dev).\n";
3288 let d = doc(src);
3289 let view = d.set_unwrapped();
3290 d.set_selection_offsets(6, 6);
3291
3292 let f = d.footnote_at_caret().expect("a reference");
3293 let start = d.pos_for_offset(f.offset.expect("a note"));
3294 let row = &view.rows[start.row as usize];
3295 let link = row
3296 .runs
3297 .iter()
3298 .find(|r| r.role == "link")
3299 .expect("a link run");
3300
3301 assert_eq!(
3302 d.link_destination_at(link.src).as_deref(),
3303 Some("https://x.dev")
3304 );
3305 assert_eq!(
3306 &src[link.src as usize..][.."a link".len()],
3307 "a link",
3308 "and it is a byte offset, not a character or column index"
3309 );
3310 // Which the character count is not: `日記 café ` is 9 characters and 13
3311 // bytes, so anything derived from the run text lands in the wrong place.
3312 let counted: usize = row
3313 .runs
3314 .iter()
3315 .take_while(|r| r.role != "link")
3316 .map(|r| r.text.chars().count())
3317 .sum();
3318 assert_ne!(counted, link.src as usize);
3319 }
3320
3321 /// The round trip through the API a frontend actually calls — which places
3322 /// carets, and so snaps them to real stops. Offsets that named the `[^`
3323 /// markers passed every test that assigned the caret directly and still
3324 /// dumped the reader in the paragraph above the note.
3325 #[test]
3326 fn following_a_footnote_and_coming_back_lands_on_real_caret_stops() {
3327 let d = doc("A claim[^1] and more.\n\n[^1]: the note\n");
3328 d.set_selection_offsets(9, 9);
3329
3330 let down = d
3331 .footnote_at_caret()
3332 .expect("a reference")
3333 .offset
3334 .expect("a note");
3335 d.set_selection_offsets(down, down);
3336 assert_eq!(
3337 d.caret_offset(),
3338 down,
3339 "the note is somewhere the caret fits"
3340 );
3341
3342 let up = d
3343 .footnote_definition_at_caret()
3344 .expect("arrived inside the definition")
3345 .offset
3346 .expect("a reference to return to");
3347 d.set_selection_offsets(up, up);
3348 assert_eq!(d.caret_offset(), up, "and so is the reference");
3349 assert_eq!(
3350 d.footnote_at_caret().expect("back on the reference").label,
3351 "1"
3352 );
3353 }
3354
3355 #[test]
3356 fn a_footnote_reference_crosses_the_ffi_raised() {
3357 // The whole point of the `sup` flag: without it a reference reaches
3358 // Swift as a run indistinguishable from a hyperlink's, which is why it
3359 // used to draw at body size.
3360 let d = doc("A claim[^1] and more.\n");
3361 let view = d.view();
3362 let runs: Vec<&Run> = view.rows.iter().flat_map(|r| &r.runs).collect();
3363 let chip = runs
3364 .iter()
3365 .find(|r| r.text.contains('1'))
3366 .expect("the reference's chip");
3367 assert!(chip.sup, "the reference should cross raised");
3368 assert!(!chip.sub);
3369 assert_eq!(
3370 chip.role, "link",
3371 "and still carrying the role every frontend paints"
3372 );
3373 // The prose it interrupts is a run of its own, on the normal baseline —
3374 // which is what proves the flag splits runs rather than bleeding.
3375 let prose = runs
3376 .iter()
3377 .find(|r| r.text.contains("claim"))
3378 .expect("the prose");
3379 assert!(!prose.sup && !prose.sub);
3380 }
3381
3382 #[test]
3383 fn utf16_indices_round_trip_through_the_visible_text_in_both_views() {
3384 // Hidden delimiters, an emoji outside the BMP, and a block gap: the
3385 // three ways an `NSRange` into the visible text and a source byte
3386 // offset part company.
3387 let d = doc("a **b\u{1F600}** c\n\nd\n");
3388 let end = d.doc_end_offset();
3389 let text = d.text_in_range(0, end);
3390 assert_eq!(text, "a b\u{1F600} c\nd");
3391 let total = text.encode_utf16().count() as u32;
3392 assert_eq!(d.utf16_index_for_offset(end), total);
3393 assert_eq!(d.offset_for_utf16_index(total), end);
3394 // Walk every stop: index it, and come back to the same stop.
3395 let mut off = 0u32;
3396 loop {
3397 let idx = d.utf16_index_for_offset(off);
3398 assert_eq!(
3399 d.offset_for_utf16_index(idx),
3400 off,
3401 "stop {off} via index {idx}"
3402 );
3403 let next = d.step_offset(off, 1);
3404 if next == off {
3405 break;
3406 }
3407 off = next;
3408 }
3409 // The 'c' comes after the hidden `**` and the two-unit emoji.
3410 let c = "a **b\u{1F600}** c".find(" c").unwrap() as u32 + 1;
3411 assert_eq!(
3412 d.utf16_index_for_offset(c),
3413 "a b\u{1F600} ".encode_utf16().count() as u32
3414 );
3415
3416 // Source view: the text is the raw source, so the index is the plain
3417 // UTF-16 count of the bytes before the offset — delimiters included.
3418 d.toggle_view();
3419 assert_eq!(
3420 d.text_in_range(0, d.doc_end_offset()),
3421 "a **b\u{1F600}** c\n\nd\n"
3422 );
3423 assert_eq!(
3424 d.utf16_index_for_offset(c),
3425 "a **b\u{1F600}** ".encode_utf16().count() as u32
3426 );
3427 assert_eq!(d.offset_for_utf16_index(d.utf16_index_for_offset(c)), c);
3428 // Inside the emoji's surrogate pair resolves to the emoji itself.
3429 let emoji = "a **b".len() as u32;
3430 assert_eq!(
3431 d.offset_for_utf16_index(d.utf16_index_for_offset(emoji) + 1),
3432 emoji
3433 );
3434 }
3435
3436 #[test]
3437 fn text_in_range_hides_delimiters_like_the_screen_does() {
3438 // "a **bold** c\n": 0:'a' 1:' ' 2:'*' 3:'*' 4:'b' 5:'o' 6:'l' 7:'d'
3439 // 8:'*' 9:'*' 10:' ' 11:'c' 12:'\n'. Bytes 8..10 are the closing `**`
3440 // — hidden, no glyph — and bytes 2..4 the opening `**`, likewise
3441 // hidden. `caret_steps_over_hidden_delimiters` in leaf-core already
3442 // pins that one Right from 7 (just past the 'd') lands on 10 (the
3443 // space before 'c'), skipping 8/9 entirely — so the *visible* text
3444 // transiting [7, 10) is exactly "d": the closing `**` contributes
3445 // nothing, matching what's drawn on screen.
3446 let d = doc("a **bold** c\n");
3447 assert_eq!(d.text_in_range(7, 10), "d");
3448 assert_eq!(
3449 d.text_in_range(7, 10).chars().count() as i32,
3450 d.distance_offset(7, 10),
3451 "text(in:).count() must equal offset(from:to:) — the UITextInput invariant this bug broke"
3452 );
3453
3454 // Plain text with no hidden delimiter in range: unchanged, still the
3455 // raw slice, proving the fix doesn't regress the common case.
3456 assert_eq!(d.text_in_range(0, 1), "a");
3457 assert_eq!(d.text_in_range(11, 12), "c");
3458 assert_eq!(
3459 d.text_in_range(0, 1).chars().count() as i32,
3460 d.distance_offset(0, 1)
3461 );
3462 }
3463
3464 #[test]
3465 fn text_in_range_matches_distance_offset_across_marked_up_and_plain_spans() {
3466 // The general invariant, straddling bold/italic/code spans and not:
3467 // for any pair of offsets, the visible text `text_in_range` returns
3468 // must have exactly as many `chars()` as `distance_offset` reports
3469 // stops between them — otherwise iOS's word tokenizer (which fetches
3470 // a text window, finds a boundary by indexing into *that string*, and
3471 // converts the index back to a position via `position(from:offset:)`)
3472 // resolves the boundary at the wrong offset.
3473 let d = doc("a **bold** _em_ and `code` here\n");
3474 let len = d.source().len() as u32;
3475 let mut pairs = Vec::new();
3476 let mut a = 0u32;
3477 while a < len {
3478 let mut b = a + 1;
3479 while b <= len {
3480 pairs.push((a, b));
3481 b += 3; // sample rather than an O(n^2) sweep
3482 }
3483 a += 1;
3484 }
3485 for (a, b) in pairs {
3486 let text = d.text_in_range(a, b);
3487 let dist = d.distance_offset(a, b).abs();
3488 assert_eq!(
3489 text.chars().count() as i32,
3490 dist,
3491 "text_in_range({a}, {b}) = {text:?} has {} chars, but distance_offset says {dist}",
3492 text.chars().count()
3493 );
3494 }
3495 }
3496
3497 #[test]
3498 fn text_in_range_separates_paragraphs_so_words_dont_merge_across_the_gap() {
3499 // Regression: double-tapping the last word on a line immediately
3500 // followed by a paragraph break selected past the break into the
3501 // next paragraph — and kept compounding across further trivial
3502 // paragraphs in a row — because `text_in_range` returned the two
3503 // paragraphs' text with nothing between them: "hello" then "hello"
3504 // read back as one merged "hellohello" run of letters, no different
3505 // from the raw source concatenation, and iOS's word tokenizer duly
3506 // selected the whole run as a single word.
3507 let d = doc("hello\n\nhello\n\nhello\n");
3508 let src = d.source();
3509 assert_eq!(
3510 src.find("hello").unwrap(),
3511 0,
3512 "paragraph 1 at the very start"
3513 );
3514 let p2 = src[5..].find("hello").unwrap() + 5; // 7: paragraph 2's "hello"
3515
3516 // A window straddling the tail of paragraph 1 ("lo") and the head of
3517 // paragraph 2 ("he").
3518 let text = d.text_in_range(3, p2 as u32 + 2);
3519 assert_ne!(
3520 text, "lohe",
3521 "the two paragraphs' words must not read as merged"
3522 );
3523 assert!(
3524 text.chars().any(|c| !c.is_alphanumeric()),
3525 "a non-letter must separate the two paragraphs' words: got {text:?}"
3526 );
3527 assert_eq!(
3528 text, "lo\nhe",
3529 "exactly one separator opens the second paragraph's head"
3530 );
3531
3532 // A window that is nothing but the bare gap itself (no glyph on the
3533 // left, since it starts exactly at the end of paragraph 1's own last
3534 // row) must still carry the break — this is the case a naive
3535 // "insert a separator only between two real hits" fix undercounts,
3536 // since there is no earlier hit to anchor it to.
3537 let gap_only = d.text_in_range(5, p2 as u32);
3538 assert!(
3539 gap_only.chars().count() as i32 >= d.distance_offset(5, p2 as u32),
3540 "text_in_range must never be shorter than distance_offset: {gap_only:?}"
3541 );
3542
3543 // The invariant the two existing tests above assert (strict
3544 // equality) no longer holds once the range spans a paragraph
3545 // boundary — see `text_in_range`'s doc comment — but it must never
3546 // *undercount* relative to `distance_offset`, which is what would let
3547 // a tokenizer's `position(from:offset:)` walk past where the text it
3548 // was handed actually put a boundary.
3549 for (a, b) in [(0u32, src.len() as u32), (3, p2 as u32 + 2), (5, p2 as u32)] {
3550 let text = d.text_in_range(a, b);
3551 let dist = d.distance_offset(a, b);
3552 assert!(
3553 text.chars().count() as i32 >= dist,
3554 "text_in_range({a}, {b}) = {text:?} ({} chars) is shorter than distance_offset {dist}",
3555 text.chars().count()
3556 );
3557 }
3558
3559 // Caret motion itself is untouched by any of this: from the very end
3560 // of paragraph 1's row, a paragraph gap still costs exactly one
3561 // Right press to reach the start of paragraph 2 — matching
3562 // leaf-core's `the_caret_skips_the_gap_between_two_paragraphs`.
3563 assert_eq!(
3564 d.distance_offset(5, p2 as u32),
3565 1,
3566 "one Right crosses the whole gap"
3567 );
3568 }
3569
3570 #[test]
3571 fn a_coloured_highlight_rides_out_as_a_name_beside_the_mark_role() {
3572 // The host draws the wash, so the colour has to reach it. It rides
3573 // `mark_color` rather than folding into `role` (`"mark-red"`) on
3574 // purpose: a renderer that only knows `"mark"` — every version of the
3575 // Swift one before this field existed — still draws the highlight.
3576 let d = doc("a ==\u{1F534} red== and ==plain== b\n");
3577 let runs = &d.view().rows[0].runs;
3578 let marks: Vec<(&str, Option<&str>)> = runs
3579 .iter()
3580 .filter(|r| r.role == "mark")
3581 .map(|r| (r.text.as_str(), r.mark_color.as_deref()))
3582 .collect();
3583 assert_eq!(marks, [("red", Some("red")), ("plain", None)]);
3584 assert!(
3585 runs.iter()
3586 .all(|r| r.role == "mark" || r.mark_color.is_none()),
3587 "nothing but a mark names a colour"
3588 );
3589 }
3590
3591 #[test]
3592 fn a_highlight_splits_runs_on_its_own_bytes_and_carries_its_id() {
3593 let d = doc("one two three\n");
3594 let view = d.set_highlights(vec![Highlight {
3595 start: 4,
3596 end: 7,
3597 id: "remark-1".into(),
3598 color: Some("#ffe066".into()),
3599 marker: Some("text.bubble".into()),
3600 }]);
3601 let row = &view.rows[0];
3602 let texts: Vec<(&str, Option<&str>)> = row
3603 .runs
3604 .iter()
3605 .map(|r| (r.text.as_str(), r.hl.as_deref()))
3606 .collect();
3607 assert_eq!(
3608 texts,
3609 [("one ", None), ("two", Some("remark-1")), (" three", None)],
3610 "the wash begins and ends exactly on the highlight's bytes"
3611 );
3612 assert_eq!(row.runs[1].hl_color.as_deref(), Some("#ffe066"));
3613 assert_eq!(d.highlight_at(5).as_deref(), Some("remark-1"));
3614 assert_eq!(
3615 d.highlights()
3616 .first()
3617 .and_then(|h| h.marker.clone())
3618 .as_deref(),
3619 Some("text.bubble"),
3620 "the marker rides back out for the frontend's margin pass"
3621 );
3622 assert_eq!(d.highlight_at(7), None, "end is exclusive");
3623 // A replace with nothing clears the wash.
3624 let view = d.set_highlights(Vec::new());
3625 assert!(view.rows[0].runs.iter().all(|r| r.hl.is_none()));
3626 }
3627}