writ 0.17.1

A hybrid markdown editor combining raw text editing with live inline rendering
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! Window chrome for the new shell (see MIGRATION-PLAN.md, Phase 6): an in-window
//! title bar (filename + dirty marker) and a status bar (nesting context + cursor
//! position). Drawn as opaque strips above/below the editor, which is inset between
//! them. CSD (custom window frame) and the async-blocked overlays are deferred.

use parley::Layout;
use vello::Scene;
use vello::kurbo::{Affine, Line, Rect, RoundedRect, Stroke};
use vello::peniko::{Brush, Color, Fill};

use crate::consts::{FIND_ROW_H, PADDING, UI_LINE_HEIGHT};
use crate::core::{FieldFocus, FindMode, FindState};
use crate::doc_layout::ScreenRect;
use crate::editor::EditorTheme;
use crate::marker::MarkerKind;
use crate::status_bar::build_context_display;
use crate::text_engine::{StyleRun, TextEngine, peniko_color, peniko_color_alpha};
use crate::text_input::{TextField, draw_text_field};

/// Everything the status bar shows, gathered from the editor + viewport each frame.
pub struct StatusInfo {
    pub context: Vec<MarkerKind>,
    pub heading_level: Option<u8>,
    pub cursor_line: usize,
    pub cursor_col: usize,
    pub total_lines: usize,
    pub first_visible: usize,
    pub last_visible: usize,
}

/// A screen rect (device px) for a chrome strip.
pub struct BarRect {
    pub x0: f64,
    pub y0: f64,
    pub x1: f64,
    pub y1: f64,
}

fn fill_rect(scene: &mut Scene, color: Color, r: &BarRect) {
    scene.fill(
        Fill::NonZero,
        Affine::IDENTITY,
        color,
        None,
        &Rect::new(r.x0, r.y0, r.x1, r.y1),
    );
}

/// Draw a floating overlay panel: a filled rounded rect with a border. Shared by
/// the GitHub hover popover and the autocomplete dropdown.
pub fn draw_panel(
    scene: &mut Scene,
    bg: Color,
    border: Color,
    rect: &Rect,
    radius: f64,
    stroke_w: f64,
) {
    let rr = RoundedRect::from_rect(*rect, radius);
    scene.fill(Fill::NonZero, Affine::IDENTITY, bg, None, &rr);
    scene.stroke(&Stroke::new(stroke_w), Affine::IDENTITY, border, None, &rr);
}

/// The shared chrome-panel look: a `theme.surface` fill with a `theme.selection`
/// hairline border, rounded. Reused by floating in-editor UI (the find bar now;
/// doc map / folding later) so they share one tone with the status bar.
pub fn draw_chrome_panel(scene: &mut Scene, theme: &EditorTheme, rect: &Rect, scale: f32) {
    draw_panel(
        scene,
        peniko_color(theme.surface),
        peniko_color(theme.selection),
        rect,
        6.0 * scale as f64,
        scale as f64,
    );
}

fn hline(scene: &mut Scene, color: Color, x0: f64, x1: f64, y: f64, width: f64) {
    scene.stroke(
        &Stroke::new(width),
        Affine::IDENTITY,
        color,
        None,
        &Line::new((x0, y), (x1, y)),
    );
}

/// Vertically-center a single line of `font_size` (device px) within a bar.
fn baseline_top(bar: &BarRect, font_size: f32) -> f32 {
    (bar.y0 as f32) + ((bar.y1 - bar.y0) as f32 - font_size * UI_LINE_HEIGHT) / 2.0
}

/// Vertically-center a built layout within a bar using its *actual* height, so the
/// glyphs sit on the bar's centerline regardless of the font's line-box metrics.
fn center_top(bar: &BarRect, layout_height: f32) -> f32 {
    (bar.y0 as f32) + ((bar.y1 - bar.y0) as f32 - layout_height) / 2.0
}

/// Draw the top title bar: centered filename with a leading `*` when dirty.
pub fn draw_title_bar(
    engine: &mut TextEngine,
    scene: &mut Scene,
    theme: &EditorTheme,
    bar: &BarRect,
    filename: &str,
    dirty: bool,
    scale: f32,
) {
    fill_rect(scene, peniko_color(theme.background), bar);
    hline(
        scene,
        peniko_color(theme.selection),
        bar.x0,
        bar.x1,
        bar.y1,
        scale as f64,
    );

    let title = if dirty {
        format!("* {filename}")
    } else {
        filename.to_string()
    };
    let font_size = 15.0;
    let color = peniko_color(theme.foreground);
    let layout = engine.build_line(&title, scale, font_size, UI_LINE_HEIGHT, color, None, &[]);
    let w = layout.width();
    let cx = ((bar.x0 + bar.x1) as f32 / 2.0) - w / 2.0;
    engine.draw_line(
        scene,
        &layout,
        (cx.max(bar.x0 as f32), baseline_top(bar, font_size)),
    );
}

