text-typeset 1.3.0

Turns rich text documents into GPU-ready glyph quads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
use crate::layout::flow::{FlowItem, FlowLayout};
use crate::types::{HitRegion, HitTestResult};

/// Map a screen-space point to a document position.
///
/// The coordinates are relative to the widget's top-left corner,
/// with scroll already accounted for (the caller passes screen coords,
/// and this function adds `scroll_offset` to convert to document space).
pub fn hit_test(flow: &FlowLayout, scroll_offset: f32, x: f32, y: f32) -> Option<HitTestResult> {
    let doc_y = y + scroll_offset;

    // Try frames first (clicks inside frame content areas take priority)
    if let Some(result) = hit_test_in_frame(flow, doc_y, x) {
        return Some(result);
    }

    // Try tables
    if let Some(result) = hit_test_in_table(flow, doc_y, x) {
        return Some(result);
    }

    // Fall back to top-level blocks
    let (block_id, block) = find_block_at_y(flow, doc_y)?;
    hit_test_block(block_id, block, doc_y, x, 0.0, 0.0)
}

/// Get the screen-space caret rectangle at a document position.
pub fn caret_rect(flow: &FlowLayout, scroll_offset: f32, position: usize) -> [f32; 4] {
    // Search frames first (matching hit_test priority so that after incremental
    // relayout of a frame block, overlapping stale positions in subsequent
    // top-level blocks don't steal the caret).
    for frame in flow.frames.values() {
        if let Some(rect) = caret_rect_in_frame(frame, position, scroll_offset, 0.0, 0.0) {
            return rect;
        }
    }

    // Search table cell blocks (before top-level blocks, matching hit_test priority
    // so that table cell positions are not stolen by an overlapping top-level block).
    for table in flow.tables.values() {
        for cell in &table.cell_layouts {
            if cell.row >= table.row_ys.len() || cell.column >= table.column_xs.len() {
                continue;
            }
            let offset_x = table.column_xs[cell.column];
            let offset_y = table.y + table.row_ys[cell.row];
            for block in &cell.blocks {
                if let Some(rect) =
                    caret_rect_in_block(block, position, scroll_offset, offset_x, offset_y)
                {
                    return rect;
                }
            }
        }
    }

    // Search top-level blocks
    for item in &flow.flow_order {
        let bid = match item {
            FlowItem::Block { block_id, .. } => *block_id,
            _ => continue,
        };
        let block = match flow.blocks.get(&bid) {
            Some(b) => b,
            None => continue,
        };

        if let Some(rect) = caret_rect_in_block(block, position, scroll_offset, 0.0, 0.0) {
            return rect;
        }
    }

    // Fallback: top-left
    [0.0, -scroll_offset, 2.0, 16.0]
}

// ── Internal helpers ────────────────────────────────────────────

use crate::layout::block::BlockLayout;
use crate::layout::line::LayoutLine;

/// Hit-test a single block, with optional coordinate offsets for frame-nested blocks.
fn hit_test_block(
    block_id: usize,
    block: &BlockLayout,
    doc_y: f32,
    x: f32,
    offset_x: f32,
    offset_y: f32,
) -> Option<HitTestResult> {
    let content_top = offset_y + block.y;
    let local_x = x - offset_x;

    // Check if x is in the left margin
    if local_x < block.left_margin {
        return Some(HitTestResult {
            position: block.position,
            block_id,
            offset_in_block: 0,
            region: HitRegion::LeftMargin,
            tooltip: None,
            table_id: None,
        });
    }

    // Find which line within the block
    let local_y = doc_y - content_top;
    let line = match find_line_at_y(&block.lines, local_y) {
        Some(l) => l,
        None => {
            // Above all lines: return start of first line
            if let Some(first_line) = block.lines.first()
                && local_y < first_line.y - first_line.ascent
            {
                return Some(HitTestResult {
                    position: block.position + first_line.char_range.start,
                    block_id,
                    offset_in_block: first_line.char_range.start,
                    region: HitRegion::BelowContent,
                    tooltip: None,
                    table_id: None,
                });
            }
            // Below all lines: return end of last line
            if let Some(last_line) = block.lines.last() {
                return Some(HitTestResult {
                    position: block.position + last_line.char_range.end,
                    block_id,
                    offset_in_block: last_line.char_range.end,
                    region: HitRegion::BelowContent,
                    tooltip: None,
                    table_id: None,
                });
            }
            return Some(HitTestResult {
                position: block.position,
                block_id,
                offset_in_block: 0,
                region: HitRegion::BelowContent,
                tooltip: None,
                table_id: None,
            });
        }
    };

    // Find which glyph within the line
    let glyph_x = local_x - block.left_margin;
    let (offset_in_block, region, tooltip) = find_position_in_line(line, glyph_x);

    Some(HitTestResult {
        position: block.position + offset_in_block,
        block_id,
        offset_in_block,
        region,
        tooltip,
        table_id: None,
    })
}

