rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Behavioural test-suite for the [`CodeEditor`] widget.
//!
//! The module-level tests cover the widget as a whole: lifecycle, mutation,
//! history, multi-caret editing, auto-pairing, line commands, find/replace,
//! folding, tabs and rendering. Pure algorithms are tested next to their
//! implementation in the sibling modules.

use super::*;
use crate::core::{Point, Rect};
use crate::widget::svg::render_to_svg;

fn editor() -> CodeEditor {
    CodeEditor::new(Rect::new(0, 0, 800, 600))
}

fn editor_with(config: CodeEditorConfig) -> CodeEditor {
    CodeEditor::with_config(Rect::new(0, 0, 800, 600), config).expect("valid configuration")
}

// ── 1. Lifecycle & configuration ────────────────────────────────────────────

/// The caret blinks in an editable buffer and is steady in a read-only one.
///
/// A caret that never changed was indistinguishable from a frozen marker, which is why the
/// negative half of this test matters as much as the positive one: a read-only editor must not keep
/// asking its host for frames to animate a caret it never draws.
#[test]
fn the_caret_blinks_when_editable_and_not_when_read_only() {
    let mut editor = editor();

    assert!(editor.tick(0), "an editable buffer blinks its caret");
    assert!(editor.is_caret_visible(), "it starts visible");
    assert!(editor.tick(500), "a blink is periodic and never settles");
    assert!(!editor.is_caret_visible(), "the half-period boundary flips it");
    assert!(editor.tick(500));
    assert!(editor.is_caret_visible(), "and it flips back");

    editor.set_read_only(true);
    assert!(!editor.tick(500), "a read-only editor has no caret to animate");
}

#[test]
fn default_state_is_an_empty_untitled_buffer() {
    let editor = editor();
    assert_eq!(editor.text(), "");
    assert_eq!(editor.cursor(), (0, 0));
    assert_eq!(editor.line_count(), 1, "a document always owns one line");
    assert!(editor.markers().is_empty());
    assert_eq!(editor.active_buffer(), 0);
    assert_eq!(editor.title(), "untitled");
    assert!(!editor.find_visible());
    assert!(!editor.completion_state().visible);
    assert!(!editor.context_menu().visible);
    assert!(!editor.has_multiple_cursors());
    assert_eq!(editor.language_name(), "Plain Text");
}

#[test]
fn config_validation_rejects_impossible_values() {
    assert!(CodeEditorConfig::new().tab_width(0).validate().is_err());
    assert!(CodeEditorConfig::new().tab_width(99).validate().is_err());
    assert!(CodeEditorConfig::new().font_size(0.0).validate().is_err());
    assert!(CodeEditorConfig::new().font_size(f32::NAN).validate().is_err());
    assert!(CodeEditorConfig::new().font_family("").validate().is_err());
    assert!(CodeEditorConfig::new().space_advance(0.0).validate().is_err());
    assert!(CodeEditorConfig::new().font_size(20.0).line_advance(10.0).validate().is_err());
    assert!(CodeEditorConfig::new().column_ruler(20_000).validate().is_err());
    assert!(CodeEditorConfig::new().validate().is_ok());
}

#[test]
fn with_config_propagates_validation_errors() {
    let geometry = Rect::new(0, 0, 400, 300);
    assert!(CodeEditor::with_config(geometry, CodeEditorConfig::new().tab_width(0)).is_err());
    let editor =
        CodeEditor::with_config(geometry, CodeEditorConfig::new().language(LanguageId::Rust));
    assert!(editor.is_ok());
    assert_eq!(editor.expect("valid config").language_name(), "Rust");
}

#[test]
fn language_selection_drives_tab_width_and_keywords() {
    let mut editor = editor();
    editor.set_language(LanguageId::Python);
    assert_eq!(editor.tab_width(), LanguageId::Python.default_tab_width());
    assert!(editor.keywords().contains(&"def"));
    assert!(!editor.keywords().contains(&"fn"));
    editor.set_language(LanguageId::Rust);
    assert!(editor.keywords().contains(&"fn"));
}

#[test]
fn display_options_are_builder_settable() {
    let config =
        CodeEditorConfig::new().auto_close_brackets(false).show_whitespace(true).column_ruler(80);
    assert!(!config.auto_close_brackets);
    assert!(config.show_whitespace);
    assert_eq!(config.column_ruler, 80);
    assert!(config.validate().is_ok());
}