/// Font size (device-independent px) for find-bar labels + match count.
const FIND_LABEL_FONT: f32 = 14.0;
/// Font size for the `.*` / `Aa` toggle chips.
const FIND_CHIP_FONT: f32 = 13.0;
/// Fixed width of the right-aligned label column (`Find`/`Replace`) so both rows align.
const FIND_LABEL_SLOT: f32 = 70.0;

/// The click rects of the replace row's `Replace` and `All` buttons (device px), returned
/// so the shell can hit-test clicks on them. Only present in Replace mode.
pub struct FindButtonRects {
    pub replace: ScreenRect,
    pub all: ScreenRect,
}

/// Draw the bottom-docked find bar (search row, plus a replace row in Replace mode)
/// filling `bar` — the strip between the document and the status bar. Same surface look
/// as the status bar: `theme.surface` fill with a `theme.selection` top hairline.
pub fn draw_find_bar(
    engine: &mut TextEngine,
    scene: &mut Scene,
    theme: &EditorTheme,
    find: &FindState,
    bar: &BarRect,
    scale: f32,
) -> Option<FindButtonRects> {
    fill_rect(scene, peniko_color(theme.surface), bar);
    hline(
        scene,
        peniko_color(theme.selection),
        bar.x0,
        bar.x1,
        bar.y0,
        scale as f64,
    );

    let row_h = FIND_ROW_H * scale;
    let rows = if find.mode == FindMode::Replace {
        2.0
    } else {
        1.0
    };
    let vpad = ((bar.y1 - bar.y0) as f32 - row_h * rows) / 2.0;
    let search_top = bar.y0 as f32 + vpad;

    draw_find_search_row(engine, scene, theme, find, bar, search_top, row_h, scale);
    if find.mode == FindMode::Replace {
        Some(draw_find_replace_row(
            engine,
            scene,
            theme,
            find,
            bar,
            search_top + row_h,
            row_h,
            scale,
        ))
    } else {
        None
    }
}

#[allow(clippy::too_many_arguments)]
fn draw_find_search_row(
    engine: &mut TextEngine,
    scene: &mut Scene,
    theme: &EditorTheme,
    find: &FindState,
    bar: &BarRect,
    row_top: f32,
    row_h: f32,
    scale: f32,
) {
    let pad = PADDING * scale;
    let gap = 10.0 * scale;
    let slot = FIND_LABEL_SLOT * scale;
    let left = bar.x0 as f32 + pad;
    let right = bar.x1 as f32 - pad;

    draw_find_label(engine, scene, theme, "Find", left, row_top, row_h, scale);

    // Right block, laid out right-to-left: match count, then case + regex chips. With no
    // matches this reads "0 / 0" (active None → 0, len 0).
    let count_str = format!(
        "{} / {}",
        find.active.map(|i| i + 1).unwrap_or(0),
        find.matches.len()
    );
    let mut run = StyleRun::new(0..count_str.len(), peniko_color(theme.comment));
    run.mono = true;
    let count = engine.build_line(
        &count_str,
        scale,
        FIND_LABEL_FONT,
        UI_LINE_HEIGHT,
        peniko_color(theme.comment),
        None,
        &[run],
    );
    let count_x = right - count.width();
    engine.draw_line(
        scene,
        &count,
        (count_x, row_top + (row_h - count.height()) / 2.0),
    );

    let mut rx = count_x - gap;
    rx = draw_find_chip(
        engine,
        scene,
        theme,
        "Aa",
        rx,
        row_top,
        row_h,
        find.case_sensitive,
        scale,
    );
    rx -= gap * 0.5;
    rx = draw_find_chip(
        engine, scene, theme, ".*", rx, row_top, row_h, find.regex, scale,
    );
    let field_right = rx - gap;

    let field_left = left + slot + gap;
    draw_find_field(
        engine,
        scene,
        theme,
        &find.search,
        field_left,
        field_right,
        row_top,
        row_h,
        find.focused && find.focus == FieldFocus::Search,
        scale,
    );
}