/// Try to hit-test within frame blocks and tables inside frames.
fn hit_test_in_frame(flow: &FlowLayout, doc_y: f32, x: f32) -> Option<HitTestResult> {
    for item in &flow.flow_order {
        let frame_id = match item {
            FlowItem::Frame {
                frame_id,
                y,
                height,
            } if doc_y >= *y && doc_y < *y + *height => *frame_id,
            _ => continue,
        };
        let frame = flow.frames.get(&frame_id)?;
        let offset_x = frame.x + frame.content_x;
        let offset_y = frame.y + frame.content_y;
        let local_y = doc_y - offset_y;

        // Only claim the hit if the point is within the content area.
        // Points in the frame's chrome (margin/border/padding) should fall
        // through to subsequent flow items so cursor Up/Down can cross
        // frame boundaries.
        if local_y < 0.0 || local_y >= frame.content_height {
            continue;
        }

        // Try tables inside the frame first
        for table in &frame.tables {
            if local_y >= table.y
                && local_y < table.y + table.total_height
                && let Some(result) = hit_test_table_content(table, doc_y, x, offset_x, offset_y)
            {
                return Some(result);
            }
        }

        // Try nested frames
        for nested in &frame.frames {
            let nested_content_y = offset_y + nested.y + nested.content_y;
            let nested_local_y = doc_y - nested_content_y;
            if nested_local_y >= 0.0
                && nested_local_y < nested.content_height
                && let Some(result) = hit_test_frame_content(nested, doc_y, x, offset_x, offset_y)
            {
                return Some(result);
            }
        }

        // Find block at local_y within frame
        for block in &frame.blocks {
            let block_bottom = block.y + block.height;
            if local_y >= block.y && local_y < block_bottom {
                return hit_test_block(block.block_id, block, doc_y, x, offset_x, offset_y);
            }
        }

        // Fallback: last block in frame (point is within content area
        // but between blocks, e.g. in margin collapsing space)
        if let Some(block) = frame.blocks.last() {
            return hit_test_block(block.block_id, block, doc_y, x, offset_x, offset_y);
        }
    }
    None
}

/// Hit-test within a single frame's content (blocks, tables, nested frames).
/// `base_x`/`base_y` are the parent coordinate offsets (before this frame's own offsets).
fn hit_test_frame_content(
    frame: &crate::layout::frame::FrameLayout,
    doc_y: f32,
    x: f32,
    base_x: f32,
    base_y: f32,
) -> Option<HitTestResult> {
    let offset_x = base_x + frame.x + frame.content_x;
    let offset_y = base_y + frame.y + frame.content_y;
    let local_y = doc_y - offset_y;

    // Try tables
    for table in &frame.tables {
        if local_y >= table.y
            && local_y < table.y + table.total_height
            && let Some(result) = hit_test_table_content(table, doc_y, x, offset_x, offset_y)
        {
            return Some(result);
        }
    }

    // Try nested frames (recursive)
    for nested in &frame.frames {
        let nested_content_y = offset_y + nested.y + nested.content_y;
        let nested_local_y = doc_y - nested_content_y;
        if nested_local_y >= 0.0
            && nested_local_y < nested.content_height
            && let Some(result) = hit_test_frame_content(nested, doc_y, x, offset_x, offset_y)
        {
            return Some(result);
        }
    }

    // Try blocks
    for block in &frame.blocks {
        let block_bottom = block.y + block.height;
        if local_y >= block.y && local_y < block_bottom {
            return hit_test_block(block.block_id, block, doc_y, x, offset_x, offset_y);
        }
    }

    // Fallback: last block
    if let Some(block) = frame.blocks.last() {
        return hit_test_block(block.block_id, block, doc_y, x, offset_x, offset_y);
    }

    None
}

/// Try to hit-test within top-level table cells.
fn hit_test_in_table(flow: &FlowLayout, doc_y: f32, x: f32) -> Option<HitTestResult> {
    for item in &flow.flow_order {
        let table_id = match item {
            FlowItem::Table {
                table_id,
                y,
                height,
            } if doc_y >= *y && doc_y < *y + *height => *table_id,
            _ => continue,
        };
        let table = flow.tables.get(&table_id)?;
        return hit_test_table_content(table, doc_y, x, 0.0, 0.0);
    }
    None
}