// ── 2. Text mutation ────────────────────────────────────────────────────────

#[test]
fn set_text_get_text_roundtrip() {
    let mut editor = editor();
    editor.set_text("hello world");
    assert_eq!(editor.text(), "hello world");
    editor.set_text("hello world");
    assert_eq!(editor.text(), "hello world");
}

#[test]
fn append_line_grows_document_and_moves_caret() {
    let mut editor = editor();
    editor.append_line("first");
    assert_eq!(editor.line_count(), 1);
    editor.append_line("second");
    assert_eq!(editor.line_count(), 2);
    assert_eq!(editor.text(), "first\nsecond");
    assert_eq!(editor.cursor().0, 1);
}

#[test]
fn insert_at_caret_splices_mid_line() {
    let mut editor = editor();
    editor.set_text("fn main() {}\n");
    editor.set_cursor(0, 11, false);
    editor.insert("let x = 1;");
    assert_eq!(editor.line_text(0).as_deref(), Some("fn main() {let x = 1;}"));
    assert_eq!(editor.cursor(), (0, 21));
}

#[test]
fn insert_with_indent_expands_tabs() {
    let mut editor = editor_with(CodeEditorConfig::new().tab_width(2).insert_spaces(true));
    editor.insert_with_indent("a\tb");
    assert_eq!(editor.text(), "a  b");
}

#[test]
fn read_only_blocks_every_mutation() {
    let mut editor = editor_with(CodeEditorConfig::new().read_only(true));
    editor.set_text("locked");
    let before = editor.text();
    editor.insert("x");
    editor.insert_newline();
    editor.backspace();
    editor.delete_forward();
    editor.insert_tab();
    editor.outdent();
    editor.indent_selection();
    editor.toggle_line_comment();
    editor.delete_selection();
    editor.move_line(1);
    editor.duplicate_line();
    editor.delete_line();
    editor.join_lines();
    editor.sort_lines();
    assert_eq!(editor.text(), before);
    assert!(!editor.undo());
    assert!(!editor.redo());
}

#[test]
fn backspace_and_delete_forward_handle_line_boundaries() {
    let mut editor = editor();
    editor.set_text("ab\ncd");
    editor.set_cursor(1, 0, false);
    editor.backspace();
    assert_eq!(editor.text(), "abcd");
    editor.set_cursor(0, 2, false);
    editor.delete_forward();
    assert_eq!(editor.text(), "abd");
    editor.set_cursor(0, 0, false);
    editor.backspace();
    assert_eq!(editor.text(), "abd", "backspace at the document start is a no-op");
}

#[test]
fn delete_word_backward_removes_whole_identifier() {
    let mut editor = editor();
    editor.set_text("let counter_value = 1;");
    editor.set_cursor(0, 18, false);
    editor.delete_word_backward();
    assert_eq!(editor.text(), "let = 1;");
}

#[test]
fn newline_auto_indents_and_expands_braces() {
    let mut editor = editor_with(CodeEditorConfig::new().tab_width(4).insert_spaces(true));
    editor.set_text("fn main() {");
    editor.set_cursor(0, 11, false);
    editor.insert_newline();
    assert_eq!(editor.text(), "fn main() {\n    ");
    assert_eq!(editor.cursor(), (1, 4));
}

#[test]
fn newline_between_braces_opens_a_block() {
    let mut editor = editor_with(CodeEditorConfig::new().tab_width(4).insert_spaces(true));
    editor.set_text("{}");
    editor.set_cursor(0, 1, false);
    editor.insert_newline();
    assert_eq!(editor.text(), "{\n    \n}");
    assert_eq!(editor.cursor(), (1, 4));
}

// ── 3. History ──────────────────────────────────────────────────────────────

#[test]
fn undo_redo_round_trips_insertions() {
    let mut editor = editor();
    editor.set_text("one");
    editor.append_line("two");
    let after = editor.text();
    assert!(editor.can_undo());
    assert!(editor.undo());
    assert_eq!(editor.text(), "one");
    assert!(editor.redo());
    assert_eq!(editor.text(), after);
}