#[allow(clippy::too_many_arguments)]
fn draw_find_replace_row(
    engine: &mut TextEngine,
    scene: &mut Scene,
    theme: &EditorTheme,
    find: &FindState,
    bar: &BarRect,
    row_top: f32,
    row_h: f32,
    scale: f32,
) -> FindButtonRects {
    let pad = PADDING * scale;
    let gap = 10.0 * scale;
    let slot = FIND_LABEL_SLOT * scale;
    let left = bar.x0 as f32 + pad;
    let right = bar.x1 as f32 - pad;
    draw_find_label(engine, scene, theme, "Replace", left, row_top, row_h, scale);

    // Right block, laid out right-to-left: `All` (primary), then `Replace`.
    let (all_left, all) = draw_find_button(
        engine, scene, theme, "All", right, row_top, row_h, true, scale,
    );
    let (replace_left, replace) = draw_find_button(
        engine,
        scene,
        theme,
        "Replace",
        all_left - gap * 0.5,
        row_top,
        row_h,
        false,
        scale,
    );

    draw_find_field(
        engine,
        scene,
        theme,
        &find.replace,
        left + slot + gap,
        replace_left - gap,
        row_top,
        row_h,
        find.focused && find.focus == FieldFocus::Replace,
        scale,
    );
    FindButtonRects { replace, all }
}

/// Draw a right-anchored pill: a rounded fill (+ optional border) sized to `layout` plus
/// `cpad` on each side and `row_h * h_factor` tall, with the label centered inside. Returns
/// the pill rect (its `x0` is the left edge, for right-to-left chaining). Shared geometry of
/// the find-bar buttons and toggle chips.
#[allow(clippy::too_many_arguments)]
fn draw_pill(
    engine: &mut TextEngine,
    scene: &mut Scene,
    layout: &Layout<Brush>,
    right_x: f32,
    row_top: f32,
    row_h: f32,
    cpad: f32,
    h_factor: f32,
    bg: Color,
    border: Option<Color>,
    scale: f32,
) -> Rect {
    let w = layout.width() + 2.0 * cpad;
    let h = row_h * h_factor;
    let x0 = right_x - w;
    let cy = row_top + (row_h - h) / 2.0;
    let rect = Rect::new(x0 as f64, cy as f64, right_x as f64, (cy + h) as f64);
    let rr = RoundedRect::from_rect(rect, 4.0 * scale as f64);
    scene.fill(Fill::NonZero, Affine::IDENTITY, bg, None, &rr);
    if let Some(border) = border {
        scene.stroke(
            &Stroke::new(scale as f64),
            Affine::IDENTITY,
            peniko_color(border),
            None,
            &rr,
        );
    }
    engine.draw_line(scene, layout, (x0 + cpad, cy + (h - layout.height()) / 2.0));
    rect
}

/// A boxed action button drawn against its right edge `right_x`; returns its left edge (so
/// buttons chain right-to-left) and its click rect. `primary` buttons (Replace All) read
/// greenish; plain buttons use a subtle neutral fill.
#[allow(clippy::too_many_arguments)]
fn draw_find_button(
    engine: &mut TextEngine,
    scene: &mut Scene,
    theme: &EditorTheme,
    label: &str,
    right_x: f32,
    row_top: f32,
    row_h: f32,
    primary: bool,
    scale: f32,
) -> (f32, ScreenRect) {
    let (color, bg, border) = if primary {
        (
            theme.green,
            peniko_color_alpha(theme.green, 0.20),
            theme.green,
        )
    } else {
        (
            theme.foreground,
            peniko_color_alpha(theme.comment, 0.12),
            theme.selection,
        )
    };
    let layout = engine.build_line(
        label,
        scale,
        FIND_CHIP_FONT,
        UI_LINE_HEIGHT,
        peniko_color(color),
        None,
        &[],
    );
    let rect = draw_pill(
        engine,
        scene,
        &layout,
        right_x,
        row_top,
        row_h,
        8.0 * scale,
        0.78,
        bg,
        Some(border),
        scale,
    );
    (rect.x0 as f32, (rect.x0, rect.y0, rect.x1, rect.y1))
}

/// A row label left-aligned at `left` (so `Find`/`Replace` line up with the document's
/// left text edge).
#[allow(clippy::too_many_arguments)]
fn draw_find_label(
    engine: &mut TextEngine,
    scene: &mut Scene,
    theme: &EditorTheme,
    text: &str,
    left: f32,
    row_top: f32,
    row_h: f32,
    scale: f32,
) {
    let layout = engine.build_line(
        text,
        scale,
        FIND_LABEL_FONT,
        UI_LINE_HEIGHT,
        peniko_color(theme.comment),
        None,
        &[],
    );
    engine.draw_line(
        scene,
        &layout,
        (left, row_top + (row_h - layout.height()) / 2.0),
    );
}

/// A toggle chip drawn against its right edge `right_x`; returns its left edge so the
/// caller can chain chips right-to-left. Active chips read purple with a tinted fill.
#[allow(clippy::too_many_arguments)]
fn draw_find_chip(
    engine: &mut TextEngine,
    scene: &mut Scene,
    theme: &EditorTheme,
    label: &str,
    right_x: f32,
    row_top: f32,
    row_h: f32,
    active: bool,
    scale: f32,
) -> f32 {
    let color = if active { theme.purple } else { theme.comment };
    let layout = engine.build_line(
        label,
        scale,
        FIND_CHIP_FONT,
        UI_LINE_HEIGHT,
        peniko_color(color),
        None,
        &[],
    );
    let bg = if active {
        peniko_color_alpha(theme.purple, 0.22)
    } else {
        peniko_color_alpha(theme.comment, 0.10)
    };
    draw_pill(
        engine,
        scene,
        &layout,
        right_x,
        row_top,
        row_h,
        6.0 * scale,
        0.72,
        bg,
        None,
        scale,
    )
    .x0 as f32
}