/// Hit-test within a table's cells. `base_x`/`base_y` are added when
/// the table lives inside a frame.
fn hit_test_table_content(
    table: &crate::layout::table::TableLayout,
    doc_y: f32,
    x: f32,
    base_x: f32,
    base_y: f32,
) -> Option<HitTestResult> {
    let local_y = doc_y - base_y - table.y;
    let local_x = x - base_x;

    // Find row
    let row = find_table_row(table, local_y)?;
    // Find column
    let col = find_table_column(table, local_x)?;

    // Find the cell at (row, col)
    let cell = table
        .cell_layouts
        .iter()
        .find(|c| c.row == row && c.column == col)?;

    let cell_x = base_x + table.column_xs[col];
    let cell_y = base_y + table.y + table.row_ys[row];

    // Find block within the cell
    let tid = table.table_id;
    let cell_local_y = doc_y - cell_y;
    for block in &cell.blocks {
        let block_bottom = block.y + block.height;
        if cell_local_y >= block.y && cell_local_y < block_bottom {
            return hit_test_block(block.block_id, block, doc_y, x, cell_x, cell_y).map(|r| {
                HitTestResult {
                    table_id: Some(tid),
                    ..r
                }
            });
        }
    }

    // Fallback: last block in cell
    if let Some(block) = cell.blocks.last() {
        return hit_test_block(block.block_id, block, doc_y, x, cell_x, cell_y).map(|r| {
            HitTestResult {
                table_id: Some(tid),
                ..r
            }
        });
    }

    None
}

/// Find which row a local y coordinate falls into.
///
/// If the coordinate lands in the gap between two rows (border/spacing area),
/// snaps to the nearest row so that vertical navigation (down-arrow) can
/// cross row boundaries without falling into a dead zone.
fn find_table_row(table: &crate::layout::table::TableLayout, local_y: f32) -> Option<usize> {
    if table.row_ys.is_empty() {
        return None;
    }

    for (r, &row_y) in table.row_ys.iter().enumerate() {
        let row_top = row_y - table.cell_padding;
        let row_bottom =
            row_y + table.row_heights.get(r).copied().unwrap_or(0.0) + table.cell_padding;
        if local_y >= row_top && local_y < row_bottom {
            return Some(r);
        }
    }

    // Point is inside the table but in the gap between rows (or just outside
    // the first/last row padding). Snap to the nearest row.
    let mut best_row = 0;
    let mut best_dist = f32::MAX;
    for (r, &row_y) in table.row_ys.iter().enumerate() {
        let row_top = row_y - table.cell_padding;
        let row_bottom =
            row_y + table.row_heights.get(r).copied().unwrap_or(0.0) + table.cell_padding;
        let row_mid = (row_top + row_bottom) / 2.0;
        let dist = (local_y - row_mid).abs();
        if dist < best_dist {
            best_dist = dist;
            best_row = r;
        }
    }
    Some(best_row)
}

/// Find which column a local x coordinate falls into.
///
/// If the coordinate lands in the gap between columns, snaps to the nearest
/// column (same rationale as `find_table_row`).
fn find_table_column(table: &crate::layout::table::TableLayout, local_x: f32) -> Option<usize> {
    if table.column_xs.is_empty() {
        return None;
    }

    for (c, &col_x) in table.column_xs.iter().enumerate() {
        let col_left = col_x - table.cell_padding;
        let col_right =
            col_x + table.column_content_widths.get(c).copied().unwrap_or(0.0) + table.cell_padding;
        if local_x >= col_left && local_x < col_right {
            return Some(c);
        }
    }

    // Snap to nearest column.
    let mut best_col = 0;
    let mut best_dist = f32::MAX;
    for (c, &col_x) in table.column_xs.iter().enumerate() {
        let col_left = col_x - table.cell_padding;
        let col_right =
            col_x + table.column_content_widths.get(c).copied().unwrap_or(0.0) + table.cell_padding;
        let col_mid = (col_left + col_right) / 2.0;
        let dist = (local_x - col_mid).abs();
        if dist < best_dist {
            best_dist = dist;
            best_col = c;
        }
    }
    Some(best_col)
}

/// Search a frame (and its nested frames, recursively) for a caret position.
fn caret_rect_in_frame(
    frame: &crate::layout::frame::FrameLayout,
    position: usize,
    scroll_offset: f32,
    base_x: f32,
    base_y: f32,
) -> Option<[f32; 4]> {
    let fx = base_x + frame.x + frame.content_x;
    let fy = base_y + frame.y + frame.content_y;
    // Search tables before blocks (matching hit_test_in_frame priority).
    for table in &frame.tables {
        for cell in &table.cell_layouts {
            if cell.row >= table.row_ys.len() || cell.column >= table.column_xs.len() {
                continue;
            }
            let offset_x = fx + table.column_xs[cell.column];
            let offset_y = fy + table.y + table.row_ys[cell.row];
            for block in &cell.blocks {
                if let Some(rect) =
                    caret_rect_in_block(block, position, scroll_offset, offset_x, offset_y)
                {
                    return Some(rect);
                }
            }
        }
    }
    for block in &frame.blocks {
        if let Some(rect) = caret_rect_in_block(block, position, scroll_offset, fx, fy) {
            return Some(rect);
        }
    }
    for nested in &frame.frames {
        if let Some(rect) = caret_rect_in_frame(nested, position, scroll_offset, fx, fy) {
            return Some(rect);
        }
    }
    None
}