#[test]
fn multi_caret_edit_is_one_undo_step() {
    let mut editor = editor();
    editor.set_text("a\nb\nc");
    editor.clear_history();
    editor.set_cursor(0, 0, false);
    assert!(editor.add_cursor_below());
    assert!(editor.add_cursor_below());
    editor.insert(">");
    assert_eq!(editor.text(), ">a\n>b\n>c");
    assert!(editor.undo());
    assert_eq!(editor.text(), "a\nb\nc");
    assert!(!editor.can_undo());
}

// ── 4. Multi-caret editing ──────────────────────────────────────────────────

#[test]
fn added_carets_track_the_primary_and_insert_everywhere() {
    let mut editor = editor();
    editor.set_text("a\nbb\nccc");
    editor.set_cursor(0, 0, false);
    assert!(editor.add_cursor_below());
    assert!(editor.add_cursor_below());
    assert_eq!(editor.cursors().len(), 3);
    assert!(editor.has_multiple_cursors());
    editor.insert("x");
    assert_eq!(editor.text(), "xa\nxbb\nxccc");
    assert_eq!(editor.cursors().len(), 3);
}

#[test]
fn select_all_occurrences_edits_every_match() {
    let mut editor = editor();
    editor.set_text("let a = 1;\nlet b = 1;\nlet c = 1;");
    editor.set_cursor(0, 0, false);
    editor.set_cursor(0, 8, false);
    editor.select_next_occurrence();
    let count = editor.select_all_occurrences();
    assert_eq!(count, 3);
    editor.insert("2");
    assert_eq!(editor.text(), "let a = 2;\nlet b = 2;\nlet c = 2;");
}

#[test]
fn escape_style_collapse_keeps_only_the_primary() {
    let mut editor = editor();
    editor.set_text("a\nb\nc");
    editor.set_cursor(0, 0, false);
    assert!(editor.add_cursor_below());
    assert!(editor.add_cursor_below());
    assert_eq!(editor.cursors().len(), 3);
    assert!(editor.collapse_cursors());
    assert_eq!(editor.cursors().len(), 1);
    assert!(!editor.has_multiple_cursors());
    assert!(!editor.collapse_cursors(), "collapsing again is a no-op");
}

#[test]
fn backspace_applies_at_every_caret() {
    let mut editor = editor();
    editor.set_text("xa\nxb\nxc");
    editor.set_cursor(0, 1, false);
    assert!(editor.add_cursor_below());
    assert!(editor.add_cursor_below());
    editor.backspace();
    assert_eq!(editor.text(), "a\nb\nc");
}

// ── 5. Auto-pairing ─────────────────────────────────────────────────────────

#[test]
fn typing_an_opener_inserts_the_pair_and_centres_the_caret() {
    let mut editor = editor();
    editor.input_text("(");
    assert_eq!(editor.text(), "()");
    assert_eq!(editor.cursor(), (0, 1));
}

#[test]
fn typing_a_closer_skips_over_the_existing_partner() {
    let mut editor = editor();
    editor.set_text("()");
    editor.set_cursor(0, 1, false);
    editor.input_text(")");
    assert_eq!(editor.text(), "()");
    assert_eq!(editor.cursor(), (0, 2));
}

#[test]
fn typing_an_opener_wraps_the_selection() {
    let mut editor = editor();
    editor.set_text("hello world");
    editor.set_cursor(0, 0, false);
    editor.move_cursor_with_selection(0, 5, true);
    editor.input_text("(");
    assert_eq!(editor.text(), "(hello) world");
    assert_eq!(editor.selected_text().as_deref(), Some("hello"));
}

#[test]
fn auto_pairing_can_be_disabled() {
    let mut editor = editor_with(CodeEditorConfig::new().auto_close_brackets(false));
    editor.input_text("(");
    assert_eq!(editor.text(), "(");
}

#[test]
fn backspace_removes_an_empty_pair_together() {
    let mut editor = editor();
    editor.set_text("()");
    editor.set_cursor(0, 1, false);
    editor.backspace();
    assert_eq!(editor.text(), "");
}

// ── 6. Line commands ────────────────────────────────────────────────────────

#[test]
fn duplicate_line_copies_below_and_selects_the_copy() {
    let mut editor = editor();
    editor.set_text("alpha\nbeta");
    editor.set_cursor(0, 2, false);
    editor.duplicate_line();
    assert_eq!(editor.text(), "alpha\nalpha\nbeta");
    assert_eq!(editor.selected_text().as_deref(), Some("alpha"));
}