/// A boxed text field: a lighter (document-background) rounded fill with a border —
/// purple when focused, otherwise the surface hairline — then the field's text/caret.
#[allow(clippy::too_many_arguments)]
fn draw_find_field(
    engine: &mut TextEngine,
    scene: &mut Scene,
    theme: &EditorTheme,
    field: &TextField,
    x0: f32,
    x1: f32,
    row_top: f32,
    row_h: f32,
    focused: bool,
    scale: f32,
) {
    let fh = row_h - 4.0 * scale;
    let cy = row_top + (row_h - fh) / 2.0;
    let rect = Rect::new(x0 as f64, cy as f64, x1.max(x0) as f64, (cy + fh) as f64);
    let rr = RoundedRect::from_rect(rect, 4.0 * scale as f64);
    scene.fill(
        Fill::NonZero,
        Affine::IDENTITY,
        peniko_color(theme.background),
        None,
        &rr,
    );
    let border = if focused {
        theme.purple
    } else {
        theme.selection
    };
    scene.stroke(
        &Stroke::new(scale as f64),
        Affine::IDENTITY,
        peniko_color(border),
        None,
        &rr,
    );
    draw_text_field(engine, scene, theme, field, &rect, scale, focused);
}

/// Draw the bottom status bar: left = nesting context (depth-colored), right =
/// heading level, cursor position, line count, scroll indicator.
pub fn draw_status_bar(
    engine: &mut TextEngine,
    scene: &mut Scene,
    theme: &EditorTheme,
    bar: &BarRect,
    info: &StatusInfo,
    scale: f32,
) {
    fill_rect(scene, peniko_color(theme.surface), bar);
    hline(
        scene,
        peniko_color(theme.selection),
        bar.x0,
        bar.x1,
        bar.y0,
        scale as f64,
    );

    let font_size = 15.0;
    let pad = PADDING * scale;

    // --- left: context markers, colored by nesting depth ---
    let depth_colors = [
        theme.cyan,
        theme.purple,
        theme.green,
        theme.orange,
        theme.pink,
        theme.yellow,
    ];
    let items = build_context_display(&info.context);
    let mut text = String::new();
    let mut runs = Vec::new();
    for (i, (s, depth)) in items.iter().enumerate() {
        // Compact nested-checkbox glyphs (`" ]"` / `"x]"`) attach to the preceding item
        // with no separating space; everything else gets a leading space.
        let needs_space = !s.starts_with(' ') && !s.starts_with('x');
        if i > 0 && needs_space {
            text.push(' ');
        }
        let start = text.len();
        text.push_str(s);
        let mut run = StyleRun::new(
            start..text.len(),
            peniko_color(depth_colors[depth % depth_colors.len()]),
        );
        run.mono = true;
        runs.push(run);
    }
    if !text.is_empty() {
        let layout = engine.build_line(
            &text,
            scale,
            font_size,
            UI_LINE_HEIGHT,
            peniko_color(theme.comment),
            None,
            &runs,
        );
        engine.draw_line(
            scene,
            &layout,
            (bar.x0 as f32 + pad, center_top(bar, layout.height())),
        );
    }

    // --- right: H-level · Ln,Col · lines · scroll ---
    let scroll = if info.total_lines <= 1
        || (info.first_visible == 0 && info.last_visible + 1 >= info.total_lines)
    {
        "All".to_string()
    } else if info.first_visible == 0 {
        "Top".to_string()
    } else if info.last_visible + 1 >= info.total_lines {
        "Bot".to_string()
    } else {
        format!(
            "{}%",
            (info.last_visible + 1) * 100 / info.total_lines.max(1)
        )
    };
    let mut segments = Vec::new();
    if let Some(l) = info.heading_level {
        segments.push(format!("H{l}"));
    }
    segments.push(format!("Ln {}, Col {}", info.cursor_line, info.cursor_col));
    segments.push(format!("{} lines", info.total_lines));
    segments.push(scroll);
    let right = segments.join("  ·  ");
    let layout = engine.build_line(
        &right,
        scale,
        font_size,
        UI_LINE_HEIGHT,
        peniko_color(theme.comment),
        None,
        &[],
    );
    let x = bar.x1 as f32 - pad - layout.width();
    engine.draw_line(scene, &layout, (x, center_top(bar, layout.height())));
}