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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! InplaceEditor widget — an in-place text editing control for table/cell editing.
//!
//! Displays text normally, and when activated (double-click), switches to an
//! edit mode with a blinking cursor. Enter/Tab accepts changes, Escape cancels.
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::undo::{TextSnapshotCommand, UndoStack};
use crate::widget::capability::coercion::{expect_bool, expect_string};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::metrics::{dimensions, ControlMetrics};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
use std::cell::RefCell;
use std::rc::Rc;
/// A text editor that switches between display mode and edit mode in-place.
///
/// In display mode, the text is drawn as plain text with a background.
/// In edit mode, it draws a text input area with a blinking cursor.
pub struct InplaceEditor {
base: BaseWidget,
text: String,
is_editing: bool,
original_text: String,
font_size: f32,
padding: i32,
cursor_position: usize,
undo_stack: UndoStack,
history_target: Rc<RefCell<String>>,
restoring_history: bool,
/// The edit caret's blink state, advanced by [`InplaceEditor::tick`].
///
/// It lives on the control because it is state that must survive between frames; the tempo and
/// the phase logic come from [`crate::style::CursorBlink`] so this control cannot drift from
/// every other caret in the crate.
cursor_blink: crate::style::CursorBlink,
/// Emitted when the edit is accepted (Enter/Tab). Carries the final text.
pub edit_accepted: Signal1<String>,
/// Emitted when the edit is cancelled (Escape).
pub edit_cancelled: GenericSignal,
}
impl InplaceEditor {
/// Creates a new InplaceEditor widget with the given text and geometry.
pub fn new(text: &str, geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::InplaceEditor, geometry, "InplaceEditor"),
text: text.to_string(),
is_editing: false,
original_text: text.to_string(),
font_size: 14.0,
padding: 4,
cursor_position: text.len(),
undo_stack: UndoStack::new(),
history_target: Rc::new(RefCell::new(text.to_string())),
restoring_history: false,
cursor_blink: crate::style::CursorBlink::new(),
edit_accepted: Signal1::new(),
edit_cancelled: GenericSignal::new(),
}
}
/// Starts editing mode.
pub fn start_edit(&mut self) {
if !self.is_editing {
self.is_editing = true;
self.original_text = self.text.clone();
self.cursor_position = self.text.len();
// Entering edit mode is entering the state the caret blinks in, so the blink starts
// here rather than waiting for the host to notice — a caret that only began blinking on
// some later frame would sit frozen for however long that took.
self.cursor_blink.start();
self.base.request_redraw();
}
}
/// Finishes editing mode. If `accept` is true, the current text is kept;
/// otherwise it reverts to the original text.
pub fn finish_edit(&mut self, accept: bool) {
if !self.is_editing {
return;
}
self.is_editing = false;
// Leaving edit mode stops the caret's animation, so a host driving frames from the control
// stops scheduling them. The caret is left visible, which is what a blurred field shows.
self.cursor_blink.stop();
if accept {
self.edit_accepted.emit(self.text.clone());
} else {
self.text = self.original_text.clone();
self.edit_cancelled.emit();
}
self.base.request_redraw();
}
/// Advances the edit caret's blink by `delta_ms` and reports whether another frame is needed.
///
/// The crate's `tick(delta_ms) -> bool` convention, and the reason the module's docs can claim
/// a blinking cursor: before this existed the caret was a solid line and nothing ever told the
/// host to draw another frame. A host calls this once per frame while it reports `true`.
pub fn tick(&mut self, delta_ms: u32) -> bool {
if !self.is_editing {
return false;
}
let running = self.cursor_blink.tick(delta_ms);
if running {
self.base.request_redraw();
}
running
}
/// Returns whether the editor is in edit mode.
pub fn is_editing(&self) -> bool {
self.is_editing
}
/// Returns the current text content.
pub fn text(&self) -> &str {
&self.text
}
/// Sets the text content.
pub fn set_text(&mut self, text: &str) {
let before = self.text.clone();
self.text = text.to_string();
if !self.restoring_history && before != self.text {
*self.history_target.borrow_mut() = self.text.clone();
self.undo_stack.push(Box::new(TextSnapshotCommand::new(
self.history_target.clone(),
before,
self.text.clone(),
"inplace_editor_text",
)));
}
self.cursor_position = self.text.chars().count();
self.base.request_redraw();
}
/// Steps back one committed edit and returns `true`, or `false` when there is
/// nothing to undo.
///
/// Only committed values are undoable: text edited in the box but not yet
/// accepted is not on the stack. The cursor is moved to the end of the
/// restored text.
pub fn undo(&mut self) -> bool {
if self.undo_stack.undo().is_err() {
return false;
}
self.restore_history_text();
true
}
/// Steps forward one undone edit and returns `true`, or `false` when there is
/// nothing to redo. Behaviour matches [`InplaceEditor::undo`].
pub fn redo(&mut self) -> bool {
if self.undo_stack.redo().is_err() {
return false;
}
self.restore_history_text();
true
}
/// Returns `true` if [`InplaceEditor::undo`] would change the value.
pub fn can_undo(&self) -> bool {
self.undo_stack.can_undo()
}
/// Returns `true` if [`InplaceEditor::redo`] would change the value.
pub fn can_redo(&self) -> bool {
self.undo_stack.can_redo()
}
fn restore_history_text(&mut self) {
self.restoring_history = true;
self.text = self.history_target.borrow().clone();
self.cursor_position = self.text.chars().count();
self.restoring_history = false;
self.base.request_redraw();
}
/// Sets the font size.
pub fn set_font_size(&mut self, size: f32) {
self.font_size = size.max(4.0);
self.base.request_redraw();
}
/// Returns the font size.
pub fn font_size(&self) -> f32 {
self.font_size
}
/// Sets the padding around the text.
pub fn set_padding(&mut self, padding: i32) {
self.padding = padding.max(0);
self.base.request_redraw();
}
/// Returns the padding.
pub fn padding(&self) -> i32 {
self.padding
}
/// The field the control actually paints.
///
/// # Why the field is not the control's rectangle
///
/// An in-place editor is a text field shown only while a cell is being edited, so it is
/// [`dimensions::TEXT_FIELD_MIN_HEIGHT`] tall, full width, centred — the same shape the
/// rest of the crate's input controls draw. Painting `geometry()` made a 240x120 census
/// cell a 240x120 box, and the value inherited the oversized box through the
/// `padding + font_size` anchor. Everything the control paints **and the double-click it
/// answers** is placed from this one box.
fn field_rect(&self) -> Rect {
ControlMetrics::full_width_band(self.geometry(), dimensions::TEXT_FIELD_MIN_HEIGHT)
}
/// Inserts a character at the cursor position.
fn insert_char(&mut self, c: char) {
if c == '\u{7f}' {
// Delete (backward)
if self.cursor_position > 0 {
let mut chars: Vec<char> = self.text.chars().collect();
chars.remove(self.cursor_position - 1);
let next = chars.into_iter().collect::<String>();
let next_cursor = self.cursor_position.saturating_sub(1);
self.set_text(&next);
self.cursor_position = next_cursor.min(self.text.chars().count());
self.base.request_redraw();
}
} else if c == '\u{ffff}' {
// Forward delete
if self.cursor_position < self.text.chars().count() {
let mut chars: Vec<char> = self.text.chars().collect();
chars.remove(self.cursor_position);
let next = chars.into_iter().collect::<String>();
self.set_text(&next);
self.cursor_position = self.cursor_position.min(self.text.chars().count());
self.base.request_redraw();
}
} else {
let mut chars: Vec<char> = self.text.chars().collect();
chars.insert(self.cursor_position, c);
let next = chars.into_iter().collect::<String>();
self.set_text(&next);
self.cursor_position = self.text.chars().count();
self.base.request_redraw();
}
}
/// Moves the cursor left by one character.
fn cursor_left(&mut self) {
if self.cursor_position > 0 {
self.cursor_position -= 1;
self.base.request_redraw();
}
}
/// Moves the cursor right by one character.
fn cursor_right(&mut self) {
let char_count = self.text.chars().count();
if self.cursor_position < char_count {
self.cursor_position += 1;
self.base.request_redraw();
}
}
}
impl Widget for InplaceEditor {
fn base(&self) -> &BaseWidget {
&self.base
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> crate::core::Size {
crate::core::Size::new(200, 28)
}
impl_draw_bridge!();
impl_widget_property_hooks!();
// The caret blink is driven through the trait so the animation bus reaches it.
fn tick(&mut self, delta_ms: u32) -> bool {
InplaceEditor::tick(self, delta_ms)
}
}
/// `InplaceEditor`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_input.in.rs` / `access_write_input.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before. `editing` maps onto the
/// widget's edit mode: writing `true` starts an edit, writing `false` cancels it,
/// matching the legacy arm.
impl WidgetProperties for InplaceEditor {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"text" => Ok(CapabilityValue::String(self.text().to_string())),
"editing" => Ok(CapabilityValue::Bool(self.is_editing())),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"text" => {
self.set_text(&expect_string(value)?);
Ok(())
}
"editing" => {
if expect_bool(value)? {
self.start_edit();
} else {
self.finish_edit(false);
}
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of!["text", "editing", BASE_PROPERTY_NAMES]
}
/// Runs one of the commands `inplace_editor` publishes.
///
/// The two actions enter and leave edit mode through the control's own methods, so
/// the guard against a redundant start, the revert-on-cancel and the
/// `edit_accepted` / `edit_cancelled` signals all stay in one place. `finish_editing`
/// accepts, which is the meaning of the name: a caller that wants the revert spells
/// it as `set("editing", false)`, where the payload says so. `set_text` assigns the
/// text and is answered through the property route.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"start_editing" => {
self.start_edit();
Ok(())
}
"finish_editing" => {
self.finish_edit(true);
Ok(())
}
"set_text" => Err(CapabilityAccessError::OutOfRange),
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl Draw for InplaceEditor {
fn draw(&mut self, context: &mut RenderContext) {
// The **field**, not the control's rectangle.
//
// An in-place editor is a text field: it is `TEXT_FIELD_MIN_HEIGHT` tall, full
// width, centred in the area it is given, exactly as every other field in this crate
// is. Painting `geometry()` made a 240x120 census cell a 240x120 box, and the text
// and caret below inherited that — the value sat `padding + font_size` down from an
// edge that was itself not the field's. The hit test reads the same box, so the
// double-click target is the visible field.
let rect = self.field_rect();
let font = Font::new("sans-serif", self.font_size, false, false);
// Chrome colours resolve explicit style first, then the theme's resolved style for
// this control, and only then a literal. The theme step is what makes an appearance
// switch visible; both modes' fill, border, cursor and text used to be hardcoded
// literals, so light and dark rendered identically.
//
// The theme reads take and release the global manager's lock internally, so no guard
// is held across the draw (the mutex is not re-entrant).
let style = self.base.style().clone();
let theme = crate::style::resolved_theme_style("inplace_editor");
// `inplace_editor` classifies as `Input`, which *does* carry a surface
// (`Colors::input_background`), so the resolved background is already a visible step
// from the window. It falls back to the theme's `background` when a theme supplies
// none, which is what reaches this arm at all.
let window_fill = crate::style::theme_manager()
.current_theme()
.map(|active| active.colors.background)
.unwrap_or(Color::WHITE);
let ink = style
.text_color
.or_else(|| theme.as_ref().and_then(|t| t.text_color))
.unwrap_or(Color::rgb(50, 50, 50));
// The accent is the theme's `primary`: the hue a theme is expected to vary most, so
// the edit-mode frame follows the appearance rather than staying a literal blue.
let accent = crate::style::theme_manager()
.current_theme()
.map(|active| active.colors.primary)
.unwrap_or(Color::rgb(0, 120, 255));
let surface = match style
.background_color
.or_else(|| theme.as_ref().and_then(|t| t.background_color))
{
Some(resolved) if resolved != window_fill => resolved,
_ => window_fill.blend(&ink, 0.08),
};
let border = style
.border_color
.or_else(|| theme.as_ref().and_then(|t| t.border_color))
.unwrap_or_else(|| surface.blend(&ink, 0.25));
if self.is_editing {
// Draw editing mode
context.fill_rect(rect, surface);
context.draw_rect_stroke(rect, accent, 2);
// Draw text, on the field's own line box. The old anchor was
// `rect.y + padding + font_size`, which put the glyph origin a *font size* below
// the field's top edge — the text was drawn on the row after the one it belonged
// to. `context.text_line` returns the field's line box, so the value is centred
// in the field rather than positioned by two unrelated offsets.
let text_x = rect.x + dimensions::TEXT_FIELD_PADDING_H as i32;
let line = context.text_line(rect, &font);
context.draw_text(
Point::new(text_x, line.y),
&self.text,
&font,
ink,
HorizontalAlignment::Left,
);
// Draw the caret, but only during the visible half of its cycle. The state comes from
// the control's `CursorBlink`, which `tick` advances; drawing it unconditionally was
// the "blinking cursor" that never blinked.
if self.cursor_blink.is_visible() {
let cursor_x = text_x + self.cursor_position as i32 * 8;
context.draw_line(
Point::new(cursor_x, line.y),
Point::new(cursor_x, line.y + line.height as i32),
ink.with_alpha_f32(0.8),
);
}
} else {
// Draw display mode
context.fill_rect(rect, surface);
context.draw_rect_stroke(rect, border, 1);
let text_x = rect.x + dimensions::TEXT_FIELD_PADDING_H as i32;
let line = context.text_line(rect, &font);
context.draw_text(
Point::new(text_x, line.y),
&self.text,
&font,
ink,
HorizontalAlignment::Left,
);
}
}
}
impl EventHandler for InplaceEditor {
fn handle_event(&mut self, event: &Event) {
if !self.base.is_enabled() {
return;
}
match event {
Event::MouseDoubleClick { pos, button } if *button == 1 => {
// Entering edit mode needs the double-click to land on the editor.
// Discarding the position meant a double-click anywhere in the window
// put this control into edit mode with no way for the user to cancel it.
//
// The test is against the **painted field**, not the control's rectangle:
// a double-click on the empty space below a 48 px field in a tall cell is on
// the window background, and starting an edit there would put the user into
// a mode they never asked for.
if self.field_rect().contains_point(*pos) {
self.start_edit();
}
}
Event::KeyPress { key, modifiers } => {
if !self.is_editing {
self.base.handle_event(event);
return;
}
match *key {
90 if *modifiers == 2 => {
let _ = self.undo();
}
89 if *modifiers == 2 => {
let _ = self.redo();
}
0x1B => {
// Escape - cancel
self.finish_edit(false);
}
0x0D | 0x09 => {
// Enter or Tab - accept
self.finish_edit(true);
}
0x08 => {
// Backspace
self.insert_char('\u{7f}');
}
0x2E => {
// Delete (forward)
self.insert_char('\u{ffff}');
}
0x25 => {
// Left arrow
self.cursor_left();
}
0x27 => {
// Right arrow
self.cursor_right();
}
_ => {
// Printable characters
if let Some(c) = char::from_u32(*key) {
if c.is_alphanumeric() || c.is_whitespace() || c.is_ascii_punctuation()
{
self.insert_char(c);
}
}
}
}
}
_ => {
self.base.handle_event(event);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::Point;
#[test]
fn inplace_editor_initial_state() {
let ie = InplaceEditor::new("Hello", Rect::new(0, 0, 200, 30));
assert_eq!(ie.text(), "Hello");
assert!(!ie.is_editing());
assert!((ie.font_size() - 14.0).abs() < 0.01);
assert_eq!(ie.padding(), 4);
assert_eq!(ie.kind(), WidgetKind::InplaceEditor);
}
/// The edit caret blinks only in edit mode.
///
/// The module has always documented a "blinking cursor", but the caret was a solid line and
/// nothing ever scheduled another frame. This pins the two halves of the lifecycle: display mode
/// owes no frame, edit mode keeps blinking, and finishing the edit stops it.
#[test]
fn the_edit_caret_blinks_only_in_edit_mode() {
let mut ie = InplaceEditor::new("Hello", Rect::new(0, 0, 200, 30));
assert!(!ie.tick(10_000), "display mode has no caret to animate");
ie.start_edit();
assert!(ie.tick(0), "entering edit mode starts the blink");
for _ in 0..10 {
assert!(ie.tick(500), "a blink is periodic and never settles");
}
ie.finish_edit(true);
assert!(!ie.tick(500), "leaving edit mode stops the blink");
}
#[test]
fn inplace_editor_set_text() {
let mut ie = InplaceEditor::new("Hello", Rect::new(0, 0, 200, 30));
ie.set_text("World");
assert_eq!(ie.text(), "World");
}
#[test]
fn inplace_editor_start_and_finish_edit_accept() {
let mut ie = InplaceEditor::new("Hello", Rect::new(0, 0, 200, 30));
let accepted = std::sync::Arc::new(std::sync::Mutex::new(None));
let accepted_clone = accepted.clone();
ie.edit_accepted.connect(move |text| {
*accepted_clone.lock().unwrap() = Some((*text).clone());
});
ie.start_edit();
assert!(ie.is_editing());
ie.set_text("Hello World");
ie.finish_edit(true);
assert!(!ie.is_editing());
assert_eq!(ie.text(), "Hello World");
assert_eq!(*accepted.lock().unwrap(), Some("Hello World".to_string()));
}
#[test]
fn inplace_editor_start_and_finish_edit_cancel() {
let mut ie = InplaceEditor::new("Hello", Rect::new(0, 0, 200, 30));
let cancelled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let cancelled_clone = cancelled.clone();
ie.edit_cancelled.connect(move || {
cancelled_clone.store(true, std::sync::atomic::Ordering::SeqCst);
});
ie.start_edit();
assert!(ie.is_editing());
ie.set_text("Modified Text");
ie.finish_edit(false);
assert!(!ie.is_editing());
assert_eq!(ie.text(), "Hello"); // Should revert to original
assert!(cancelled.load(std::sync::atomic::Ordering::SeqCst));
}
#[test]
fn inplace_editor_double_click_starts_edit() {
let mut ie = InplaceEditor::new("Hello", Rect::new(0, 0, 200, 30));
ie.handle_event(&Event::MouseDoubleClick { pos: Point::new(50, 15), button: 1 });
assert!(ie.is_editing());
}
/// The field is a full-width band one text-field height tall, centred in the control.
///
/// The control painted its whole rectangle, so a 240x120 census cell drew a 240x120 box
/// and the value was anchored from its oversized top edge.
#[test]
fn the_field_is_a_text_field_height_in_any_rectangle() {
for height in [48u32, 120, 300] {
let ie = InplaceEditor::new("Sample", Rect::new(0, 0, 240, height));
let field = ie.field_rect();
assert_eq!(
field.height,
dimensions::TEXT_FIELD_MIN_HEIGHT,
"at control height {height}"
);
assert_eq!(field.width, 240, "the field spans the control's width");
assert_eq!(field.y, (height - field.height) as i32 / 2, "at control height {height}");
}
let short = InplaceEditor::new("Sample", Rect::new(0, 0, 240, 20));
assert_eq!(short.field_rect().height, 20, "a short control clamps the field");
}
/// A double-click below the field does not start an edit.
///
/// With the field centred in a 120 px cell, a double-click inside the control's
/// rectangle but below the drawn band is on the window background; starting an edit
/// there puts the user into a mode they never asked for.
#[test]
fn a_double_click_below_the_drawn_field_does_not_start_an_edit() {
let mut ie = InplaceEditor::new("Hello", Rect::new(0, 0, 240, 120));
let field = ie.field_rect();
ie.handle_event(&Event::MouseDoubleClick {
pos: Point::new(field.x + 10, field.y + field.height as i32 / 2),
button: 1,
});
assert!(ie.is_editing(), "a double-click on the drawn field starts an edit");
let mut ie = InplaceEditor::new("Hello", Rect::new(0, 0, 240, 120));
ie.handle_event(&Event::MouseDoubleClick {
pos: Point::new(field.x + 10, field.y + field.height as i32 + 40),
button: 1,
});
assert!(!ie.is_editing(), "a double-click below the drawn field must not");
}
/// The value is drawn on the field's own line box, not a font size below its top edge.
///
/// The old anchor was `rect.y + padding + font_size`, which put the glyph origin a whole
/// font size down from the field's top — the value was drawn on the row *after* the one
/// it belonged to, and the caret spanned a different band from the text.
///
/// # Why the check is on the ink
///
/// The value is no longer a `<text>` element carrying a `y`: the backend emits the same
/// `font8x8` rectangles the software rasteriser fills, as subpaths of a single `<path>`
/// (see `crate::widget::svg::text_ink_box`). The string is absent from the document, and
/// the ink box is the stronger witness anyway — it is where the glyphs landed, not what an
/// element claimed.
#[cfg(not(alloc_frugal))]
#[test]
fn the_value_sits_inside_the_field() {
let mut ie = InplaceEditor::new("Sample", Rect::new(0, 0, 240, 120));
ie.start_edit();
let svg = crate::widget::svg::render_to_svg(&mut ie);
let field = ie.field_rect();
let (_, top, _, bottom) = crate::widget::svg::text_ink_box(&svg)
.expect("an editor with text draws it as glyph geometry");
assert!(top >= field.y, "the value starts inside the field: y={top}, field={field:?}");
assert!(
bottom <= field.y + field.height as i32,
"and above the field's bottom edge: y={bottom}, field={field:?}"
);
}
#[test]
fn inplace_editor_escape_cancels_edit() {
let mut ie = InplaceEditor::new("Hello", Rect::new(0, 0, 200, 30));
ie.start_edit();
ie.set_text("Changed");
ie.handle_event(&Event::KeyPress {
key: 0x1B, // Escape
modifiers: 0,
});
assert!(!ie.is_editing());
assert_eq!(ie.text(), "Hello");
}
#[test]
fn inplace_editor_enter_accepts_edit() {
let mut ie = InplaceEditor::new("Hello", Rect::new(0, 0, 200, 30));
ie.start_edit();
ie.set_text("Accepted");
ie.handle_event(&Event::KeyPress {
key: 0x0D, // Enter
modifiers: 0,
});
assert!(!ie.is_editing());
assert_eq!(ie.text(), "Accepted");
}
#[test]
fn inplace_editor_set_font_size_and_padding() {
let mut ie = InplaceEditor::new("Test", Rect::new(0, 0, 200, 30));
ie.set_font_size(18.0);
assert!((ie.font_size() - 18.0).abs() < 0.01);
ie.set_font_size(0.0); // Should clamp
assert!((ie.font_size() - 4.0).abs() < 0.01);
ie.set_padding(8);
assert_eq!(ie.padding(), 8);
ie.set_padding(-5); // Should clamp to 0
assert_eq!(ie.padding(), 0);
}
#[test]
fn inplace_editor_insert_characters() {
let mut ie = InplaceEditor::new("", Rect::new(0, 0, 200, 30));
ie.start_edit();
// Simulate typing
ie.insert_char('A');
ie.insert_char('B');
ie.insert_char('C');
assert_eq!(ie.text(), "ABC");
assert_eq!(ie.cursor_position, 3);
// Backspace
ie.insert_char('\u{7f}');
assert_eq!(ie.text(), "AB");
assert_eq!(ie.cursor_position, 2);
}
}