#[test]
fn delete_line_removes_the_caret_line() {
    let mut editor = editor();
    editor.set_text("alpha\nbeta\ngamma");
    editor.set_cursor(1, 0, false);
    editor.delete_line();
    assert_eq!(editor.text(), "alpha\ngamma");
}

#[test]
fn join_lines_merges_with_the_following_line() {
    let mut editor = editor();
    editor.set_text("foo\n    bar");
    editor.set_cursor(0, 0, false);
    editor.join_lines();
    assert_eq!(editor.text(), "foo bar");
    assert_eq!(editor.cursor(), (0, 3));
}

#[test]
fn sort_lines_orders_the_selected_block() {
    let mut editor = editor();
    editor.set_text("c\na\nb\nd");
    editor.set_cursor(0, 0, false);
    editor.move_cursor_with_selection(2, 0, true);
    editor.sort_lines();
    assert_eq!(editor.text(), "a\nb\nc\nd");
}

#[test]
fn goto_line_moves_to_the_first_non_blank_column() {
    let mut editor = editor();
    editor.set_text("zero\n    two\nthree");
    editor.goto_line(1);
    assert_eq!(editor.cursor(), (1, 4));
    editor.goto_line(999);
    assert_eq!(editor.cursor(), (2, 0));
}

#[test]
fn trim_trailing_whitespace_cleans_every_line() {
    let mut editor = editor();
    editor.set_text("a  \nb\t\nc");
    editor.trim_trailing_whitespace();
    assert_eq!(editor.text(), "a\nb\nc");
}

// ── 7. Find & replace ───────────────────────────────────────────────────────

#[test]
fn find_bar_tracks_hits_and_navigates() {
    let mut editor = editor();
    editor.set_text("foo bar foo baz foo");
    editor.open_find(false);
    assert!(editor.find_visible());
    editor.set_search_query("foo");
    assert_eq!(editor.search_matches().len(), 3);
    editor.find_next(false);
    let first = editor.selected_text();
    editor.find_next(false);
    let second = editor.selected_text();
    assert_eq!(first, second);
    assert_eq!(first.as_deref(), Some("foo"));
    editor.close_find();
    assert!(!editor.find_visible());
}

#[test]
fn replace_all_rewrites_every_hit_in_one_step() {
    let mut editor = editor();
    editor.set_text("a-b-c");
    editor.open_find(true);
    editor.set_search_query("-");
    editor.set_search_replacement("+");
    let replaced = editor.replace_all();
    assert_eq!(replaced, 2);
    assert_eq!(editor.text(), "a+b+c");
    assert!(editor.undo());
    assert_eq!(editor.text(), "a-b-c");
}

// ── 8. Folding ──────────────────────────────────────────────────────────────

#[test]
fn folding_hides_interior_lines_and_unfolding_restores_them() {
    let mut editor = editor_with(CodeEditorConfig::new().language(LanguageId::Rust));
    editor.set_text("fn main() {\n    let x = 1;\n    let y = 2;\n}");
    editor.fold(0, 3);
    assert!(editor.is_line_folded(0));
    assert_eq!(editor.folded_line_count(), 3);
    editor.unfold_all();
    assert_eq!(editor.folded_line_count(), 0);
}