/// Compute the caret rect for a position within a single block.
/// Returns None if the position is not within this block.
fn caret_rect_in_block(
    block: &BlockLayout,
    position: usize,
    scroll_offset: f32,
    offset_x: f32,
    offset_y: f32,
) -> Option<[f32; 4]> {
    let block_end = block.position + block.lines.last().map(|l| l.char_range.end).unwrap_or(0);

    if position < block.position || position > block_end {
        return None;
    }

    let offset_in_block = position - block.position;

    for line in &block.lines {
        if offset_in_block < line.char_range.start {
            continue;
        }
        if offset_in_block > line.char_range.end {
            continue;
        }

        let caret_x = line.x_for_offset(offset_in_block) + block.left_margin + offset_x;
        let caret_y = offset_y + block.y + line.y - line.ascent - scroll_offset;
        let caret_height = line.line_height;

        return Some([caret_x, caret_y, 2.0, caret_height]);
    }

    None
}

fn find_block_at_y(flow: &FlowLayout, doc_y: f32) -> Option<(usize, &BlockLayout)> {
    if flow.flow_order.is_empty() {
        return None;
    }

    // Binary search: find the last item whose y <= doc_y
    let idx = flow.flow_order.partition_point(|item| {
        let y = match item {
            FlowItem::Block { y, .. } | FlowItem::Table { y, .. } | FlowItem::Frame { y, .. } => *y,
        };
        y <= doc_y
    });

    // Check the item at idx-1 (the last one with y <= doc_y) and nearby items
    let start = idx.saturating_sub(1);
    let end = (idx + 1).min(flow.flow_order.len());
    for i in start..end {
        if let FlowItem::Block {
            block_id,
            y,
            height,
        } = &flow.flow_order[i]
            && doc_y >= *y
            && doc_y < *y + *height
            && let Some(block) = flow.blocks.get(block_id)
        {
            return Some((*block_id, block));
        }
    }

    // Determine whether doc_y is above or below all content by comparing
    // against the first item's y. idx==0 means no item has y <= doc_y.
    if idx == 0 {
        // Above all blocks: return the first one
        for item in &flow.flow_order {
            if let FlowItem::Block { block_id, .. } = item
                && let Some(block) = flow.blocks.get(block_id)
            {
                return Some((*block_id, block));
            }
        }
    }

    // Below all blocks: return the last one
    for item in flow.flow_order.iter().rev() {
        if let FlowItem::Block { block_id, .. } = item
            && let Some(block) = flow.blocks.get(block_id)
        {
            return Some((*block_id, block));
        }
    }
    None
}

fn find_line_at_y(lines: &[LayoutLine], local_y: f32) -> Option<&LayoutLine> {
    // line.y is the baseline; the line occupies from (y - ascent) to (y - ascent + line_height)
    for line in lines {
        let line_top = line.y - line.ascent;
        let line_bottom = line_top + line.line_height;
        if local_y >= line_top && local_y < line_bottom {
            return Some(line);
        }
    }
    None
}

fn find_position_in_line(line: &LayoutLine, local_x: f32) -> (usize, HitRegion, Option<String>) {
    for run in &line.runs {
        // Inline image hit detection
        if let Some(ref name) = run.shaped_run.image_name {
            let img_end = run.x + run.shaped_run.advance_width;
            if local_x < img_end {
                let offset = run
                    .shaped_run
                    .glyphs
                    .first()
                    .map(|g| g.cluster as usize)
                    .unwrap_or(line.char_range.start);
                return (
                    offset,
                    HitRegion::Image { name: name.clone() },
                    run.decorations.tooltip.clone(),
                );
            }
            continue;
        }

        let mut glyph_x = run.x;

        for glyph in &run.shaped_run.glyphs {
            let glyph_mid = glyph_x + glyph.x_advance / 2.0;

            if local_x < glyph_mid {
                let offset = glyph.cluster as usize;
                let tooltip = run.decorations.tooltip.clone();
                if run.decorations.is_link {
                    return (
                        offset,
                        HitRegion::Link {
                            href: run.decorations.anchor_href.clone().unwrap_or_default(),
                        },
                        tooltip,
                    );
                }
                return (offset, HitRegion::Text, tooltip);
            }

            glyph_x += glyph.x_advance;
        }
    }

    // Past end of line
    (line.char_range.end, HitRegion::PastLineEnd, None)
}