/// `is_line_folded` must agree with `folded_line_count` at any fold count.
///
/// They used to answer from *different* sources — this predicate scanned the
/// derived `folded_lines` cache while the count read the model. The two agree in
/// every configuration that actually compiles today, so this is a consistency
/// guard rather than a reproduction: it pins the invariant that the read paths
/// cannot diverge, and it exceeds the `MiniVec` capacity so the cache cannot hold
/// every folded start. If `code_editor` is ever enabled on an `alloc_frugal`
/// build, this is the test that would catch the drift first.
#[test]
fn folding_more_regions_than_the_cache_holds_stays_consistent() {
    let mut editor = editor_with(CodeEditorConfig::new().language(LanguageId::Rust));
    // 100 foldable regions, comfortably past the 64-element cache.
    let mut text = String::new();
    for i in 0..100 {
        text.push_str(&format!("fn f{i}() {{\n    let x = {i};\n}}\n"));
    }
    editor.set_text(&text);

    let last_line = editor.line_count().saturating_sub(1);
    let mut line = 0usize;
    while line < editor.line_count() {
        editor.fold(line, (line + 2).min(last_line));
        line += 3;
    }
    let folded = editor.fold_regions().iter().filter(|r| r.folded).count();
    assert!(folded > 64, "the test must exceed the 64-element cache, got {folded}");

    // Every folded region must be reported, including one the cache would have
    // had to drop first.
    let mut folded_starts: Vec<usize> =
        editor.fold_regions().iter().filter(|r| r.folded).map(|r| r.start_line).collect();
    folded_starts.sort_unstable();
    for start in [folded_starts[0], *folded_starts.last().expect("non-empty")] {
        assert!(
            editor.is_line_folded(start),
            "folded region at line {start} must be reported as folded"
        );
    }

    // A line that is NOT folded must not be reported as folded either — the
    // predicate has to stay exact, not just permissive.
    let unfolded = (0..editor.line_count()).find(|l| !folded_starts.contains(l));
    if let Some(line) = unfolded {
        assert!(!editor.is_line_folded(line));
    }

    editor.unfold_all();
    assert_eq!(editor.folded_line_count(), 0);
    assert!(!editor.is_line_folded(folded_starts[0]));
}

// ── 9. Tabs ─────────────────────────────────────────────────────────────────

#[test]
fn buffers_open_switch_and_close() {
    let mut editor = editor();
    let first = editor.active_buffer();
    let second = editor.open_buffer("second.rs", "fn b() {}");
    assert_eq!(editor.active_buffer(), second);
    assert_eq!(editor.text(), "fn b() {}");
    assert!(editor.activate_buffer(first));
    assert_eq!(editor.text(), "");
    assert!(editor.close_buffer(second));
    assert_eq!(editor.buffers().len(), 1);
}

// ── 10. Rendering ───────────────────────────────────────────────────────────

#[test]
fn draw_produces_svg_output() {
    let mut editor = editor();
    editor.set_text("fn main() {\n    let x = 1;\n}");
    editor.set_markers(vec![DiagnosticMarker::new(1, "unused", MarkerSeverity::Warning)]);
    let svg = render_to_svg(&mut editor);
    assert!(svg.starts_with("<svg"));
    assert!(svg.len() > 100);
}

#[test]
fn draw_with_multiple_cursors_stays_well_formed() {
    let mut editor = editor();
    editor.set_text("alpha\nbeta\ngamma");
    editor.set_cursor(0, 0, false);
    assert!(editor.add_cursor_below());
    assert!(editor.add_cursor_below());
    let svg = render_to_svg(&mut editor);
    assert!(svg.starts_with("<svg"));
    assert!(svg.ends_with("</svg>"));
}

#[test]
fn whitespace_and_ruler_overlays_render_without_panicking() {
    let mut editor = editor_with(CodeEditorConfig::new().show_whitespace(true).column_ruler(10));
    editor.set_text("let x = 1;\n\tlet y = 2;");
    let svg = render_to_svg(&mut editor);
    assert!(svg.starts_with("<svg"));
    assert!(svg.ends_with("</svg>"));
}

#[test]
fn rect_for_range_is_available_for_a_valid_selection() {
    let editor = editor();
    let rect = editor.rect_for_range(TextPosition::new(0, 0), TextPosition::new(0, 5));
    assert!(rect.is_some());
}

#[test]
fn position_at_point_is_inside_the_document() {
    let editor = editor();
    let position = editor.position_at_point(Point::new(200, 120));
    assert!(position.is_some());
}

/// The editor's palette follows the active appearance, so it is not a white slab in a dark window.
///
/// Regression (BLUE21 P4-4): the constructor used `SyntaxPalette::default()` unconditionally, and
/// that default is the *light* palette. A dark host therefore got a near-white editor background
/// with dark token ink inside a dark window — the same shape `radar_chart` and `font_preview` had.
/// The assertion is a relation between the two palettes, not two literals: the dark background must
/// be darker than the light one, and each palette's plain ink must be legible on its own ground.
#[test]
fn the_syntax_palette_has_a_dark_counterpart_that_reads_on_its_own_ground() {
    let light = SyntaxPalette::light();
    let dark = SyntaxPalette::dark();

    assert!(
        dark.background.luminance() < light.background.luminance(),
        "the dark palette's editor ground must be the darker of the two"
    );
    assert!(
        dark.chrome_background.luminance() < light.chrome_background.luminance(),
        "and its chrome with it"
    );
    for palette in [&light, &dark] {
        let plain = palette.color_for(TokenKind::Plain);
        assert!(
            plain.contrast_ratio(palette.background) >= 4.5,
            "plain text must clear the AA floor on its own ground: {:.2}:1",
            plain.contrast_ratio(palette.background)
        );
        let comment = palette.color_for(TokenKind::Comment);
        assert!(
            comment.contrast_ratio(palette.background) >= 4.5,
            "a comment must be readable, not merely present: {:.2}:1",
            comment.contrast_ratio(palette.background)
        );
        // Every category is distinct from plain: a palette whose keywords look like identifiers is
        // a palette a reader cannot scan.
        for kind in [TokenKind::Keyword, TokenKind::Type, TokenKind::Function, TokenKind::String] {
            assert_ne!(
                palette.color_for(kind),
                plain,
                "{kind:?} must be distinguished from plain text"
            );
        }
    }
    assert_ne!(
        SyntaxPalette::default(),
        dark,
        "the default stays the light palette so an unthemed build is unchanged"
    );
    assert_eq!(SyntaxPalette::default(), light, "and it is exactly the light one");
}

/// A freshly constructed editor picks the palette that matches the active appearance.
///
/// This is the half the palette test above cannot cover: that test proves both palettes exist and
/// read correctly, while this one proves the *constructor* selects the right one. Regression
/// (BLUE21 P4-4): it selected the light one unconditionally, so the dark census SVG carried a
/// near-white editor inside a dark window.
#[test]
fn a_fresh_editor_picks_the_palette_that_matches_the_active_appearance() {
    let _guard = crate::style::theme_test_guard();
    {
        let mut manager = crate::theme::global_theme_manager();
        manager.register_theme(crate::theme::Theme::default());
        manager.register_theme(crate::theme::Theme::dark());
    }

    crate::theme::global_theme_manager().set_appearance(crate::theme::AppearanceMode::Light);
    let light = editor().palette().background;
    crate::theme::global_theme_manager().set_appearance(crate::theme::AppearanceMode::Dark);
    let dark = editor().palette().background;

    assert!(
        dark.luminance() < light.luminance(),
        "the dark editor must have the darker ground: light={light:?} dark={dark:?}"
    );
    assert_eq!(light, SyntaxPalette::light().background, "light selects the light palette");
    crate::theme::global_theme_manager().set_appearance(crate::theme::AppearanceMode::Light);
}

/// The two palettes are opposite in the way that matters: every dark token ink is lighter than its
/// light counterpart, and every one clears the AA floor on its own ground.
///
/// # Why this replaces a pixel assertion
///
/// A first attempt rendered the editor with text and compared the emitted token fills. That
/// assertion **did not bear weight**: the renderer pushes a token's ink toward the *field* it sits
/// on, and the field follows the theme — so the two appearances' token fills differ even when both
/// draw the same palette, and forcing the light palette into the dark editor still left the dark
/// render's tokens far lighter (min luminance 181 vs the light render's max 68). The palette's own
/// effect is entangled with the field blend at that level.
///
/// The property that *is* the defect is a property of the palette itself — a light-ground palette
/// used on a dark ground — so it is asserted on the palettes, where it is exact, rather than on a
/// derivation that cannot separate the two.
#[test]
fn every_dark_token_ink_is_lighter_than_its_light_counterpart() {
    let light = SyntaxPalette::light();
    let dark = SyntaxPalette::dark();
    let mut checked = 0;
    for kind in [
        TokenKind::Plain,
        TokenKind::Keyword,
        TokenKind::Type,
        TokenKind::Function,
        TokenKind::String,
        TokenKind::Comment,
        TokenKind::Number,
    ] {
        let l = light.color_for(kind);
        let d = dark.color_for(kind);
        assert!(
            d.luminance() > l.luminance(),
            "{kind:?} must be a lighter ink in the dark palette: light={l:?} dark={d:?}"
        );
        assert!(
            d.contrast_ratio(dark.background) >= 4.5,
            "{kind:?} must clear the AA floor on the dark ground: {:.2}:1",
            d.contrast_ratio(dark.background)
        );
        checked += 1;
    }
    assert_eq!(checked, 7, "the loop must actually cover the categories it names");
}