1
//! Single-line text input widget with placeholder and two-way data binding.
2
//!
3
//! The main entry point is [`TextInput`], which holds the editable state
4
//! ([`TextInputState`]) together with per-platform default styles.  Call
5
//! [`TextInput::dom()`] to obtain a renderable [`Dom`] node.
6
//!
7
//! The widget is a `contenteditable` host: the container carries the flag and
8
//! the tab index, so the engine's `TextEditManager` owns the caret, the
9
//! selection and the buffer. Caret and selection are display-list items driven
10
//! by that manager — the widget contributes no cursor node — and edits run
11
//! through `record_text_input` / `apply_text_changeset`. [`TextInputState`] is a
12
//! *mirror* of that state, refreshed from the engine's changesets so the public
13
//! callbacks keep the shape existing hosts bind against.
14
//!
15
//! Both the value and the placeholder are `<p>` blocks wrapping a bare text
16
//! node: a [`NodeType::Text`](azul_core::dom::NodeType::Text) node is always
17
//! inline-level and owns no rect, so box-model properties on one are inert and
18
//! nothing bounds or clips the line.
19
//!
20
//! For higher-level text-input management (IME, clipboard, undo) see
21
//! `layout/src/managers/text_input.rs`.
22

            
23
use alloc::{string::String, vec::Vec};
24

            
25
use azul_core::{
26
    callbacks::{CoreCallback, CoreCallbackData, Update},
27
    dom::{Dom, DomNodeId},
28
    refany::RefAny,
29
    task::OptionTimerId,
30
};
31
use azul_css::{css::BoxOrStatic, dynamic_selector::OptionCssPropertyWithConditionsVec};
32
#[allow(clippy::wildcard_imports)]
33
// widget/render module pulls in the css property/value types it builds with
34
use azul_css::{
35
    dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
36
    props::{
37
        basic::*,
38
        layout::*,
39
        property::{CssProperty, *},
40
        style::*,
41
    },
42
    OptionString, *,
43
};
44

            
45
use crate::callbacks::{Callback, CallbackInfo};
46

            
47
const BACKGROUND_COLOR: ColorU = ColorU {
48
    r: 255,
49
    g: 255,
50
    b: 255,
51
    a: 255,
52
}; // white
53
const COLOR_9B9B9B: ColorU = ColorU {
54
    r: 155,
55
    g: 155,
56
    b: 155,
57
    a: 255,
58
}; // #9b9b9b
59
const COLOR_4C4C4C: ColorU = ColorU {
60
    r: 76,
61
    g: 76,
62
    b: 76,
63
    a: 255,
64
}; // #4C4C4C
65

            
66
const BACKGROUND_THEME_LIGHT: &[StyleBackgroundContent] =
67
    &[StyleBackgroundContent::Color(BACKGROUND_COLOR)];
68
const BACKGROUND_COLOR_LIGHT: StyleBackgroundContentVec =
69
    StyleBackgroundContentVec::from_const_slice(BACKGROUND_THEME_LIGHT);
70

            
71
const SANS_SERIF_STR: &str = "system:ui";
72
const SANS_SERIF: AzString = AzString::from_const_str(SANS_SERIF_STR);
73
const SANS_SERIF_FAMILIES: &[StyleFontFamily] = &[StyleFontFamily::System(SANS_SERIF)];
74
const SANS_SERIF_FAMILY: StyleFontFamilyVec =
75
    StyleFontFamilyVec::from_const_slice(SANS_SERIF_FAMILIES);
76

            
77
// -- container style
78

            
79
/// Minimum height of the field (border box), every platform: one line of the
80
/// 11 px UI font plus the chrome. With no text the value `<p>` has no line box
81
/// and the placeholder is positioned out of flow, so without this an EMPTY
82
/// field collapsed to its padding + border (4 px) — it used to be propped up
83
/// by the UA `<p>` margin that `widget_p` now resets.
84
const TEXT_INPUT_MIN_HEIGHT_PX: isize = 22;
85

            
86
#[cfg(target_os = "windows")]
87
pub(crate) static TEXT_INPUT_CONTAINER_PROPS: &[CssPropertyWithConditions] = &[
88
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
89
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Text)),
90
    CssPropertyWithConditions::simple(CssProperty::const_box_sizing(LayoutBoxSizing::BorderBox)),
91
    CssPropertyWithConditions::simple(CssProperty::const_min_height(LayoutMinHeight::const_px(
92
        TEXT_INPUT_MIN_HEIGHT_PX,
93
    ))),
94
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
95
    CssPropertyWithConditions::simple(CssProperty::const_background_content(
96
        BACKGROUND_COLOR_LIGHT,
97
    )),
98
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
99
        inner: COLOR_4C4C4C,
100
    })),
101
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
102
        LayoutPaddingLeft::const_px(2),
103
    )),
104
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
105
        LayoutPaddingRight::const_px(2),
106
    )),
107
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
108
        1,
109
    ))),
110
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
111
        LayoutPaddingBottom::const_px(1),
112
    )),
113
    // border: 1px solid #484c52;
114
    CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
115
        LayoutBorderTopWidth::const_px(1),
116
    )),
117
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
118
        LayoutBorderBottomWidth::const_px(1),
119
    )),
120
    CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
121
        LayoutBorderLeftWidth::const_px(1),
122
    )),
123
    CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
124
        LayoutBorderRightWidth::const_px(1),
125
    )),
126
    CssPropertyWithConditions::simple(CssProperty::const_border_top_style(StyleBorderTopStyle {
127
        inner: BorderStyle::Inset,
128
    })),
129
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
130
        StyleBorderBottomStyle {
131
            inner: BorderStyle::Inset,
132
        },
133
    )),
134
    CssPropertyWithConditions::simple(CssProperty::const_border_left_style(StyleBorderLeftStyle {
135
        inner: BorderStyle::Inset,
136
    })),
137
    CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
138
        StyleBorderRightStyle {
139
            inner: BorderStyle::Inset,
140
        },
141
    )),
142
    CssPropertyWithConditions::simple(CssProperty::const_border_top_color(StyleBorderTopColor {
143
        inner: COLOR_9B9B9B,
144
    })),
145
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
146
        StyleBorderBottomColor {
147
            inner: COLOR_9B9B9B,
148
        },
149
    )),
150
    CssPropertyWithConditions::simple(CssProperty::const_border_left_color(StyleBorderLeftColor {
151
        inner: COLOR_9B9B9B,
152
    })),
153
    CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
154
        StyleBorderRightColor {
155
            inner: COLOR_9B9B9B,
156
        },
157
    )),
158
    // A single-line field CLIPS vertically but SCROLLS horizontally WITHOUT a
159
    // scrollbar, so the caret stays visible once the text runs past the right
160
    // edge. `overflow-x: hidden` clipped the caret (the "append-only" feel the
161
    // user hit); `auto` makes the container a scroll box the caret-reveal
162
    // (`scroll_selection_into_view`) can shift, and `scrollbar-width: none` keeps
163
    // a one-line input from sprouting a horizontal bar under it.
164
    CssPropertyWithConditions::simple(CssProperty::const_overflow_x(LayoutOverflow::Auto)),
165
    CssPropertyWithConditions::simple(CssProperty::const_overflow_y(LayoutOverflow::Hidden)),
166
    CssPropertyWithConditions::simple(CssProperty::ScrollbarWidth(
167
        LayoutScrollbarWidthValue::Exact(LayoutScrollbarWidth::None),
168
    )),
169
    // The value line is centred in the field's `min-height` — which needs the
170
    // field to BE a flex container. Without this the box laid out as a block,
171
    // `justify-content` did nothing, and the value sat at the top edge with the
172
    // bottom border a line's height below it (the number input on the frontpage
173
    // screenshot looked like it had a rule drawn through it).
174
    CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
175
        LayoutDisplay::Flex,
176
    ))),
177
    CssPropertyWithConditions::simple(CssProperty::FlexDirection(LayoutFlexDirectionValue::Exact(
178
        LayoutFlexDirection::Column,
179
    ))),
180
    CssPropertyWithConditions::simple(CssProperty::const_justify_content(
181
        LayoutJustifyContent::Center,
182
    )),
183
    // Hover and focus border states are NOT here. They live in the theme
184
    // modules (`flat::FIELD_BORDER_STATES`, `flora::FIELD_BORDER_STATES`) and
185
    // are appended by `flat::text_input` / `flora::text_input`, because the
186
    // dark half of each pair needs the theme's `DARK_ACC` — a colour this file
187
    // cannot see. Declared here, they could only ever name the light-mode
188
    // colours, which is why a hovered field kept its light ring on a dark
189
    // surface.
190
    //
191
    // The Windows-only grey hover ring (#4c4c4c) went with them: which colour
192
    // rings the field is the theme's decision now, and neither theme draws a
193
    // platform distinction.
194
];
195

            
196
#[cfg(target_os = "linux")]
197
pub(crate) static TEXT_INPUT_CONTAINER_PROPS: &[CssPropertyWithConditions] = &[
198
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
199
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Text)),
200
    CssPropertyWithConditions::simple(CssProperty::const_box_sizing(LayoutBoxSizing::BorderBox)),
201
    CssPropertyWithConditions::simple(CssProperty::const_min_height(LayoutMinHeight::const_px(
202
        TEXT_INPUT_MIN_HEIGHT_PX,
203
    ))),
204
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(11))),
205
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
206
    CssPropertyWithConditions::simple(CssProperty::const_background_content(
207
        BACKGROUND_COLOR_LIGHT,
208
    )),
209
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
210
        inner: COLOR_4C4C4C,
211
    })),
212
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
213
        LayoutPaddingLeft::const_px(2),
214
    )),
215
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
216
        LayoutPaddingRight::const_px(2),
217
    )),
218
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
219
        1,
220
    ))),
221
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
222
        LayoutPaddingBottom::const_px(1),
223
    )),
224
    // border: 1px solid #484c52;
225
    CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
226
        LayoutBorderTopWidth::const_px(1),
227
    )),
228
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
229
        LayoutBorderBottomWidth::const_px(1),
230
    )),
231
    CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
232
        LayoutBorderLeftWidth::const_px(1),
233
    )),
234
    CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
235
        LayoutBorderRightWidth::const_px(1),
236
    )),
237
    CssPropertyWithConditions::simple(CssProperty::const_border_top_style(StyleBorderTopStyle {
238
        inner: BorderStyle::Inset,
239
    })),
240
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
241
        StyleBorderBottomStyle {
242
            inner: BorderStyle::Inset,
243
        },
244
    )),
245
    CssPropertyWithConditions::simple(CssProperty::const_border_left_style(StyleBorderLeftStyle {
246
        inner: BorderStyle::Inset,
247
    })),
248
    CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
249
        StyleBorderRightStyle {
250
            inner: BorderStyle::Inset,
251
        },
252
    )),
253
    CssPropertyWithConditions::simple(CssProperty::const_border_top_color(StyleBorderTopColor {
254
        inner: COLOR_9B9B9B,
255
    })),
256
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
257
        StyleBorderBottomColor {
258
            inner: COLOR_9B9B9B,
259
        },
260
    )),
261
    CssPropertyWithConditions::simple(CssProperty::const_border_left_color(StyleBorderLeftColor {
262
        inner: COLOR_9B9B9B,
263
    })),
264
    CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
265
        StyleBorderRightColor {
266
            inner: COLOR_9B9B9B,
267
        },
268
    )),
269
    CssPropertyWithConditions::simple(CssProperty::const_overflow_x(LayoutOverflow::Hidden)),
270
    CssPropertyWithConditions::simple(CssProperty::const_overflow_y(LayoutOverflow::Hidden)),
271
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Left)),
272
    // The value line is centred in the field's `min-height` — which needs the
273
    // field to BE a flex container. Without this the box laid out as a block,
274
    // `justify-content` did nothing, and the value sat at the top edge with the
275
    // bottom border a line's height below it (the number input on the frontpage
276
    // screenshot looked like it had a rule drawn through it).
277
    CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
278
        LayoutDisplay::Flex,
279
    ))),
280
    CssPropertyWithConditions::simple(CssProperty::FlexDirection(LayoutFlexDirectionValue::Exact(
281
        LayoutFlexDirection::Column,
282
    ))),
283
    CssPropertyWithConditions::simple(CssProperty::const_justify_content(
284
        LayoutJustifyContent::Center,
285
    )),
286
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SANS_SERIF_FAMILY)),
287
    // Hover and focus border states are NOT here. They live in the theme
288
    // modules (`flat::FIELD_BORDER_STATES`, `flora::FIELD_BORDER_STATES`) and
289
    // are appended by `flat::text_input` / `flora::text_input`, because the
290
    // dark half of each pair needs the theme's `DARK_ACC` — a colour this file
291
    // cannot see. Declared here, they could only ever name the light-mode
292
    // colours, which is why a hovered field kept its light ring on a dark
293
    // surface.
294
];
295

            
296
// Mobile (Android / iOS) inherit the macOS-style container — same flex
297
// box-sizing and background; touch-target padding is the user's concern.
298
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
299
pub(crate) static TEXT_INPUT_CONTAINER_PROPS: &[CssPropertyWithConditions] = &[
300
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
301
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Text)),
302
    CssPropertyWithConditions::simple(CssProperty::const_box_sizing(LayoutBoxSizing::BorderBox)),
303
    CssPropertyWithConditions::simple(CssProperty::const_min_height(LayoutMinHeight::const_px(
304
        TEXT_INPUT_MIN_HEIGHT_PX,
305
    ))),
306
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
307
    CssPropertyWithConditions::simple(CssProperty::const_background_content(
308
        BACKGROUND_COLOR_LIGHT,
309
    )),
310
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
311
        inner: COLOR_4C4C4C,
312
    })),
313
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
314
        LayoutPaddingLeft::const_px(2),
315
    )),
316
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
317
        LayoutPaddingRight::const_px(2),
318
    )),
319
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
320
        1,
321
    ))),
322
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
323
        LayoutPaddingBottom::const_px(1),
324
    )),
325
    // border: 1px solid #484c52;
326
    CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
327
        LayoutBorderTopWidth::const_px(1),
328
    )),
329
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
330
        LayoutBorderBottomWidth::const_px(1),
331
    )),
332
    CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
333
        LayoutBorderLeftWidth::const_px(1),
334
    )),
335
    CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
336
        LayoutBorderRightWidth::const_px(1),
337
    )),
338
    CssPropertyWithConditions::simple(CssProperty::const_border_top_style(StyleBorderTopStyle {
339
        inner: BorderStyle::Inset,
340
    })),
341
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
342
        StyleBorderBottomStyle {
343
            inner: BorderStyle::Inset,
344
        },
345
    )),
346
    CssPropertyWithConditions::simple(CssProperty::const_border_left_style(StyleBorderLeftStyle {
347
        inner: BorderStyle::Inset,
348
    })),
349
    CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
350
        StyleBorderRightStyle {
351
            inner: BorderStyle::Inset,
352
        },
353
    )),
354
    CssPropertyWithConditions::simple(CssProperty::const_border_top_color(StyleBorderTopColor {
355
        inner: COLOR_9B9B9B,
356
    })),
357
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
358
        StyleBorderBottomColor {
359
            inner: COLOR_9B9B9B,
360
        },
361
    )),
362
    CssPropertyWithConditions::simple(CssProperty::const_border_left_color(StyleBorderLeftColor {
363
        inner: COLOR_9B9B9B,
364
    })),
365
    CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
366
        StyleBorderRightColor {
367
            inner: COLOR_9B9B9B,
368
        },
369
    )),
370
    CssPropertyWithConditions::simple(CssProperty::const_overflow_x(LayoutOverflow::Hidden)),
371
    CssPropertyWithConditions::simple(CssProperty::const_overflow_y(LayoutOverflow::Hidden)),
372
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Left)),
373
    // The value line is centred in the field's `min-height` — which needs the
374
    // field to BE a flex container. Without this the box laid out as a block,
375
    // `justify-content` did nothing, and the value sat at the top edge with the
376
    // bottom border a line's height below it (the number input on the frontpage
377
    // screenshot looked like it had a rule drawn through it).
378
    CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
379
        LayoutDisplay::Flex,
380
    ))),
381
    CssPropertyWithConditions::simple(CssProperty::FlexDirection(LayoutFlexDirectionValue::Exact(
382
        LayoutFlexDirection::Column,
383
    ))),
384
    CssPropertyWithConditions::simple(CssProperty::const_justify_content(
385
        LayoutJustifyContent::Center,
386
    )),
387
    // Hover and focus border states are NOT here. They live in the theme
388
    // modules (`flat::FIELD_BORDER_STATES`, `flora::FIELD_BORDER_STATES`) and
389
    // are appended by `flat::text_input` / `flora::text_input`, because the
390
    // dark half of each pair needs the theme's `DARK_ACC` — a colour this file
391
    // cannot see. Declared here, they could only ever name the light-mode
392
    // colours, which is why a hovered field kept its light ring on a dark
393
    // surface.
394
];
395

            
396
// -- label style
397
//
398
// The label is the `<p>` block wrapping the value text, so it is the box that
399
// bounds the line and clips against the container's `overflow: hidden`.
400
// `white-space: pre` keeps a single-line field on one line and preserves the
401
// spaces the user typed.
402

            
403
#[cfg(target_os = "windows")]
404
pub(crate) static TEXT_INPUT_LABEL_PROPS: &[CssPropertyWithConditions] = &[
405
    // The PROMPT's own colour, via the real `::placeholder` cascade. The
406
    // engine paints the prompt with the value line's style, overridden by
407
    // whatever `::placeholder` declares - so this is the widget's default
408
    // and any app rule (`.my-field::placeholder { color: ... }`) wins over
409
    // it exactly like normal CSS.
410
    CssPropertyWithConditions::on_placeholder(CssProperty::const_text_color(StyleTextColor {
411
        inner: COLOR_9B9B9B,
412
    })),
413
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
414
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
415
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
416
    // The value line SCROLLS horizontally (no visible bar) so the caret stays
417
    // in view once the text runs past the right edge. This is where the scroll
418
    // MUST live: the container is a block box this value `<p>` fills exactly
419
    // (394 px in a 400 px field), so the overflowing line is INSIDE this box,
420
    // not the container's. `overflow-x: hidden` trapped it and the field went
421
    // append-only — the caret walked off the right edge and new characters were
422
    // invisible. `auto` makes this the horizontal scroll box the caret-reveal
423
    // (`scroll_selection_into_view` → `find_scrollable_ancestor`) shifts to
424
    // follow the caret; `scrollbar-width: none` keeps a one-line field from
425
    // reserving vertical space for a horizontal bar. `white-space: pre` keeps
426
    // the value on one line so it overflows horizontally rather than wrapping.
427
    CssPropertyWithConditions::simple(CssProperty::const_overflow_x(LayoutOverflow::Auto)),
428
    CssPropertyWithConditions::simple(CssProperty::const_overflow_y(LayoutOverflow::Hidden)),
429
    CssPropertyWithConditions::simple(CssProperty::ScrollbarWidth(
430
        LayoutScrollbarWidthValue::Exact(LayoutScrollbarWidth::None),
431
    )),
432
    CssPropertyWithConditions::simple(CssProperty::WhiteSpace(StyleWhiteSpaceValue::Exact(
433
        StyleWhiteSpace::Pre,
434
    ))),
435
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(11))),
436
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
437
        inner: COLOR_4C4C4C,
438
    })),
439
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SANS_SERIF_FAMILY)),
440
];
441

            
442
#[cfg(target_os = "linux")]
443
pub(crate) static TEXT_INPUT_LABEL_PROPS: &[CssPropertyWithConditions] = &[
444
    // The PROMPT's own colour, via the real `::placeholder` cascade. The
445
    // engine paints the prompt with the value line's style, overridden by
446
    // whatever `::placeholder` declares - so this is the widget's default
447
    // and any app rule (`.my-field::placeholder { color: ... }`) wins over
448
    // it exactly like normal CSS.
449
    CssPropertyWithConditions::on_placeholder(CssProperty::const_text_color(StyleTextColor {
450
        inner: COLOR_9B9B9B,
451
    })),
452
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
453
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
454
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
455
    // The value line SCROLLS horizontally (no visible bar) so the caret stays
456
    // in view once the text runs past the right edge. This is where the scroll
457
    // MUST live: the container is a block box this value `<p>` fills exactly
458
    // (394 px in a 400 px field), so the overflowing line is INSIDE this box,
459
    // not the container's. `overflow-x: hidden` trapped it and the field went
460
    // append-only — the caret walked off the right edge and new characters were
461
    // invisible. `auto` makes this the horizontal scroll box the caret-reveal
462
    // (`scroll_selection_into_view` → `find_scrollable_ancestor`) shifts to
463
    // follow the caret; `scrollbar-width: none` keeps a one-line field from
464
    // reserving vertical space for a horizontal bar. `white-space: pre` keeps
465
    // the value on one line so it overflows horizontally rather than wrapping.
466
    CssPropertyWithConditions::simple(CssProperty::const_overflow_x(LayoutOverflow::Auto)),
467
    CssPropertyWithConditions::simple(CssProperty::const_overflow_y(LayoutOverflow::Hidden)),
468
    CssPropertyWithConditions::simple(CssProperty::ScrollbarWidth(
469
        LayoutScrollbarWidthValue::Exact(LayoutScrollbarWidth::None),
470
    )),
471
    CssPropertyWithConditions::simple(CssProperty::WhiteSpace(StyleWhiteSpaceValue::Exact(
472
        StyleWhiteSpace::Pre,
473
    ))),
474
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(11))),
475
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
476
        inner: COLOR_4C4C4C,
477
    })),
478
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SANS_SERIF_FAMILY)),
479
];
480

            
481
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
482
pub(crate) static TEXT_INPUT_LABEL_PROPS: &[CssPropertyWithConditions] = &[
483
    // The PROMPT's own colour, via the real `::placeholder` cascade. The
484
    // engine paints the prompt with the value line's style, overridden by
485
    // whatever `::placeholder` declares - so this is the widget's default
486
    // and any app rule (`.my-field::placeholder { color: ... }`) wins over
487
    // it exactly like normal CSS.
488
    CssPropertyWithConditions::on_placeholder(CssProperty::const_text_color(StyleTextColor {
489
        inner: COLOR_9B9B9B,
490
    })),
491
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
492
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
493
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
494
    // The value line SCROLLS horizontally (no visible bar) so the caret stays
495
    // in view once the text runs past the right edge. This is where the scroll
496
    // MUST live: the container is a block box this value `<p>` fills exactly
497
    // (394 px in a 400 px field), so the overflowing line is INSIDE this box,
498
    // not the container's. `overflow-x: hidden` trapped it and the field went
499
    // append-only — the caret walked off the right edge and new characters were
500
    // invisible. `auto` makes this the horizontal scroll box the caret-reveal
501
    // (`scroll_selection_into_view` → `find_scrollable_ancestor`) shifts to
502
    // follow the caret; `scrollbar-width: none` keeps a one-line field from
503
    // reserving vertical space for a horizontal bar. `white-space: pre` keeps
504
    // the value on one line so it overflows horizontally rather than wrapping.
505
    CssPropertyWithConditions::simple(CssProperty::const_overflow_x(LayoutOverflow::Auto)),
506
    CssPropertyWithConditions::simple(CssProperty::const_overflow_y(LayoutOverflow::Hidden)),
507
    CssPropertyWithConditions::simple(CssProperty::ScrollbarWidth(
508
        LayoutScrollbarWidthValue::Exact(LayoutScrollbarWidth::None),
509
    )),
510
    CssPropertyWithConditions::simple(CssProperty::WhiteSpace(StyleWhiteSpaceValue::Exact(
511
        StyleWhiteSpace::Pre,
512
    ))),
513
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(11))),
514
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
515
        inner: COLOR_4C4C4C,
516
    })),
517
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SANS_SERIF_FAMILY)),
518
];
519

            
520
/// Single-line text input widget with platform-native styling.
521
///
522
/// Use [`TextInput::create()`] to build an instance, configure it with the
523
/// `with_*` / `set_*` builder methods, and call [`TextInput::dom()`] to
524
/// obtain a renderable DOM tree.
525
#[derive(Debug, Clone, PartialEq, Eq)]
526
#[repr(C)]
527
pub struct TextInput {
528
    pub text_input_state: TextInputStateWrapper,
529
    pub container_style: OptionCssPropertyWithConditionsVec,
530
    pub label_style: OptionCssPropertyWithConditionsVec,
531
    /// What this control is CALLED, for assistive technology.
532
    ///
533
    /// Carried by the WIDGET so it knows at build time whether it was named;
534
    /// forwarded into the accessibility declaration it already builds.
535
    pub accessibility_name: OptionString,
536
    pub theme: crate::widgets::themes::OptionUiTheme,
537
}
538

            
539
/// Editable state of a text input (text buffer, cursor position, selection).
540
#[derive(Debug, Clone, PartialEq, Eq)]
541
#[repr(C)]
542
pub struct TextInputState {
543
    pub text: U32Vec, // Vec<char>
544
    pub placeholder: OptionString,
545
    pub max_len: usize,
546
    pub selection: OptionTextInputSelection,
547
    pub cursor_pos: usize,
548
}
549

            
550
/// [`TextInputState`] together with optional user callbacks and cursor animation state.
551
#[derive(Debug, Clone, PartialEq, Eq)]
552
#[repr(C)]
553
pub struct TextInputStateWrapper {
554
    pub inner: TextInputState,
555
    pub on_text_input: OptionTextInputOnTextInput,
556
    pub on_virtual_key_down: OptionTextInputOnVirtualKeyDown,
557
    pub on_focus_lost: OptionTextInputOnFocusLost,
558
    pub update_text_input_before_calling_focus_lost_fn: bool,
559
    pub update_text_input_before_calling_vk_down_fn: bool,
560
    pub cursor_animation: OptionTimerId,
561
}
562

            
563
/// Return value from a text-input callback indicating whether the framework
564
/// should update and whether the input was valid.
565
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
566
#[repr(C)]
567
pub struct OnTextInputReturn {
568
    pub update: Update,
569
    pub valid: TextInputValid,
570
}
571

            
572
/// Whether the text input accepted or rejected the most recent edit.
573
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
574
#[repr(C)]
575
pub enum TextInputValid {
576
    Yes,
577
    No,
578
}
579

            
580
// The text input field has a special return which specifies
581
// whether the text input should handle the character
582
pub type TextInputOnTextInputCallbackType =
583
    extern "C" fn(RefAny, CallbackInfo, TextInputState) -> OnTextInputReturn;
584
impl_widget_callback!(
585
    TextInputOnTextInput,
586
    OptionTextInputOnTextInput,
587
    TextInputOnTextInputCallback,
588
    TextInputOnTextInputCallbackType
589
);
590

            
591
azul_core::impl_managed_callback! {
592
    wrapper:        TextInputOnTextInputCallback,
593
    info_ty:        CallbackInfo,
594
    return_ty:      OnTextInputReturn,
595
    default_ret:    OnTextInputReturn { update: Update::DoNothing, valid: TextInputValid::Yes },
596
    invoker_static: TEXT_INPUT_ON_TEXT_INPUT_INVOKER,
597
    invoker_ty:     AzTextInputOnTextInputCallbackInvoker,
598
    thunk_fn:       az_text_input_on_text_input_callback_thunk,
599
    setter_fn:      AzApp_setTextInputOnTextInputCallbackInvoker,
600
    from_handle_fn: AzTextInputOnTextInputCallback_createFromHostHandle,
601
    extra_args:     [ state: TextInputState ],
602
}
603

            
604
pub type TextInputOnVirtualKeyDownCallbackType =
605
    extern "C" fn(RefAny, CallbackInfo, TextInputState) -> OnTextInputReturn;
606
impl_widget_callback!(
607
    TextInputOnVirtualKeyDown,
608
    OptionTextInputOnVirtualKeyDown,
609
    TextInputOnVirtualKeyDownCallback,
610
    TextInputOnVirtualKeyDownCallbackType
611
);
612

            
613
azul_core::impl_managed_callback! {
614
    wrapper:        TextInputOnVirtualKeyDownCallback,
615
    info_ty:        CallbackInfo,
616
    return_ty:      OnTextInputReturn,
617
    default_ret:    OnTextInputReturn { update: Update::DoNothing, valid: TextInputValid::Yes },
618
    invoker_static: TEXT_INPUT_ON_VIRTUAL_KEY_DOWN_INVOKER,
619
    invoker_ty:     AzTextInputOnVirtualKeyDownCallbackInvoker,
620
    thunk_fn:       az_text_input_on_virtual_key_down_callback_thunk,
621
    setter_fn:      AzApp_setTextInputOnVirtualKeyDownCallbackInvoker,
622
    from_handle_fn: AzTextInputOnVirtualKeyDownCallback_createFromHostHandle,
623
    extra_args:     [ state: TextInputState ],
624
}
625

            
626
pub type TextInputOnFocusLostCallbackType =
627
    extern "C" fn(RefAny, CallbackInfo, TextInputState) -> Update;
628
impl_widget_callback!(
629
    TextInputOnFocusLost,
630
    OptionTextInputOnFocusLost,
631
    TextInputOnFocusLostCallback,
632
    TextInputOnFocusLostCallbackType
633
);
634

            
635
azul_core::impl_managed_callback! {
636
    wrapper:        TextInputOnFocusLostCallback,
637
    info_ty:        CallbackInfo,
638
    return_ty:      Update,
639
    default_ret:    Update::DoNothing,
640
    invoker_static: TEXT_INPUT_ON_FOCUS_LOST_INVOKER,
641
    invoker_ty:     AzTextInputOnFocusLostCallbackInvoker,
642
    thunk_fn:       az_text_input_on_focus_lost_callback_thunk,
643
    setter_fn:      AzApp_setTextInputOnFocusLostCallbackInvoker,
644
    from_handle_fn: AzTextInputOnFocusLostCallback_createFromHostHandle,
645
    extra_args:     [ state: TextInputState ],
646
}
647
#[allow(variant_size_differences)]
648
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
649
// disparity accepted
650
#[derive(Copy, Debug, Clone, Hash, PartialEq, Eq)]
651
#[repr(C, u8)]
652
pub enum TextInputSelection {
653
    All,
654
    FromTo(TextInputSelectionRange),
655
}
656

            
657
azul_css::impl_option!(
658
    TextInputSelection,
659
    OptionTextInputSelection,
660
    copy = false,
661
    [Debug, Clone, Hash, PartialEq, Eq]
662
);
663

            
664
#[derive(Copy, Debug, Clone, Hash, PartialEq, Eq)]
665
#[repr(C)]
666
pub struct TextInputSelectionRange {
667
    pub dir_from: usize,
668
    pub dir_to: usize,
669
}
670

            
671
impl Default for TextInput {
672
1041
    fn default() -> Self {
673
1041
        Self {
674
1041
            text_input_state: TextInputStateWrapper::default(),
675
1041
            container_style: OptionCssPropertyWithConditionsVec::None,
676
1041
            label_style: OptionCssPropertyWithConditionsVec::None,
677
1041
            accessibility_name: OptionString::None,
678
1041
            theme: None.into(),
679
1041
        }
680
1041
    }
681
}
682

            
683
impl Default for TextInputState {
684
1228
    fn default() -> Self {
685
1228
        Self {
686
1228
            text: Vec::new().into(),
687
1228
            placeholder: None.into(),
688
1228
            // Unlimited, like a browser <input> without `maxlength`. The old
689
1228
            // default was an arbitrary 50 that nothing enforced; now that
690
1228
            // typing past `max_len` is vetoed (default_on_text_input), keeping
691
1228
            // 50 would have silently capped every existing field.
692
1228
            max_len: usize::MAX,
693
1228
            selection: None.into(),
694
1228
            cursor_pos: 0,
695
1228
        }
696
1228
    }
697
}
698

            
699
impl TextInputState {
700
    #[must_use]
701
204
    pub fn get_text(&self) -> String {
702
204
        self.text
703
204
            .iter()
704
51297
            .filter_map(|c| core::char::from_u32(*c))
705
204
            .collect()
706
204
    }
707
}
708

            
709
impl Default for TextInputStateWrapper {
710
1041
    fn default() -> Self {
711
1041
        Self {
712
1041
            inner: TextInputState::default(),
713
1041
            on_text_input: None.into(),
714
1041
            on_virtual_key_down: None.into(),
715
1041
            on_focus_lost: None.into(),
716
1041
            update_text_input_before_calling_focus_lost_fn: true,
717
1041
            update_text_input_before_calling_vk_down_fn: true,
718
1041
            cursor_animation: None.into(),
719
1041
        }
720
1041
    }
721
}
722

            
723
impl TextInput {
724
    /// The container style this widget renders with.
725
    ///
726
    /// `None` means no opinion, so the widget's default applies — the same
727
    /// answer both themes give, asked in one place.
728
    #[must_use]
729
806
    pub fn resolved_container_style(&self) -> CssPropertyWithConditionsVec {
730
806
        self.container_style
731
806
            .clone()
732
806
            .into_option()
733
806
            .unwrap_or_else(|| {
734
274
                CssPropertyWithConditionsVec::from_const_slice(TEXT_INPUT_CONTAINER_PROPS)
735
274
            })
736
806
    }
737

            
738
    /// The label style this widget renders with.
739
    ///
740
    /// `None` means no opinion, so the widget's default applies — the same
741
    /// answer both themes give, asked in one place.
742
    #[must_use]
743
787
    pub fn resolved_label_style(&self) -> CssPropertyWithConditionsVec {
744
787
        self.label_style.clone().into_option().unwrap_or_else(|| {
745
782
            CssPropertyWithConditionsVec::from_const_slice(TEXT_INPUT_LABEL_PROPS)
746
782
        })
747
787
    }
748

            
749
    /// Name this control for assistive technology.
750
    #[must_use]
751
105
    pub fn with_accessibility_name<S: Into<AzString>>(mut self, name: S) -> Self {
752
105
        self.accessibility_name = Some(name.into()).into();
753
105
        self
754
105
    }
755

            
756
    #[must_use]
757
484
    pub fn create() -> Self {
758
484
        Self::default()
759
484
    }
760

            
761
    #[must_use]
762
286
    pub fn with_text(mut self, text: AzString) -> Self {
763
286
        self.set_text(text);
764
286
        self
765
286
    }
766

            
767
    // owned AzString passed by value per the azul FFI / api.json setter convention.
768
    #[allow(clippy::needless_pass_by_value)]
769
351
    pub fn set_text(&mut self, text: AzString) {
770
351
        self.text_input_state.inner.text = text
771
351
            .as_str()
772
351
            .chars()
773
102053
            .map(|c| c as u32)
774
351
            .collect::<Vec<_>>()
775
351
            .into();
776
351
    }
777

            
778
    /// Pick the widget theme. Unset (`None`), the widget renders in the
779
    /// default theme (`crate::widgets::themes::UiTheme::default()`).
780
    pub const fn set_theme(&mut self, theme: crate::widgets::themes::UiTheme) {
781
        self.theme = crate::widgets::themes::OptionUiTheme::Some(theme);
782
    }
783

            
784
    /// [`Self::set_theme`] for the builder chain.
785
    #[must_use]
786
    pub const fn with_theme(mut self, theme: crate::widgets::themes::UiTheme) -> Self {
787
        self.set_theme(theme);
788
        self
789
    }
790

            
791
100
    pub fn set_placeholder(&mut self, placeholder: AzString) {
792
100
        self.text_input_state.inner.placeholder = Some(placeholder).into();
793
100
    }
794

            
795
    #[must_use]
796
77
    pub fn with_placeholder(mut self, placeholder: AzString) -> Self {
797
77
        self.set_placeholder(placeholder);
798
77
        self
799
77
    }
800

            
801
491
    pub fn set_on_text_input<C: Into<TextInputOnTextInputCallback>>(
802
491
        &mut self,
803
491
        refany: RefAny,
804
491
        callback: C,
805
491
    ) {
806
491
        self.text_input_state.on_text_input = Some(TextInputOnTextInput {
807
491
            callback: callback.into(),
808
491
            refany,
809
491
        })
810
491
        .into();
811
491
    }
812

            
813
    #[must_use]
814
5
    pub fn with_on_text_input<C: Into<TextInputOnTextInputCallback>>(
815
5
        mut self,
816
5
        refany: RefAny,
817
5
        callback: C,
818
5
    ) -> Self {
819
5
        self.set_on_text_input(refany, callback);
820
5
        self
821
5
    }
822

            
823
13
    pub fn set_on_virtual_key_down<C: Into<TextInputOnVirtualKeyDownCallback>>(
824
13
        &mut self,
825
13
        refany: RefAny,
826
13
        callback: C,
827
13
    ) {
828
13
        self.text_input_state.on_virtual_key_down = Some(TextInputOnVirtualKeyDown {
829
13
            callback: callback.into(),
830
13
            refany,
831
13
        })
832
13
        .into();
833
13
    }
834

            
835
    #[must_use]
836
8
    pub fn with_on_virtual_key_down<C: Into<TextInputOnVirtualKeyDownCallback>>(
837
8
        mut self,
838
8
        refany: RefAny,
839
8
        callback: C,
840
8
    ) -> Self {
841
8
        self.set_on_virtual_key_down(refany, callback);
842
8
        self
843
8
    }
844

            
845
592
    pub fn set_on_focus_lost<C: Into<TextInputOnFocusLostCallback>>(
846
592
        &mut self,
847
592
        refany: RefAny,
848
592
        callback: C,
849
592
    ) {
850
592
        self.text_input_state.on_focus_lost = Some(TextInputOnFocusLost {
851
592
            callback: callback.into(),
852
592
            refany,
853
592
        })
854
592
        .into();
855
592
    }
856
    #[must_use]
857
111
    pub fn with_on_focus_lost<C: Into<TextInputOnFocusLostCallback>>(
858
111
        mut self,
859
111
        refany: RefAny,
860
111
        callback: C,
861
111
    ) -> Self {
862
111
        self.set_on_focus_lost(refany, callback);
863
111
        self
864
111
    }
865

            
866
113
    pub fn set_container_style(&mut self, style: CssPropertyWithConditionsVec) {
867
113
        self.container_style = OptionCssPropertyWithConditionsVec::Some(style);
868
113
    }
869

            
870
    #[must_use]
871
109
    pub fn with_container_style(mut self, style: CssPropertyWithConditionsVec) -> Self {
872
109
        self.set_container_style(style);
873
109
        self
874
109
    }
875

            
876
6
    pub fn set_label_style(&mut self, style: CssPropertyWithConditionsVec) {
877
6
        self.label_style = OptionCssPropertyWithConditionsVec::Some(style);
878
6
    }
879

            
880
    #[must_use]
881
4
    pub fn with_label_style(mut self, style: CssPropertyWithConditionsVec) -> Self {
882
4
        self.set_label_style(style);
883
4
        self
884
4
    }
885

            
886
    #[must_use]
887
4
    pub fn swap_with_default(&mut self) -> Self {
888
4
        let mut s = Self::default();
889
4
        core::mem::swap(&mut s, self);
890
4
        s
891
4
    }
892

            
893
    /// Renders the widget.
894
    ///
895
    /// The container is the `contenteditable` host — the flag, the tab index and
896
    /// the focus callbacks all sit on it, because focus events do not bubble and
897
    /// the engine records an edit against the *focused* node. Its two children
898
    /// are `<p>` blocks wrapping a bare text node each; nothing else is emitted,
899
    /// in particular no caret node (the engine paints the caret and the
900
    /// selection from its display list).
901
    #[must_use]
902
781
    pub fn dom(self) -> Dom {
903
        // `UiTheme::default()` is Flat, and so is every other widget's fallback:
904
        // an unset theme here used to reach FLORA, which is why an unthemed
905
        // TextInput rendered skeuomorphic next to a flat Button.
906
781
        let theme = self
907
781
            .theme
908
781
            .into_option()
909
781
            .unwrap_or(crate::widgets::themes::UiTheme::Flat);
910
781
        match theme {
911
780
            crate::widgets::themes::UiTheme::Flat => crate::widgets::themes::flat::text_input(self),
912
            crate::widgets::themes::UiTheme::Flora => {
913
1
                crate::widgets::themes::flora::text_input(self)
914
            }
915
        }
916
781
    }
917
}
918

            
919
pub const TEXT_INPUT_CONTAINER_CLASS: &str = "__azul-native-text-input-container";
920
pub const TEXT_INPUT_LABEL_CLASS: &str = "__azul-native-text-input-label";
921

            
922
/// The value `<p>` - the editable line the engine paints the `placeholder`
923
/// attribute's prompt into while it is empty and unfocused.
924
///
925
/// Resolved through the same hierarchy hop the container's own layout
926
/// guarantees; a subtree of any other shape yields `None` and every handler
927
/// bails out. (Was `label_nodes`, returning an overlay node too, until the
928
/// prompt became an engine-painted attribute.)
929
40
fn value_node(info: &CallbackInfo) -> Option<DomNodeId> {
930
40
    let child = info.get_first_child(info.get_hit_node())?;
931
    // SHAPE GUARD: the value `<p>` always wraps exactly one text leaf, so a
932
    // childless first child means the hit node was NOT the container (it was
933
    // the value line itself, whose first child IS that leaf). The two-child
934
    // layout used to get this for free - `first child -> next sibling` walked
935
    // off the end - and a handler that mutates the buffer on a malformed
936
    // subtree silently diverges the model from the screen.
937
35
    let node = child.node.into_crate_internal()?;
938
35
    if info.get_children_count(child.dom, node) == 0 {
939
1
        return None;
940
34
    }
941
34
    Some(child)
942
40
}
943

            
944
/// Adopts the engine's text for `node` into the widget's mirror.
945
///
946
/// The engine owns the buffer, so its answer wins — except that an empty answer
947
/// is ambiguous: `get_text_before_textinput` also yields nothing for a node
948
/// whose text sits under a block wrapper it does not descend into. An empty
949
/// read therefore never clears a non-empty mirror.
950
34
fn adopt_engine_text(state: &mut TextInputState, info: &CallbackInfo, node: DomNodeId) {
951
34
    let Some(text) = info.get_node_text_content(node) else {
952
        return;
953
    };
954
34
    if text.is_empty() && !state.text.is_empty() {
955
6
        return;
956
28
    }
957
52
    state.text = text.chars().map(|c| c as u32).collect::<Vec<_>>().into();
958
34
}
959

            
960
/// The engine's selection, in the widget's public shape.
961
///
962
/// Offsets are byte offsets into the value, matching the cursor positions the
963
/// engine reports; a range that spans the whole buffer collapses to
964
/// [`TextInputSelection::All`].
965
60
fn engine_selection(
966
60
    info: &CallbackInfo,
967
60
    node: DomNodeId,
968
60
    len: usize,
969
60
) -> Option<TextInputSelection> {
970
60
    let ranges = info.get_node_selection_ranges(node);
971
60
    let range = *ranges.as_ref().first()?;
972
    let dir_from = range.start.cluster_id.start_byte_in_run as usize;
973
    let dir_to = range.end.cluster_id.start_byte_in_run as usize;
974
    if len != 0 && dir_from == 0 && dir_to >= len {
975
        return Some(TextInputSelection::All);
976
    }
977
    Some(TextInputSelection::FromTo(TextInputSelectionRange {
978
        dir_from,
979
        dir_to,
980
    }))
981
60
}
982

            
983
/// Mirrors the insertion the engine is about to apply.
984
///
985
/// The engine inserts at the caret, so the mirror does too whenever the caret
986
/// is readable and lands on a character boundary; otherwise it appends, which
987
/// is where the caret sits for every append-only path. `cursor_pos` stays a
988
/// byte offset, as it has always been.
989
23
fn mirror_insertion(state: &mut TextInputState, inserted: &str, caret: Option<usize>) {
990
23
    let text = state.get_text();
991
23
    let at = caret
992
23
        .filter(|at| *at <= text.len() && text.is_char_boundary(*at))
993
23
        .unwrap_or(text.len());
994

            
995
23
    let mut next = String::with_capacity(text.len() + inserted.len());
996
23
    next.push_str(&text[..at]);
997
23
    next.push_str(inserted);
998
23
    next.push_str(&text[at..]);
999

            
217
    state.text = next.chars().map(|c| c as u32).collect::<Vec<_>>().into();
23
    state.cursor_pos = at.saturating_add(inserted.len());
23
}
/// The caret's byte offset inside the edited node, if the engine has one.
16
fn engine_caret(info: &CallbackInfo, node: DomNodeId) -> Option<usize> {
16
    info.get_node_cursor_position(node)
16
        .map(|c| c.cluster_id.start_byte_in_run as usize)
16
}
#[must_use]
6
pub extern "C" fn default_on_focus_received(
6
    mut text_input: RefAny,
6
    mut info: CallbackInfo,
6
) -> Update {
6
    let Some(mut text_input) = text_input.downcast_mut::<TextInputStateWrapper>() else {
1
        return Update::DoNothing;
    };
5
    let text_input = &mut *text_input;
    // A text input always has its placeholder as the first child; a hit node
    // without one is not a text input.
    // A text input always has its value <p> as first child; a hit node
    // without one is not a text input.
5
    let Some(_value) = value_node(&info) else {
2
        return Update::DoNothing;
    };
3
    let container = info.get_hit_node();
3
    adopt_engine_text(&mut text_input.inner, &info, container);
    // The prompt hides itself: the engine paints it only while the line is
    // empty AND unfocused, recomputed per display list. No toggle here, and
    // so nothing that can latch.
    // The engine seeds the caret at the end of the value when focus lands on a
    // contenteditable host; the mirror follows it.
3
    let end_of_text = text_input.inner.text.len();
3
    text_input.inner.cursor_pos = engine_caret(&info, container).unwrap_or(end_of_text);
3
    Update::DoNothing
6
}
#[must_use]
6
pub extern "C" fn default_on_focus_lost(mut text_input: RefAny, mut info: CallbackInfo) -> Update {
6
    let Some(mut text_input) = text_input.downcast_mut::<TextInputStateWrapper>() else {
1
        return Update::DoNothing;
    };
5
    let text_input = &mut *text_input;
5
    let Some(_value) = value_node(&info) else {
1
        return Update::DoNothing;
    };
4
    let container = info.get_hit_node();
4
    adopt_engine_text(&mut text_input.inner, &info, container);
    // The prompt reappears on its own once the blur lands (empty + unfocused
    // is re-evaluated on the next display list).
    // rustc doesn't understand the borrowing lifetime here
4
    let text_input = &mut *text_input;
4
    let onfocuslost = &mut text_input.on_focus_lost;
4
    let inner = text_input.inner.clone();
4
    match onfocuslost.as_mut() {
1
        Some(TextInputOnFocusLost { callback, refany }) => {
1
            (callback.cb)(refany.clone(), info, inner)
        }
3
        None => Update::DoNothing,
    }
6
}
#[must_use]
16
pub extern "C" fn default_on_text_input(text_input: RefAny, info: CallbackInfo) -> Update {
16
    default_on_text_input_inner(text_input, info).unwrap_or(Update::DoNothing)
16
}
18
fn default_on_text_input_inner(mut text_input: RefAny, mut info: CallbackInfo) -> Option<Update> {
18
    let mut text_input = text_input.downcast_mut::<TextInputStateWrapper>()?;
    // The engine records the edit before the callbacks run and applies it after
    // them; this handler only observes it and mirrors it into the widget state.
    // An `Input` WITHOUT a pending record is a post-edit NOTIFICATION: an edit
    // committed outside the record pipeline (deletion, programmatic edit) that
    // is already applied — adopt it and inform the user hook; `valid` cannot
    // veto what already happened.
17
    let inserted_text = info
17
        .get_text_changeset()
17
        .map(|c| c.inserted_text.as_str().to_string())
17
        .unwrap_or_default();
17
    let _value = value_node(&info)?;
15
    let container = info.get_hit_node();
15
    if inserted_text.is_empty() {
        // Idempotent: a notification that changed nothing observable (a
        // spurious Input, an edit already mirrored) stays a strict no-op, so
        // the no-changeset pins keep holding.
2
        let before = text_input.inner.get_text();
2
        adopt_engine_text(&mut text_input.inner, &info, container);
2
        if text_input.inner.get_text() == before {
2
            return None;
        }
        let len = text_input.inner.get_text().len();
        text_input.inner.selection = engine_selection(&info, container, len).into();
        let result = {
            let text_input = &mut *text_input;
            let inner_clone = text_input.inner.clone();
            match text_input.on_text_input.as_mut() {
                Some(TextInputOnTextInput { callback, refany }) => {
                    (callback.cb)(refany.clone(), info, inner_clone)
                }
                None => OnTextInputReturn {
                    update: Update::DoNothing,
                    valid: TextInputValid::Yes,
                },
            }
        };
        return Some(result.update);
13
    }
    // A single-line field never accepts a line separator: veto insertions
    // carrying one (paste with newlines; the engine's Enter line break is
    // already vetoed in the key handler).
13
    if inserted_text.contains('\n') {
        info.prevent_default();
        return Some(Update::DoNothing);
13
    }
13
    let caret = engine_caret(&info, container);
13
    adopt_engine_text(&mut text_input.inner, &info, container);
    // maxlength: veto an insertion that would GROW the value past `max_len`
    // (counted in characters, the stored unit). Replacement-aware: the engine
    // deletes the live selection before inserting, so the prospective length
    // is current − selected + inserted. An edit that shrinks or holds the
    // length always passes — a select-all-and-type at the limit must not be
    // blocked, and a value pushed over the limit programmatically
    // (`set_text` is deliberately NOT capped, like a browser's programmatic
    // assignment) can still be edited back down.
    {
13
        let current = text_input.inner.get_text();
13
        let current_chars = current.chars().count();
13
        let selected_chars = match engine_selection(&info, container, current.len()) {
            Some(TextInputSelection::All) => current_chars,
            Some(TextInputSelection::FromTo(r)) => {
                let (a, b) = (r.dir_from.min(r.dir_to), r.dir_from.max(r.dir_to));
                if b <= current.len() && current.is_char_boundary(a) && current.is_char_boundary(b)
                {
                    current[a..b].chars().count()
                } else {
                    0
                }
            }
13
            None => 0,
        };
13
        let prospective = current_chars
13
            .saturating_sub(selected_chars)
13
            .saturating_add(inserted_text.chars().count());
13
        if prospective > text_input.inner.max_len && prospective > current_chars {
1
            info.prevent_default();
1
            return Some(Update::DoNothing);
12
        }
    }
12
    let result = {
        // rustc doesn't understand the borrowing lifetime here
12
        let text_input = &mut *text_input;
12
        let ontextinput = &mut text_input.on_text_input;
        // inner_clone has the new text
12
        let mut inner_clone = text_input.inner.clone();
12
        mirror_insertion(&mut inner_clone, &inserted_text, caret);
12
        let len = inner_clone.get_text().len();
12
        inner_clone.selection = engine_selection(&info, container, len).into();
12
        match ontextinput.as_mut() {
2
            Some(TextInputOnTextInput { callback, refany }) => {
2
                (callback.cb)(refany.clone(), info, inner_clone)
            }
10
            None => OnTextInputReturn {
10
                update: Update::DoNothing,
10
                valid: TextInputValid::Yes,
10
            },
        }
    };
12
    if result.valid == TextInputValid::Yes {
11
        // No placeholder bookkeeping: the first accepted character makes the
11
        // line non-empty, and the engine simply stops painting the prompt on
11
        // the next display list.
11
        mirror_insertion(&mut text_input.inner, &inserted_text, caret);
11
        let len = text_input.inner.get_text().len();
11
        text_input.inner.selection = engine_selection(&info, container, len).into();
11
    } else {
1
        // The engine applies the recorded changeset once the callbacks return,
1
        // unless one of them vetoes it.
1
        info.prevent_default();
1
    }
12
    Some(result.update)
18
}
#[must_use]
14
pub extern "C" fn default_on_virtual_key_down(text_input: RefAny, info: CallbackInfo) -> Update {
14
    default_on_virtual_key_down_inner(text_input, info).unwrap_or(Update::DoNothing)
14
}
15
fn default_on_virtual_key_down_inner(
15
    mut text_input: RefAny,
15
    mut info: CallbackInfo,
15
) -> Option<Update> {
15
    let mut text_input = text_input.downcast_mut::<TextInputStateWrapper>()?;
14
    let keyboard_state = info.get_current_keyboard_state();
14
    let keycode = keyboard_state.current_virtual_keycode.into_option()?;
13
    let _value = value_node(&info)?;
12
    let container = info.get_hit_node();
12
    adopt_engine_text(&mut text_input.inner, &info, container);
    // Editing keys (Backspace, Delete, the arrows, Enter) are the engine's
    // default actions; this handler only forwards the key to the user's hook
    // and lets a rejection stop the default from running.
12
    let result = {
        // rustc doesn't understand the borrowing lifetime here
12
        let text_input = &mut *text_input;
12
        let mut inner_clone = text_input.inner.clone();
12
        let len = inner_clone.get_text().len();
12
        inner_clone.selection = engine_selection(&info, container, len).into();
12
        match text_input.on_virtual_key_down.as_mut() {
5
            Some(TextInputOnVirtualKeyDown { callback, refany }) => {
5
                (callback.cb)(refany.clone(), info, inner_clone)
            }
7
            None => OnTextInputReturn {
7
                update: Update::DoNothing,
7
                valid: TextInputValid::Yes,
7
            },
        }
    };
12
    let len = text_input.inner.get_text().len();
12
    text_input.inner.selection = engine_selection(&info, container, len).into();
12
    if result.valid == TextInputValid::No {
1
        info.prevent_default();
11
    }
    // Single-line field: Enter must never edit the value. The engine-side
    // default in this host (white-space:pre) is a literal "\n" insert, so it
    // is vetoed here; activation semantics stay with the user's hook above.
11
    if matches!(
12
        keycode,
        azul_core::window::VirtualKeyCode::Return | azul_core::window::VirtualKeyCode::NumpadEnter
1
    ) {
1
        info.prevent_default();
11
    }
12
    Some(result.update)
15
}
#[must_use]
2
pub extern "C" fn default_on_mouse_hover(mut text_input: RefAny, _info: CallbackInfo) -> Update {
2
    let Some(_text_input) = text_input.downcast_mut::<TextInputStateWrapper>() else {
1
        return Update::DoNothing;
    };
1
    Update::DoNothing
2
}
#[cfg(all(test, feature = "std"))]
#[allow(clippy::too_many_lines, clippy::float_cmp)]
mod autotest_generated {
    use std::{
        collections::{BTreeMap, HashMap},
        sync::{Arc, Mutex},
    };
    use azul_core::{
        dom::{
            AttributeType, DomId, DomNodeId, EventFilter, FocusEventFilter, HoverEventFilter,
            IdOrClass, NodeId, NodeType, TabIndex,
        },
        geom::{LogicalRect, OptionLogicalPosition},
        gl::OptionGlContextPtr,
        hit_test::ScrollPosition,
        refany::OptionRefAny,
        resources::RendererResources,
        styled_dom::{NodeHierarchyItemId, StyledDom},
        window::{MonitorVec, RawWindowHandle, VirtualKeyCode},
    };
    use azul_css::dynamic_selector::{DynamicSelector, PseudoStateType, ThemeCondition};
    use rust_fontconfig::FcFontCache;
    use super::*;
    #[cfg(feature = "icu")]
    use crate::icu::IcuLocalizerHandle;
    use crate::{
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
        managers::text_input::PendingTextEdit,
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
        widgets::theme_probe,
        window::{DomLayoutResult, LayoutWindow},
        window_state::FullWindowState,
    };
    // ==================================================================
    // Sample data
    // ==================================================================
    /// Strings the buffer has to survive a `set_text` -> `get_text` round-trip on.
    /// Deliberately loaded with cases where "length" is ambiguous: the buffer counts
    /// *scalars*, `str::len()` counts *bytes*, and a human counts *graphemes* — three
    /// numbers that only agree for pure ASCII.
    const HOSTILE: [&str; 20] = [
        "",
        " ",
        "a",
        "hello world",
        "\0",         // a lone NUL is a perfectly good scalar
        "a\0b",       // ... and it survives in the middle of a string, too
        "\u{7f}",     // largest 1-byte scalar
        "\u{80}",     // smallest 2-byte scalar
        "\u{7ff}",    // largest 2-byte scalar
        "\u{800}",    // smallest 3-byte scalar
        "\u{ffff}",   // largest 3-byte scalar (and a non-character)
        "\u{10000}",  // smallest 4-byte scalar
        "\u{10ffff}", // the largest scalar that exists at all
        "é",
        "e\u{301}", // e + COMBINING ACUTE: 2 scalars, 1 grapheme
        "👨‍👩‍👧‍👦",       // ZWJ family: 7 scalars, 1 grapheme, 25 bytes
        "日本語",
        "مرحبا",    // RTL
        "\u{200b}", // zero-width space: invisible, but still one scalar
        "\r\n\t",
    ];
    /// `u32` code units that are **not** Unicode scalars, so `char::from_u32` rejects
    /// every one of them. The buffer is a `U32Vec`, so nothing stops them from being
    /// in there — `get_text` is the only thing standing between them and a `String`.
    const NON_SCALAR_UNITS: [u32; 6] = [
        0xD800,      // leading surrogate
        0xDC00,      // trailing surrogate
        0xDFFF,      // last surrogate
        0x0011_0000, // one past the last scalar
        0xFFFF_FFFE,
        u32::MAX,
    ];
    // ==================================================================
    // Widget fixtures
    // ==================================================================
    /// A `TextInput` whose buffer holds *raw* code units — the only way to build a
    /// state that `set_text` could never produce (it goes through `char`).
    fn input_with_units(units: &[u32]) -> TextInput {
        let mut input = TextInput::create();
        input.text_input_state.inner.text = units.to_vec().into();
        input
    }
    /// Renders `input` and hands back both the flattened DOM *and* the very `RefAny`
    /// the widget registered on its own handlers. Driving the handlers with these two
    /// is the real wiring: nothing is rebuilt by hand, so a mismatch between what
    /// `dom()` stores and what the handlers expect cannot hide behind the fixture.
    fn rendered(input: TextInput) -> (StyledDom, RefAny) {
        let dom = input.dom();
        let state = dom.root.callbacks.as_ref()[0].refany.clone();
        (StyledDom::create_from_dom(dom), state)
    }
    /// The `TextInputState` currently sitting behind a widget-state payload.
    fn state_of(state: &RefAny) -> TextInputState {
        let mut state = state.clone();
        let wrapper = state
            .downcast_ref::<TextInputStateWrapper>()
            .expect("the widget state must still be a TextInputStateWrapper");
        wrapper.inner.clone()
    }
    /// Reaches into the live widget state — used to plant a cursor position that
    /// `dom()` would otherwise have already normalised away.
    fn poke(state: &RefAny, f: impl FnOnce(&mut TextInputStateWrapper)) {
        let mut state = state.clone();
        let mut wrapper = state
            .downcast_mut::<TextInputStateWrapper>()
            .expect("the widget state must still be a TextInputStateWrapper");
        f(&mut wrapper);
    }
    // ==================================================================
    // Recording hooks
    // ==================================================================
    /// A user payload that records every state it is handed and answers with a
    /// canned verdict. It arrives as the `refany` argument — a *shared* clone of
    /// what the test still holds — so the test reads back exactly what the widget
    /// passed, with no global state involved.
    struct Recorder {
        seen: Vec<TextInputState>,
        update: Update,
        valid: TextInputValid,
    }
    fn recorder(update: Update, valid: TextInputValid) -> RefAny {
        RefAny::new(Recorder {
            seen: Vec::new(),
            update,
            valid,
        })
    }
    fn recorded(probe: &RefAny) -> Vec<TextInputState> {
        let mut probe = probe.clone();
        let log = probe
            .downcast_ref::<Recorder>()
            .expect("the user payload must still be a Recorder");
        log.seen.clone()
    }
    extern "C" fn record_text_input(
        mut data: RefAny,
        _: CallbackInfo,
        state: TextInputState,
    ) -> OnTextInputReturn {
        let Some(mut log) = data.downcast_mut::<Recorder>() else {
            return OnTextInputReturn {
                update: Update::DoNothing,
                valid: TextInputValid::Yes,
            };
        };
        log.seen.push(state);
        OnTextInputReturn {
            update: log.update,
            valid: log.valid,
        }
    }
    // Deliberately *not* the same body as `record_text_input`: two hooks with
    // byte-identical bodies can be folded onto a single symbol by the linker, and
    // the two slots have to stay distinguishable by function pointer.
    extern "C" fn record_virtual_key(
        mut data: RefAny,
        _: CallbackInfo,
        state: TextInputState,
    ) -> OnTextInputReturn {
        match data.downcast_mut::<Recorder>() {
            Some(mut log) => {
                let answer = OnTextInputReturn {
                    update: log.update,
                    valid: log.valid,
                };
                log.seen.push(state);
                answer
            }
            None => OnTextInputReturn {
                update: Update::RefreshDom,
                valid: TextInputValid::No,
            },
        }
    }
    extern "C" fn record_focus_lost(
        mut data: RefAny,
        _: CallbackInfo,
        state: TextInputState,
    ) -> Update {
        data.downcast_mut::<Recorder>()
            .map_or(Update::RefreshDom, |mut log| {
                log.seen.push(state);
                log.update
            })
    }
    /// A `Callback`-shaped (2-argument) function — the shape FFI bindings hand in,
    /// which the `From<Callback>` arm *transmutes* into the 3-argument widget slot.
    /// Never invoked; only its address is ever compared.
    extern "C" fn generic_shaped(_: RefAny, _: CallbackInfo) -> Update {
        Update::DoNothing
    }
    // ==================================================================
    // CallbackInfo harness
    // ==================================================================
    /// The container is always the flattened root of `TextInput::dom()`.
    const CONTAINER: usize = 0;
    fn dom_node(idx: usize) -> DomNodeId {
        DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
        }
    }
    /// A `DomNodeId` whose node component is `None` — the "nothing concrete was hit"
    /// case. `CallbackInfo::set_css_property` *panics* on such an id, so every
    /// handler has to bail out before it ever gets there.
    fn node_none() -> DomNodeId {
        DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::NONE,
        }
    }
    fn inner_id(node: DomNodeId) -> NodeId {
        node.node
            .into_crate_internal()
            .expect("expected a concrete node id")
    }
    /// A `DomLayoutResult` carrying only a `styled_dom`: the text-input handlers
    /// reach only `get_hit_node` / `get_first_child` / `get_next_sibling`, all of
    /// which read the node hierarchy alone — no real layout (and no font) needed.
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
        DomLayoutResult {
            styled_dom,
            layout_tree: LayoutTree {
                nodes: Vec::new(),
                warm: Vec::new(),
                cold: Vec::new(),
                root: 0,
                dom_to_layout: BTreeMap::new(),
                children_arena: Vec::new(),
                children_offsets: Vec::new(),
                subtree_needs_intrinsic: Vec::new(),
            },
            calculated_positions: Vec::new(),
            viewport: LogicalRect::zero(),
            display_list: Arc::new(DisplayList::default()),
            scroll_ids: HashMap::new(),
            scroll_id_to_node_id: HashMap::new(),
        }
    }
    /// Everything a default handler can read out of the window.
    struct Env {
        styled_dom: StyledDom,
        hit: DomNodeId,
        keycode: Option<VirtualKeyCode>,
        changeset: Option<PendingTextEdit>,
    }
    impl Env {
        fn new(styled_dom: StyledDom) -> Self {
            Self {
                styled_dom,
                hit: dom_node(CONTAINER),
                keycode: None,
                changeset: None,
            }
        }
        fn hit(mut self, hit: DomNodeId) -> Self {
            self.hit = hit;
            self
        }
        fn key(mut self, keycode: VirtualKeyCode) -> Self {
            self.keycode = Some(keycode);
            self
        }
        fn insert(mut self, text: &str) -> Self {
            self.changeset = Some(PendingTextEdit {
                node: dom_node(CONTAINER),
                inserted_text: text.into(),
                old_text: AzString::from(""),
            });
            self
        }
    }
    /// The container's single `<p>` child (the value line) plus its bare text
    /// leaf, resolved through the *same* API the handlers use — so no test has
    /// to hard-code a flattened index. The prompt is an ATTRIBUTE on the value
    /// line, not a node, so there is nothing else to resolve.
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    struct Nodes {
        label: Option<DomNodeId>,
        label_text: Option<DomNodeId>,
    }
    /// Runs `f` with a real `CallbackInfo` over a window holding `env.styled_dom` as
    /// the root DOM. Returns `f`'s value, every change the handler pushed onto the
    /// transaction log, and the resolved child node ids.
    fn run<R>(env: Env, f: impl FnOnce(CallbackInfo) -> R) -> (R, Vec<CallbackChange>, Nodes) {
        let mut layout_window =
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
        layout_window
            .layout_results
            .insert(DomId::ROOT_ID, layout_result(env.styled_dom));
        if let Some(changeset) = env.changeset {
            layout_window.text_input_manager.set_changeset(changeset);
        }
        let layout_window = layout_window;
        let renderer_resources = RendererResources::default();
        let previous_window_state: Option<FullWindowState> = None;
        let mut current_window_state = FullWindowState::default();
        current_window_state.keyboard_state.current_virtual_keycode = env.keycode.into();
        let gl_context = OptionGlContextPtr::None;
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
            BTreeMap::new();
        let window_handle = RawWindowHandle::Unsupported;
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
        let ref_data = CallbackInfoRefData {
            layout_window: &layout_window,
            renderer_resources: &renderer_resources,
            previous_window_state: &previous_window_state,
            current_window_state: &current_window_state,
            gl_context: &gl_context,
            current_scroll_manager: &scroll_states,
            current_window_handle: &window_handle,
            system_callbacks: &system_callbacks,
            system_style: Arc::new(system::SystemStyle::default()),
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
            #[cfg(feature = "icu")]
            icu_localizer: IcuLocalizerHandle::default(),
            ctx: OptionRefAny::None,
        };
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
        let probe = CallbackInfo::new(
            &ref_data,
            &changes,
            dom_node(CONTAINER),
            OptionLogicalPosition::None,
            OptionLogicalPosition::None,
        );
        let label = probe.get_first_child(dom_node(CONTAINER));
        let label_text = label.and_then(|l| probe.get_first_child(l));
        let nodes = Nodes { label, label_text };
        let info = CallbackInfo::new(
            &ref_data,
            &changes,
            env.hit,
            OptionLogicalPosition::None,
            OptionLogicalPosition::None,
        );
        let r = f(info);
        let pushed = info.take_changes();
        (r, pushed, nodes)
    }
    /// Every `(node, opacity)` pair pushed onto the transaction log, in push order.
    fn pushed_opacities(changes: &[CallbackChange]) -> Vec<(NodeId, f32)> {
        changes
            .iter()
            .filter_map(|c| match c {
                CallbackChange::ChangeNodeCssProperties {
                    node_id,
                    properties,
                    ..
                } => {
                    let o = properties.as_ref().iter().find_map(|p| match p {
                        CssProperty::Opacity(o) => o.get_property().map(|o| o.inner.normalized()),
                        _ => None,
                    })?;
                    Some((*node_id, o))
                }
                _ => None,
            })
            .collect()
    }
    /// Every `(node, text)` repaint pushed onto the transaction log, in push order.
    fn pushed_texts(changes: &[CallbackChange]) -> Vec<(DomNodeId, String)> {
        changes
            .iter()
            .filter_map(|c| match c {
                CallbackChange::ChangeNodeText { node_id, text } => {
                    Some((*node_id, text.as_str().to_string()))
                }
                _ => None,
            })
            .collect()
    }
    // ==================================================================
    // DOM probes
    // ==================================================================
    /// Flattened child indices of `TextInput::dom()`.
    /// The value line is the container's ONLY child now - the prompt rides
    /// on it as a `placeholder` attribute the engine paints.
    const LABEL_CHILD: usize = 0;
    fn classes(node: &Dom) -> Vec<String> {
        node.root
            .get_ids_and_classes()
            .as_ref()
            .iter()
            .filter_map(|c| match c {
                IdOrClass::Class(s) => Some(s.as_str().to_string()),
                IdOrClass::Id(_) => None,
            })
            .collect()
    }
    /// The text a `<p>` label wraps, looking through the block wrapper the
    /// widget convention mandates (`p > text`).
    fn text_of(node: &Dom) -> String {
        assert!(
            matches!(node.root.get_node_type(), NodeType::P),
            "widget text must be wrapped in a <p> block"
        );
        match node.children.as_ref() {
            [only] => only
                .root
                .get_node_type()
                .format()
                .expect("expected a bare text leaf"),
            other => panic!(
                "a label <p> wraps exactly one text node, found {}",
                other.len()
            ),
        }
    }
    /// Every `NodeType::Text` node in `node`'s subtree that is not a bare leaf
    /// under a `<p>`: css props, callbacks, a tab index, a dataset or children
    /// on a text node are all inert, because a text node owns no rect.
    fn text_nodes_carrying_state(node: &Dom, parent_is_p: bool, bad: &mut Vec<String>) {
        if let NodeType::Text(t) = node.root.get_node_type() {
            let carries = !node.root.get_style().is_empty()
                || !node.root.get_callbacks().as_ref().is_empty()
                || node.root.get_tab_index().is_some()
                || node.root.get_dataset().is_some()
                || !node.children.as_ref().is_empty()
                || !parent_is_p;
            if carries {
                bad.push(t.as_ref().as_str().to_string());
            }
        }
        let is_p = matches!(node.root.get_node_type(), NodeType::P);
        for c in node.children.as_ref() {
            text_nodes_carrying_state(c, is_p, bad);
        }
    }
    fn dataset_state(dom: &Dom) -> TextInputState {
        let mut dataset = dom
            .root
            .get_dataset()
            .cloned()
            .expect("TextInput::dom must attach its state as the container's dataset");
        let wrapper = dataset
            .downcast_ref::<TextInputStateWrapper>()
            .expect("the dataset must be a TextInputStateWrapper");
        wrapper.inner.clone()
    }
    /// `n` properties lifted off the default container style — an easy way to mint
    /// pairwise-distinct style vectors without hard-coding any CSS.
    fn style(n: usize) -> CssPropertyWithConditionsVec {
        let all: Vec<CssPropertyWithConditions> = TextInput::default()
            .resolved_container_style()
            .as_slice()
            .to_vec();
        assert!(n <= all.len(), "not enough default properties to slice");
        CssPropertyWithConditionsVec::from_vec(all.into_iter().take(n).collect())
    }
    // ==================================================================
    // TextInputState::get_text
    // ==================================================================
    #[test]
    fn get_text_on_a_default_state_is_the_empty_string() {
        let state = TextInputState::default();
        assert_eq!(state.get_text(), "");
        assert!(state.text.is_empty());
        assert_eq!(state.cursor_pos, 0);
        assert!(state.placeholder.is_none());
        assert!(state.selection.is_none());
    }
    #[test]
    fn get_text_round_trips_every_hostile_string() {
        // The buffer stores one `u32` per scalar, so the round-trip must be exact for
        // anything `chars()` can produce — combining marks, ZWJ sequences, embedded
        // NULs and the very last scalar included.
        for s in HOSTILE {
            let input = TextInput::create().with_text(s.into());
            assert_eq!(
                input.text_input_state.inner.get_text(),
                s,
                "the buffer did not round-trip {s:?}",
            );
        }
    }
    #[test]
    fn get_text_silently_drops_code_units_that_are_not_unicode_scalars() {
        // `get_text` is a `filter_map(char::from_u32)`: junk in the buffer is skipped,
        // not escaped and not panicked on. Pin that, because "skip" is the difference
        // between a lossy read and a crash on FFI-provided buffers.
        for unit in NON_SCALAR_UNITS {
            let state = TextInputState {
                text: vec![u32::from('A'), unit, u32::from('B')].into(),
                ..TextInputState::default()
            };
            assert_eq!(
                state.get_text(),
                "AB",
                "code unit {unit:#x} was not dropped from the rendered text",
            );
            assert_eq!(
                state.text.len(),
                3,
                "get_text must not mutate the buffer it reads",
            );
        }
    }
    #[test]
    fn get_text_on_a_buffer_of_nothing_but_junk_is_empty_and_does_not_panic() {
        let state = TextInputState {
            text: NON_SCALAR_UNITS.to_vec().into(),
            ..TextInputState::default()
        };
        assert_eq!(state.get_text(), "");
        assert_eq!(state.text.len(), NON_SCALAR_UNITS.len());
    }
    #[test]
    fn get_text_never_yields_more_chars_than_the_buffer_holds() {
        // The one invariant that holds for *any* buffer contents: filtering can only
        // ever shrink. A `get_text` that grew would mean the buffer and the rendered
        // label disagree about how far the cursor can travel.
        let mut units: Vec<u32> = Vec::new();
        for (i, unit) in NON_SCALAR_UNITS.iter().enumerate() {
            units.push(u32::from('x'));
            units.push(*unit);
            units.push(0x1F600 + i as u32);
        }
        let state = TextInputState {
            text: units.clone().into(),
            ..TextInputState::default()
        };
        let rendered = state.get_text();
        assert!(
            rendered.chars().count() <= state.text.len(),
            "get_text produced {} chars from a {}-unit buffer",
            rendered.chars().count(),
            state.text.len(),
        );
        assert_eq!(
            rendered.chars().count(),
            units.len() - NON_SCALAR_UNITS.len()
        );
    }
    #[test]
    fn get_text_is_pure() {
        let state = TextInputState {
            text: vec![u32::from('a'), 0xD800, u32::from('b')].into(),
            ..TextInputState::default()
        };
        let before = state.clone();
        assert_eq!(state.get_text(), state.get_text());
        assert_eq!(state, before, "get_text mutated the state it was given");
    }
    #[test]
    fn get_text_on_a_very_large_buffer_does_not_panic() {
        let n = 50_000;
        let state = TextInputState {
            text: core::iter::repeat_n(u32::from('ß'), n)
                .collect::<Vec<_>>()
                .into(),
            ..TextInputState::default()
        };
        let text = state.get_text();
        assert_eq!(text.chars().count(), n);
        // 'ß' is two bytes: byte length and scalar count are *not* the same number.
        assert_eq!(text.len(), n * 2);
    }
    // ==================================================================
    // TextInput::set_text / with_text
    // ==================================================================
    #[test]
    fn with_text_is_exactly_set_text() {
        for s in HOSTILE {
            let mut a = TextInput::create();
            a.set_text(s.into());
            let b = TextInput::create().with_text(s.into());
            assert_eq!(a, b, "with_text and set_text disagree on {s:?}");
        }
    }
    #[test]
    fn set_text_stores_one_code_unit_per_scalar_not_per_byte() {
        // The classic off-by-UTF-8 bug: storing `s.len()` units for a string whose
        // scalar count is smaller. Every non-ASCII entry in the table has a byte
        // length strictly greater than its scalar count.
        for s in HOSTILE {
            let input = TextInput::create().with_text(s.into());
            assert_eq!(
                input.text_input_state.inner.text.len(),
                s.chars().count(),
                "the buffer length for {s:?} is not the scalar count",
            );
        }
        let family = "👨‍👩‍👧‍👦";
        let input = TextInput::create().with_text(family.into());
        assert_eq!(input.text_input_state.inner.text.len(), 7);
        assert_eq!(family.len(), 25, "the ZWJ family is 25 bytes, not 7");
    }
    #[test]
    fn set_text_stores_the_scalar_values_verbatim() {
        let input = TextInput::create().with_text("aé\u{10ffff}".into());
        assert_eq!(
            input.text_input_state.inner.text.as_slice(),
            &[0x61, 0xE9, 0x0010_FFFF],
        );
    }
    #[test]
    fn set_text_replaces_rather_than_appends() {
        let mut input = TextInput::create();
        input.set_text("first".into());
        input.set_text("second".into());
        assert_eq!(input.text_input_state.inner.get_text(), "second");
        assert_eq!(input.text_input_state.inner.text.len(), 6);
    }
    #[test]
    fn set_text_with_an_empty_string_clears_the_buffer() {
        let mut input = TextInput::create().with_text("something".into());
        input.set_text("".into());
        assert!(input.text_input_state.inner.text.is_empty());
        assert_eq!(input.text_input_state.inner.get_text(), "");
        assert_eq!(
            input,
            TextInput::create(),
            "clearing did not restore a fresh widget"
        );
    }
    #[test]
    fn set_text_does_not_enforce_max_len() {
        // INTENDED: `max_len` caps USER input (the text-input handler vetoes a
        // growing keystroke), but a PROGRAMMATIC assignment is stored whole —
        // the same split a browser makes: `maxlength` never truncates a value
        // set from script. The default is unlimited (`usize::MAX`), like an
        // <input> without `maxlength`.
        let long: String = "x".repeat(200);
        let mut input = TextInput::create().with_text(long.clone().into());
        assert_eq!(input.text_input_state.inner.max_len, usize::MAX);
        assert_eq!(input.text_input_state.inner.text.len(), 200);
        assert_eq!(input.text_input_state.inner.get_text(), long);
        // Even a field WITH a limit accepts a longer programmatic value.
        input.text_input_state.inner.max_len = 50;
        input.set_text("y".repeat(80).into());
        assert_eq!(input.text_input_state.inner.text.len(), 80);
    }
    #[test]
    fn set_text_leaves_the_cursor_where_it_was() {
        // `set_text` writes the buffer and nothing else: the cursor is only
        // reconciled by `dom()` / the focus handler. A widget built with text but
        // never rendered therefore reports a cursor of 0 over a non-empty buffer.
        let input = TextInput::create().with_text("hello".into());
        assert_eq!(input.text_input_state.inner.cursor_pos, 0);
        assert_eq!(input.text_input_state.inner.text.len(), 5);
    }
    #[test]
    fn set_text_touches_nothing_but_the_buffer() {
        let mut input = TextInput::create().with_placeholder("type here".into());
        let before = input.clone();
        input.set_text("abc".into());
        assert_eq!(
            input
                .text_input_state
                .inner
                .placeholder
                .as_ref()
                .map(|s| s.as_str().to_string()),
            Some("type here".to_string()),
        );
        assert_eq!(
            input.resolved_container_style(),
            before.resolved_container_style()
        );
        assert_eq!(input.resolved_label_style(), before.resolved_label_style());
        assert_eq!(
            input.text_input_state.inner.max_len,
            before.text_input_state.inner.max_len
        );
        assert!(input.text_input_state.inner.selection.is_none());
    }
    #[test]
    fn with_text_on_a_very_large_string_does_not_panic() {
        let n = 50_000;
        let long: String = "a".repeat(n);
        let input = TextInput::create().with_text(long.into());
        assert_eq!(input.text_input_state.inner.text.len(), n);
    }
    #[test]
    fn set_text_is_idempotent() {
        for s in HOSTILE {
            let mut input = TextInput::create();
            input.set_text(s.into());
            let once = input.clone();
            input.set_text(s.into());
            assert_eq!(input, once, "re-assigning {s:?} changed the widget");
        }
    }
    // ==================================================================
    // TextInput::set_placeholder / with_placeholder
    // ==================================================================
    #[test]
    fn placeholder_is_absent_on_a_fresh_widget() {
        assert!(TextInput::create()
            .text_input_state
            .inner
            .placeholder
            .is_none());
    }
    #[test]
    fn with_placeholder_is_exactly_set_placeholder_and_stores_the_string_verbatim() {
        for s in HOSTILE {
            let mut a = TextInput::create();
            a.set_placeholder(s.into());
            let b = TextInput::create().with_placeholder(s.into());
            assert_eq!(
                a, b,
                "with_placeholder and set_placeholder disagree on {s:?}"
            );
            assert_eq!(
                a.text_input_state
                    .inner
                    .placeholder
                    .as_ref()
                    .map(|p| p.as_str()),
                Some(s),
                "the placeholder {s:?} was not stored byte-for-byte",
            );
        }
    }
    #[test]
    fn set_placeholder_overwrites_a_previous_placeholder_and_never_clears_it() {
        let mut input = TextInput::create();
        input.set_placeholder("first".into());
        input.set_placeholder("".into());
        // An empty placeholder is still *a* placeholder, not the absence of one.
        assert_eq!(
            input
                .text_input_state
                .inner
                .placeholder
                .as_ref()
                .map(|p| p.as_str()),
            Some(""),
        );
    }
    #[test]
    fn set_placeholder_does_not_touch_the_text_buffer() {
        let mut input = TextInput::create().with_text("abc".into());
        input.set_placeholder("hint".into());
        assert_eq!(input.text_input_state.inner.get_text(), "abc");
    }
    // ==================================================================
    // Style setters
    // ==================================================================
    #[test]
    fn each_style_setter_writes_exactly_one_slot() {
        let marker = style(1);
        let mut b = TextInput::create();
        b.set_container_style(marker.clone());
        assert_eq!(b.resolved_container_style(), marker);
        assert_eq!(
            b.resolved_label_style(),
            TextInput::create().resolved_label_style()
        );
        let mut c = TextInput::create();
        c.set_label_style(marker.clone());
        assert_eq!(c.resolved_label_style(), marker);
        assert_eq!(
            c.resolved_container_style(),
            TextInput::create().resolved_container_style()
        );
    }
    #[test]
    fn the_with_style_builders_are_exactly_their_setters() {
        let s = style(2);
        let mut b = TextInput::create();
        b.set_container_style(s.clone());
        assert_eq!(b, TextInput::create().with_container_style(s.clone()));
        let mut c = TextInput::create();
        c.set_label_style(s.clone());
        assert_eq!(c, TextInput::create().with_label_style(s));
    }
    #[test]
    fn style_setters_accept_an_empty_vector_and_survive_rendering() {
        let empty = CssPropertyWithConditionsVec::from_vec(Vec::new());
        let input = TextInput::create()
            .with_container_style(empty.clone())
            .with_label_style(empty.clone());
        assert!(input.resolved_container_style().is_empty());
        // Stripping every declared property must not stop the widget from rendering.
        let dom = input.dom();
        assert_eq!(dom.children.as_ref().len(), 1);
    }
    #[test]
    fn style_setters_overwrite_rather_than_merge() {
        let mut input = TextInput::create();
        input.set_container_style(style(4));
        input.set_container_style(style(1));
        assert_eq!(input.resolved_container_style().len(), 1);
    }
    // ==================================================================
    // Callback setters
    // ==================================================================
    #[test]
    fn set_on_text_input_stores_the_fn_pointer_and_the_payload_verbatim() {
        let mut input = TextInput::create();
        input.set_on_text_input(
            RefAny::new(0xDEAD_BEEF_u32),
            record_text_input as TextInputOnTextInputCallbackType,
        );
        let slot = input
            .text_input_state
            .on_text_input
            .as_ref()
            .expect("set_on_text_input stored nothing");
        assert_eq!(
            slot.callback.cb as *const () as usize,
            record_text_input as TextInputOnTextInputCallbackType as *const () as usize,
            "the fn pointer was mangled on the way in",
        );
        let mut payload = slot.refany.clone();
        assert_eq!(
            *payload
                .downcast_ref::<u32>()
                .expect("the payload changed type"),
            0xDEAD_BEEF,
        );
        assert!(
            payload.downcast_ref::<u64>().is_none(),
            "the payload must not be readable as a differently-typed value",
        );
    }
    #[test]
    fn set_on_virtual_key_down_and_set_on_focus_lost_store_their_own_slots() {
        let mut input = TextInput::create();
        input.set_on_virtual_key_down(
            RefAny::new(1_u8),
            record_virtual_key as TextInputOnVirtualKeyDownCallbackType,
        );
        input.set_on_focus_lost(
            RefAny::new(2_u8),
            record_focus_lost as TextInputOnFocusLostCallbackType,
        );
        assert!(
            input.text_input_state.on_text_input.as_ref().is_none(),
            "the text-input slot was filled in by an unrelated setter",
        );
        assert_eq!(
            input
                .text_input_state
                .on_virtual_key_down
                .as_ref()
                .expect("the virtual-key slot is empty")
                .callback
                .cb as *const () as usize,
            record_virtual_key as TextInputOnVirtualKeyDownCallbackType as *const () as usize,
        );
        assert_eq!(
            input
                .text_input_state
                .on_focus_lost
                .as_ref()
                .expect("the focus-lost slot is empty")
                .callback
                .cb as *const () as usize,
            record_focus_lost as TextInputOnFocusLostCallbackType as *const () as usize,
        );
    }
    #[test]
    fn the_with_callback_builders_are_exactly_their_setters() {
        let payload = RefAny::new(7_u16);
        let mut a = TextInput::create();
        a.set_on_text_input(
            payload.clone(),
            record_text_input as TextInputOnTextInputCallbackType,
        );
        assert_eq!(
            a,
            TextInput::create().with_on_text_input(
                payload.clone(),
                record_text_input as TextInputOnTextInputCallbackType,
            ),
        );
        let mut b = TextInput::create();
        b.set_on_virtual_key_down(
            payload.clone(),
            record_virtual_key as TextInputOnVirtualKeyDownCallbackType,
        );
        assert_eq!(
            b,
            TextInput::create().with_on_virtual_key_down(
                payload.clone(),
                record_virtual_key as TextInputOnVirtualKeyDownCallbackType,
            ),
        );
        let mut c = TextInput::create();
        c.set_on_focus_lost(
            payload.clone(),
            record_focus_lost as TextInputOnFocusLostCallbackType,
        );
        assert_eq!(
            c,
            TextInput::create().with_on_focus_lost(
                payload,
                record_focus_lost as TextInputOnFocusLostCallbackType
            ),
        );
    }
    #[test]
    fn setting_a_callback_twice_replaces_it_rather_than_stacking() {
        let mut input = TextInput::create();
        input.set_on_text_input(
            RefAny::new(1_u8),
            record_text_input as TextInputOnTextInputCallbackType,
        );
        input.set_on_text_input(
            RefAny::new(2_u8),
            record_virtual_key as TextInputOnTextInputCallbackType,
        );
        let slot = input
            .text_input_state
            .on_text_input
            .as_ref()
            .expect("slot is empty");
        assert_eq!(
            slot.callback.cb as *const () as usize,
            record_virtual_key as TextInputOnTextInputCallbackType as *const () as usize,
            "the second assignment did not win",
        );
        let mut payload = slot.refany.clone();
        assert_eq!(
            *payload.downcast_ref::<u8>().expect("wrong payload type"),
            2
        );
    }
    #[test]
    fn a_generic_two_argument_callback_is_accepted_through_the_ffi_conversion() {
        // FFI bindings hand in a `Callback` (2 args) which the `From<Callback>` arm
        // transmutes into the 3-argument widget slot. It must survive being stored
        // and read back — only the *address* is meaningful, so that is all we check.
        let generic = Callback {
            cb: generic_shaped,
            ctx: OptionRefAny::None,
        };
        let input = TextInput::create().with_on_text_input(RefAny::new(0_u8), generic);
        assert_eq!(
            input
                .text_input_state
                .on_text_input
                .as_ref()
                .expect("the transmuted callback was dropped")
                .callback
                .cb as *const () as usize,
            generic_shaped as *const () as usize,
        );
    }
    // ==================================================================
    // TextInput::create / swap_with_default
    // ==================================================================
    #[test]
    fn create_is_default_and_is_pure() {
        assert_eq!(TextInput::create(), TextInput::default());
        assert_eq!(TextInput::create(), TextInput::create());
    }
    #[test]
    fn create_starts_empty_with_no_hooks_and_no_running_animation() {
        let input = TextInput::create();
        assert!(input.text_input_state.inner.text.is_empty());
        assert!(input.text_input_state.inner.placeholder.is_none());
        assert!(input.text_input_state.inner.selection.is_none());
        assert_eq!(input.text_input_state.inner.cursor_pos, 0);
        // Unlimited by default, like an <input> without `maxlength`.
        assert_eq!(input.text_input_state.inner.max_len, usize::MAX);
        assert!(input.text_input_state.on_text_input.as_ref().is_none());
        assert!(input
            .text_input_state
            .on_virtual_key_down
            .as_ref()
            .is_none());
        assert!(input.text_input_state.on_focus_lost.as_ref().is_none());
        assert!(input.text_input_state.cursor_animation.is_none());
        assert!(
            input
                .text_input_state
                .update_text_input_before_calling_focus_lost_fn
        );
        assert!(
            input
                .text_input_state
                .update_text_input_before_calling_vk_down_fn
        );
        assert!(!input.resolved_container_style().is_empty());
    }
    #[test]
    fn swap_with_default_returns_the_old_widget_and_leaves_a_fresh_one_behind() {
        let mut input = TextInput::create()
            .with_text("typed".into())
            .with_placeholder("hint".into());
        let old = input.swap_with_default();
        assert_eq!(old.text_input_state.inner.get_text(), "typed");
        assert_eq!(
            input,
            TextInput::create(),
            "what was left behind is not a fresh widget"
        );
    }
    #[test]
    fn swapping_twice_round_trips_the_original_widget() {
        let mut a = TextInput::create().with_text("abc".into());
        let mut b = a.swap_with_default(); // a = default, b = "abc"
        let c = b.swap_with_default(); // b = default, c = "abc"
        assert_eq!(c, TextInput::create().with_text("abc".into()));
        assert_eq!(a, TextInput::create());
        assert_eq!(b, TextInput::create());
    }
    #[test]
    fn swap_with_default_moves_the_hooks_out_rather_than_copying_them() {
        let probe = recorder(Update::DoNothing, TextInputValid::Yes);
        let mut input = TextInput::create().with_on_text_input(
            probe.clone(),
            record_text_input as TextInputOnTextInputCallbackType,
        );
        let old = input.swap_with_default();
        assert!(
            old.text_input_state.on_text_input.as_ref().is_some(),
            "the hook vanished during the swap",
        );
        // A duplicated hook would fire twice, and a duplicated RefAny would
        // double-free its payload.
        assert!(
            input.text_input_state.on_text_input.as_ref().is_none(),
            "the hook was copied instead of moved",
        );
        // The payload is still alive and still typed after the move (a double-freed
        // RefAny would not survive the downcast inside `recorded`).
        assert!(recorded(&probe).is_empty(), "the hook fired during a swap");
    }
    // ==================================================================
    // TextInput::dom
    // ==================================================================
    #[test]
    fn dom_builds_a_container_with_exactly_one_value_block() {
        let dom = TextInput::create().dom();
        assert_eq!(classes(&dom), vec!["__azul-native-text-input-container"]);
        assert_eq!(
            dom.children.as_ref().len(),
            1,
            "the prompt is an attribute, not a second child"
        );
        let label = &dom.children.as_ref()[LABEL_CHILD];
        assert_eq!(classes(label), vec!["__azul-native-text-input-label"]);
        assert!(matches!(label.root.get_node_type(), NodeType::P));
        assert_eq!(label.children.as_ref().len(), 1);
        assert!(matches!(
            label.children.as_ref()[0].root.get_node_type(),
            NodeType::Text(_),
        ));
    }
    #[test]
    fn dom_emits_no_cursor_node() {
        // The caret and the selection are display-list items driven by the
        // engine's TextEditManager; a widget-owned cursor div resolved against
        // the container and never tracked the caret.
        fn walk(node: &Dom, out: &mut Vec<String>) {
            out.extend(classes(node));
            for c in node.children.as_ref() {
                walk(c, out);
            }
        }
        let mut all = Vec::new();
        walk(
            &TextInput::create().with_text("typed".into()).dom(),
            &mut all,
        );
        assert!(
            !all.iter().any(|c| c.contains("cursor")),
            "the widget still emits a cursor node: {all:?}",
        );
    }
    #[test]
    fn dom_carries_no_state_on_any_text_node() {
        // A NodeType::Text node is unconditionally inline-level and owns no
        // rect, so css props / callbacks / a tab index / a dataset / children on
        // one are all inert. Every text node must be a bare leaf under a <p>.
        for input in [
            TextInput::create(),
            TextInput::create()
                .with_text("typed".into())
                .with_placeholder("hint".into()),
        ] {
            let mut bad = Vec::new();
            text_nodes_carrying_state(&input.dom(), false, &mut bad);
            assert!(bad.is_empty(), "text nodes carrying inert state: {bad:?}");
        }
    }
    #[test]
    fn dom_marks_the_container_as_keyboard_focusable_and_editable() {
        // Focus events do not bubble and the engine records an edit against the
        // FOCUSED node, so the tab index and the contenteditable flag have to
        // sit on the same node the handlers are attached to.
        let dom = TextInput::create().dom();
        assert_eq!(dom.root.get_tab_index(), Some(TabIndex::Auto));
        assert!(dom.root.is_contenteditable());
    }
    #[test]
    fn dom_keeps_the_placeholder_out_of_the_editable_content() {
        // The prompt must never be typed into. It cannot be: it is an
        // ATTRIBUTE the engine paints, so it owns no node inside the
        // contenteditable host and no text an edit could reach.
        let dom = TextInput::create().with_placeholder("hint".into()).dom();
        let label = &dom.children.as_ref()[LABEL_CHILD];
        assert_eq!(label.root.get_placeholder(), Some("hint"));
        assert_eq!(
            text_of(label),
            "",
            "the prompt is not part of the editable content"
        );
        assert!(!label
            .root
            .attributes()
            .as_ref()
            .iter()
            .any(|a| matches!(a, AttributeType::ContentEditable(_))));
    }
    #[test]
    fn dom_never_bakes_placeholder_visibility_into_css() {
        // The widget used to bake `display:none` onto its overlay prompt when
        // the buffer was non-empty - a build-time snapshot of a RUNTIME fact,
        // which is exactly what latched. The DOM must now be identical either
        // way: whether the prompt shows is decided per display list, by the
        // engine, from (empty && unfocused).
        let filled = TextInput::create().with_text("typed".into()).dom();
        let empty = TextInput::create().dom();
        let display = |node: &Dom| -> Option<CssProperty> {
            node.root
                .style
                .iter_inline_properties()
                .map(|(p, _)| p.clone())
                .filter(|p| matches!(p, CssProperty::Display(_)))
                .last()
        };
        assert_eq!(
            display(&filled.children.as_ref()[LABEL_CHILD]),
            display(&empty.children.as_ref()[LABEL_CHILD]),
            "the value line's css must not depend on whether it has text",
        );
        assert_eq!(
            filled.children.as_ref()[LABEL_CHILD].root.get_placeholder(),
            empty.children.as_ref()[LABEL_CHILD].root.get_placeholder(),
            "and neither must the prompt attribute",
        );
    }
    #[test]
    fn dom_registers_exactly_the_five_default_handlers_over_one_shared_state() {
        let dom = TextInput::create().dom();
        let callbacks = dom.root.callbacks.as_ref();
        let events: Vec<EventFilter> = callbacks.iter().map(|c| c.event).collect();
        assert_eq!(
            events,
            vec![
                EventFilter::Focus(FocusEventFilter::FocusReceived),
                EventFilter::Focus(FocusEventFilter::FocusLost),
                EventFilter::Focus(FocusEventFilter::TextInput),
                EventFilter::Focus(FocusEventFilter::VirtualKeyDown),
                EventFilter::Hover(HoverEventFilter::MouseOver),
            ],
        );
        let targets: Vec<usize> = callbacks.iter().map(|c| c.callback.cb).collect();
        assert_eq!(
            targets,
            vec![
                default_on_focus_received as usize,
                default_on_focus_lost as usize,
                default_on_text_input as usize,
                default_on_virtual_key_down as usize,
                default_on_mouse_hover as usize,
            ],
            "the handlers are wired to the wrong events",
        );
        // All five handlers plus the dataset must share ONE state; separate copies
        // would let the focus handler and the text handler drift apart.
        for c in callbacks {
            assert_eq!(
                c.refany, callbacks[0].refany,
                "a handler got its own state copy"
            );
        }
        assert_eq!(
            dom.root.get_dataset().expect("no dataset attached"),
            &callbacks[0].refany,
        );
    }
    #[test]
    fn dom_renders_the_buffer_into_the_label_and_the_prompt_into_the_attribute() {
        let dom = TextInput::create()
            .with_text("typed".into())
            .with_placeholder("hint".into())
            .dom();
        let label = &dom.children.as_ref()[LABEL_CHILD];
        assert_eq!(text_of(label), "typed");
        assert_eq!(label.root.get_placeholder(), Some("hint"));
    }
    #[test]
    fn dom_without_a_placeholder_still_carries_an_empty_attribute() {
        // The handlers navigate `container -> first child`; the attribute is
        // always present (empty when unset) and the engine paints nothing for
        // an empty prompt.
        let dom = TextInput::create().with_text("typed".into()).dom();
        assert_eq!(dom.children.as_ref().len(), 1);
        assert_eq!(
            dom.children.as_ref()[LABEL_CHILD].root.get_placeholder(),
            Some("")
        );
    }
    #[test]
    fn dom_passes_hostile_text_and_placeholder_through_unchanged() {
        for s in HOSTILE {
            let dom = TextInput::create()
                .with_text(s.into())
                .with_placeholder(s.into())
                .dom();
            assert_eq!(
                text_of(&dom.children.as_ref()[LABEL_CHILD]),
                s,
                "label mangled {s:?}"
            );
            assert_eq!(
                dom.children.as_ref()[LABEL_CHILD].root.get_placeholder(),
                Some(s),
                "placeholder mangled {s:?}",
            );
        }
    }
    #[test]
    fn dom_syncs_the_cursor_to_the_end_of_the_buffer() {
        for s in HOSTILE {
            let dom = TextInput::create().with_text(s.into()).dom();
            assert_eq!(
                dataset_state(&dom).cursor_pos,
                s.chars().count(),
                "the cursor was not parked at the end of {s:?}",
            );
        }
    }
    #[test]
    fn dom_measures_the_cursor_in_code_units_which_can_outrun_the_rendered_text() {
        // KNOWN GAP: `dom()` sets `cursor_pos = text.len()` (code units), while the
        // label only renders the units that are valid scalars. A buffer holding junk
        // therefore ends up with a cursor past the end of what is on screen.
        let dom = input_with_units(&[u32::from('a'), 0xD800, u32::from('b')]).dom();
        assert_eq!(dataset_state(&dom).cursor_pos, 3);
        assert_eq!(text_of(&dom.children.as_ref()[LABEL_CHILD]), "ab");
    }
    #[test]
    fn dom_on_a_very_large_buffer_does_not_panic() {
        let n = 50_000;
        let long: String = "x".repeat(n);
        let dom = TextInput::create().with_text(long.into()).dom();
        assert_eq!(text_of(&dom.children.as_ref()[LABEL_CHILD]).len(), n);
        assert_eq!(dataset_state(&dom).cursor_pos, n);
    }
    #[test]
    fn dom_keeps_the_configured_styles_on_the_nodes_they_were_set_for() {
        let label_style = style(2);
        let container_style = style(3);
        let dom = TextInput::create()
            .with_label_style(label_style.clone())
            .with_container_style(container_style.clone())
            .dom();
        let declared = |v: &CssPropertyWithConditionsVec| -> Vec<CssProperty> {
            v.as_ref().iter().map(|p| p.property.clone()).collect()
        };
        // The theme appends its dark twins AND the field's hover/focus border
        // states on top of what the caller set, so only the resting,
        // unconditional half of the container's style is the caller's verbatim.
        // The label carries no state rules, so the stricter probe still holds
        // there.
        assert_eq!(theme_probe::unconditional(&dom), declared(&container_style));
        assert_eq!(
            theme_probe::unthemed(&dom.children.as_ref()[LABEL_CHILD]),
            declared(&label_style)
        );
    }
    #[test]
    fn dom_gives_the_container_and_the_label_a_dark_mode_twin() {
        // A caller-supplied style replaces the widget's own, but it must not
        // disable the theme's dark half — otherwise setting any style at all
        // leaves the field painting a light fill on a dark surface.
        let dom = TextInput::create()
            .with_container_style(style(3))
            .with_label_style(style(2))
            .dom();
        assert!(
            theme_probe::dark(&dom)
                .iter()
                .any(|p| matches!(p, CssProperty::BackgroundContent(_))),
            "the container keeps its light fill in dark mode",
        );
        assert!(
            theme_probe::dark(&dom.children.as_ref()[LABEL_CHILD])
                .iter()
                .any(|p| matches!(p, CssProperty::TextColor(_))),
            "the label keeps its light ink in dark mode",
        );
    }
    #[test]
    fn dom_carries_the_themes_hover_and_focus_border_states_with_dark_twins() {
        // The rules moved OUT of `TEXT_INPUT_CONTAINER_PROPS` and into the theme
        // modules, which is a move nothing else in this suite would notice: no
        // compiler error, and every other assertion here still passes if a
        // theme silently forgets to append them. Hence this test — and hence it
        // asks BOTH themes, since each `text_input()` appends the array itself.
        use crate::widgets::themes::{OptionUiTheme, UiTheme};
        for (name, theme) in [("flat", UiTheme::Flat), ("flora", UiTheme::Flora)] {
            let mut input = TextInput::create();
            input.theme = OptionUiTheme::Some(theme);
            let dom = input.dom();
            let conditioned = |want_dark: bool, want_focus: bool| -> usize {
                dom.root
                    .style
                    .iter_inline_properties()
                    .filter(|(p, conds)| {
                        let is_border = matches!(
                            p,
                            CssProperty::BorderTopColor(_)
                                | CssProperty::BorderBottomColor(_)
                                | CssProperty::BorderLeftColor(_)
                                | CssProperty::BorderRightColor(_)
                        );
                        let mut dark = false;
                        let mut state_matches = false;
                        for c in conds.as_ref() {
                            match c {
                                DynamicSelector::Theme(ThemeCondition::Dark) => dark = true,
                                DynamicSelector::PseudoState(PseudoStateType::Focus) => {
                                    state_matches = want_focus;
                                }
                                DynamicSelector::PseudoState(PseudoStateType::Hover) => {
                                    state_matches = !want_focus;
                                }
                                _ => {}
                            }
                        }
                        is_border && state_matches && dark == want_dark
                    })
                    .count()
            };
            for (state, want_focus) in [("hover", false), ("focus", true)] {
                assert_eq!(
                    conditioned(false, want_focus),
                    4,
                    "{name} {state}: all four border edges must take the accent, or the ring is \
                     drawn on some sides only",
                );
                assert_eq!(
                    conditioned(true, want_focus),
                    4,
                    "{name} {state}: the dark twin is missing, so the field keeps its light-mode \
                     ring on a dark surface",
                );
            }
            // And the dark declarations really are gated, not unconditional.
            assert!(
                !theme_probe::dark(&dom).is_empty(),
                "{name}: the theme contributed no dark-mode declarations at all"
            );
        }
    }
    #[test]
    fn the_rendered_tree_flattens_to_the_shape_the_handlers_navigate() {
        let (styled_dom, _) = rendered(TextInput::create());
        let ((), _, nodes) = run(Env::new(styled_dom), |_| ());
        let label = nodes.label.expect("the container has no first child");
        let label_text = nodes.label_text.expect("the value block has no text leaf");
        assert_ne!(label, label_text);
        assert_ne!(label, dom_node(CONTAINER));
    }
    // ==================================================================
    // default_on_focus_received
    // ==================================================================
    #[test]
    fn focus_received_with_a_foreign_payload_is_an_inert_no_op() {
        let (styled_dom, _) = rendered(TextInput::create());
        let foreign = RefAny::new(0xDEAD_BEEF_u32);
        let (update, changes, _) = run(Env::new(styled_dom), |info| {
            default_on_focus_received(foreign.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a foreign payload still produced {changes:?}"
        );
    }
    #[test]
    fn focus_received_on_a_node_with_no_children_bails_out_before_touching_css() {
        // `set_css_property` panics on a `None` node id, and every handler
        // bails when the hit node has no children. The escape must happen
        // before any write.
        let (styled_dom, state) = rendered(TextInput::create());
        let (update, changes, nodes) = run(Env::new(styled_dom).hit(node_none()), |info| {
            default_on_focus_received(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(nodes.label.is_some(), "the fixture itself is malformed");
    }
    #[test]
    fn focus_received_on_the_value_text_leaf_is_a_no_op() {
        // The bare text leaf is the one node in the tree with no children.
        let (probe_dom, _) = rendered(TextInput::create());
        let (_, _, nodes) = run(Env::new(probe_dom), |_| ());
        let leaf = nodes.label_text.expect("no value text leaf");
        let (styled_dom, state) = rendered(TextInput::create());
        let (update, changes, _) = run(Env::new(styled_dom).hit(leaf), |info| {
            default_on_focus_received(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a childless hit node still pushed {changes:?}"
        );
    }
    #[test]
    fn focus_writes_no_placeholder_css_at_all() {
        // 2026-08-31 ruling: focusing an empty field HIDES its placeholder -
        // the rule TextArea always had. The empty-editable strut caret marks
        // the focused field, so the old blank-field concern is gone;
        // `focus_lost_shows_the_placeholder_only_while_the_buffer_is_empty`
        // pins the symmetric restore.
        let (styled_dom, state) = rendered(TextInput::create());
        let (update, changes, nodes) = run(Env::new(styled_dom), |info| {
            default_on_focus_received(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "focus must write NO css: the engine paints the prompt only while the line is empty \
             AND unfocused, so there is no state to toggle and nothing that can latch: {changes:?}",
        );
        let _ = nodes;
        let (styled_dom, state) = rendered(TextInput::create().with_text("typed".into()));
        let (update, changes, _) = run(Env::new(styled_dom), |info| {
            default_on_focus_received(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "focusing a non-empty input touched the placeholder anyway: {changes:?}",
        );
    }
    #[test]
    fn focus_received_reparks_the_cursor_at_the_end_of_the_buffer() {
        let (styled_dom, state) = rendered(TextInput::create().with_text("hello".into()));
        // Plant a cursor that is both stale and out of range.
        poke(&state, |w| w.inner.cursor_pos = usize::MAX);
        let (_, _, _) = run(Env::new(styled_dom), |info| {
            default_on_focus_received(state.clone(), info)
        });
        assert_eq!(state_of(&state).cursor_pos, 5);
    }
    // ==================================================================
    // default_on_focus_lost
    // ==================================================================
    #[test]
    fn blur_writes_no_placeholder_css_at_all() {
        let (styled_dom, state) = rendered(TextInput::create());
        let (update, changes, nodes) = run(Env::new(styled_dom), |info| {
            default_on_focus_lost(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "blur must write NO css either — the prompt reappears because the next display list \
             sees empty+unfocused: {changes:?}",
        );
        let _ = nodes;
        let (styled_dom, state) = rendered(TextInput::create().with_text("typed".into()));
        let (_, changes, _) = run(Env::new(styled_dom), |info| {
            default_on_focus_lost(state.clone(), info)
        });
        assert!(
            changes.is_empty(),
            "blurring a non-empty input revealed the placeholder over the text: {changes:?}",
        );
    }
    #[test]
    fn focus_lost_hands_the_hook_the_live_state_and_returns_its_verdict() {
        let probe = recorder(Update::RefreshDomAllWindows, TextInputValid::Yes);
        let (styled_dom, state) = rendered(
            TextInput::create()
                .with_text("typed".into())
                .with_on_focus_lost(
                    probe.clone(),
                    record_focus_lost as TextInputOnFocusLostCallbackType,
                ),
        );
        let (update, _, _) = run(Env::new(styled_dom), |info| {
            default_on_focus_lost(state.clone(), info)
        });
        assert_eq!(
            update,
            Update::RefreshDomAllWindows,
            "the hook's Update was swallowed"
        );
        let seen = recorded(&probe);
        assert_eq!(
            seen.len(),
            1,
            "the hook fired {} times, expected once",
            seen.len()
        );
        assert_eq!(seen[0].get_text(), "typed");
        assert_eq!(
            seen[0].cursor_pos, 5,
            "the hook saw a cursor that dom() should have synced"
        );
    }
    #[test]
    fn focus_lost_without_a_hook_reports_no_work_to_do() {
        let (styled_dom, state) = rendered(TextInput::create().with_text("typed".into()));
        let (update, _, _) = run(Env::new(styled_dom), |info| {
            default_on_focus_lost(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
    }
    #[test]
    fn focus_lost_on_a_none_hit_node_skips_the_hook_entirely() {
        // The early return sits *above* the hook dispatch, so a blur that cannot find
        // its placeholder never reaches user code. Worth pinning: a user hook that
        // commits a form would otherwise fire on a malformed hit.
        let probe = recorder(Update::RefreshDom, TextInputValid::Yes);
        let (styled_dom, state) = rendered(TextInput::create().with_on_focus_lost(
            probe.clone(),
            record_focus_lost as TextInputOnFocusLostCallbackType,
        ));
        let (update, changes, _) = run(Env::new(styled_dom).hit(node_none()), |info| {
            default_on_focus_lost(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(
            recorded(&probe).is_empty(),
            "the hook fired on a hit node that does not exist"
        );
    }
    #[test]
    fn focus_lost_with_a_foreign_payload_is_an_inert_no_op() {
        let (styled_dom, _) = rendered(TextInput::create());
        let foreign = RefAny::new("not a text input".to_string());
        let (update, changes, _) = run(Env::new(styled_dom), |info| {
            default_on_focus_lost(foreign.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    // ==================================================================
    // default_on_text_input
    // ==================================================================
    #[test]
    fn text_input_without_a_pending_changeset_does_nothing() {
        let (styled_dom, state) = rendered(TextInput::create());
        let (update, changes, _) = run(Env::new(styled_dom), |info| {
            default_on_text_input(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(state_of(&state).get_text(), "");
    }
    #[test]
    fn text_input_with_an_empty_insertion_does_nothing() {
        let (styled_dom, state) = rendered(TextInput::create().with_text("abc".into()));
        let (update, changes, _) = run(Env::new(styled_dom).insert(""), |info| {
            default_on_text_input(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "an empty insertion still repainted: {changes:?}"
        );
        assert_eq!(state_of(&state).get_text(), "abc");
        assert_eq!(state_of(&state).cursor_pos, 3);
    }
    #[test]
    fn text_input_mirrors_the_insertion_and_hides_the_placeholder() {
        let (styled_dom, state) = rendered(TextInput::create().with_placeholder("hint".into()));
        let (update, changes, nodes) = run(Env::new(styled_dom).insert("hi"), |info| {
            default_on_text_input(state.clone(), info)
        });
        assert_eq!(
            update,
            Update::DoNothing,
            "no hook is installed, so nothing needs redrawing"
        );
        assert_eq!(state_of(&state).get_text(), "hi");
        assert_eq!(state_of(&state).cursor_pos, 2);
        assert!(
            pushed_opacities(&changes).is_empty(),
            "typing must not toggle any placeholder override: {changes:?}",
        );
        let _ = nodes;
        assert!(
            pushed_texts(&changes).is_empty(),
            "the widget repainted the value itself; the engine owns the buffer: {changes:?}",
        );
    }
    #[test]
    fn text_input_appends_to_an_existing_buffer_rather_than_replacing_it() {
        let (styled_dom, state) = rendered(TextInput::create().with_text("ab".into()));
        let (_, changes, _) = run(Env::new(styled_dom).insert("cd"), |info| {
            default_on_text_input(state.clone(), info)
        });
        assert_eq!(state_of(&state).get_text(), "abcd");
        assert!(pushed_texts(&changes).is_empty());
    }
    #[test]
    fn text_input_hands_the_hook_a_preview_that_already_contains_the_insertion() {
        // The hook is a *validator*: it has to see the would-be result, not the state
        // before the edit, or it can never reject an edit for what it produces.
        let probe = recorder(Update::RefreshDom, TextInputValid::Yes);
        let (styled_dom, state) = rendered(
            TextInput::create()
                .with_text("ab".into())
                .with_on_text_input(
                    probe.clone(),
                    record_text_input as TextInputOnTextInputCallbackType,
                ),
        );
        let (update, _, _) = run(Env::new(styled_dom).insert("c"), |info| {
            default_on_text_input(state.clone(), info)
        });
        assert_eq!(
            update,
            Update::RefreshDom,
            "the hook's Update was swallowed"
        );
        let seen = recorded(&probe);
        assert_eq!(seen.len(), 1);
        assert_eq!(
            seen[0].get_text(),
            "abc",
            "the hook was shown the pre-edit buffer"
        );
        assert_eq!(seen[0].cursor_pos, 3);
    }
    #[test]
    fn text_input_rejected_by_the_hook_leaves_the_buffer_and_the_screen_untouched() {
        let probe = recorder(Update::RefreshDomAllWindows, TextInputValid::No);
        let (styled_dom, state) = rendered(
            TextInput::create()
                .with_text("ab".into())
                .with_placeholder("hint".into())
                .with_on_text_input(
                    probe.clone(),
                    record_text_input as TextInputOnTextInputCallbackType,
                ),
        );
        let (update, changes, _) = run(Env::new(styled_dom).insert("c"), |info| {
            default_on_text_input(state.clone(), info)
        });
        assert_eq!(
            update,
            Update::RefreshDomAllWindows,
            "a rejected edit still reports its Update"
        );
        assert_eq!(
            state_of(&state).get_text(),
            "ab",
            "a rejected edit was applied anyway"
        );
        assert_eq!(
            state_of(&state).cursor_pos,
            2,
            "a rejected edit still moved the cursor"
        );
        assert!(
            changes
                .iter()
                .all(|c| matches!(c, CallbackChange::PreventDefault)),
            "a rejected edit still repainted the widget: {changes:?}",
        );
        assert!(
            changes
                .iter()
                .any(|c| matches!(c, CallbackChange::PreventDefault)),
            "a rejected edit did not stop the engine from applying the changeset",
        );
    }
    #[test]
    fn text_input_advances_the_cursor_by_utf8_byte_length_not_by_scalar_count() {
        // KNOWN GAP: the cursor is advanced by `inserted_text.len()` — the *byte*
        // length of the insertion — while the buffer grows by one unit per scalar.
        // For anything outside ASCII the two disagree, and the cursor ends up past
        // the end of the buffer it indexes into.
        let (styled_dom, state) = rendered(TextInput::create());
        let (_, _, _) = run(Env::new(styled_dom).insert("é"), |info| {
            default_on_text_input(state.clone(), info)
        });
        let after = state_of(&state);
        assert_eq!(after.get_text(), "é");
        assert_eq!(after.text.len(), 1, "the buffer holds one scalar");
        assert_eq!(
            after.cursor_pos, 2,
            "but the cursor moved by the two UTF-8 bytes"
        );
        assert!(
            after.cursor_pos > after.text.len(),
            "the cursor is expected to overshoot here; see the KNOWN GAP above",
        );
    }
    #[test]
    fn text_input_recomputes_the_cursor_rather_than_accumulating_a_stale_one() {
        // The cursor is derived from the insertion point every time, so a stale
        // value planted by a host cannot survive — nor overflow.
        let (styled_dom, state) = rendered(TextInput::create());
        poke(&state, |w| w.inner.cursor_pos = usize::MAX);
        let (update, _, _) = run(Env::new(styled_dom).insert("abc"), |info| {
            default_on_text_input(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert_eq!(state_of(&state).cursor_pos, 3);
        assert_eq!(state_of(&state).get_text(), "abc");
    }
    #[test]
    fn text_input_accepts_astral_combining_and_multi_scalar_insertions() {
        for s in ["\u{10ffff}", "e\u{301}", "👨‍👩‍👧‍👦", "日本語", "\0"] {
            let (styled_dom, state) = rendered(TextInput::create());
            let (_, changes, _) = run(Env::new(styled_dom).insert(s), |info| {
                default_on_text_input(state.clone(), info)
            });
            assert_eq!(state_of(&state).get_text(), s, "the buffer mangled {s:?}");
            assert_eq!(state_of(&state).text.len(), s.chars().count());
            assert!(pushed_texts(&changes).is_empty());
        }
    }
    #[test]
    fn text_input_on_a_wrong_shaped_subtree_changes_nothing() {
        // Hitting the label means `first child -> next sibling` walks off the end of
        // the tree. The handler has to give up *before* mutating the buffer, or the
        // model and the screen would silently diverge.
        let (probe_dom, _) = rendered(TextInput::create());
        let (_, _, nodes) = run(Env::new(probe_dom), |_| ());
        let label = nodes.label.expect("no label");
        let (styled_dom, state) = rendered(TextInput::create().with_text("ab".into()));
        let (result, changes, _) = run(Env::new(styled_dom).hit(label).insert("c"), |info| {
            default_on_text_input_inner(state.clone(), info)
        });
        assert_eq!(
            result, None,
            "the handler claimed to have handled a malformed tree"
        );
        assert!(changes.is_empty());
        assert_eq!(
            state_of(&state).get_text(),
            "ab",
            "the buffer changed anyway"
        );
    }
    #[test]
    fn text_input_on_a_none_hit_node_changes_nothing() {
        let (styled_dom, state) = rendered(TextInput::create().with_text("ab".into()));
        let (update, changes, _) = run(Env::new(styled_dom).hit(node_none()).insert("c"), |info| {
            default_on_text_input(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(state_of(&state).get_text(), "ab");
    }
    #[test]
    fn text_input_with_a_foreign_payload_is_an_inert_no_op() {
        let (styled_dom, _) = rendered(TextInput::create());
        let foreign = RefAny::new(0_u8);
        let (result, changes, _) = run(Env::new(styled_dom).insert("a"), |info| {
            default_on_text_input_inner(foreign.clone(), info)
        });
        assert_eq!(result, None);
        assert!(changes.is_empty());
    }
    #[test]
    fn text_input_default_max_len_is_unlimited() {
        // The default is unlimited, like an <input> without `maxlength`: an
        // 80-char insertion into a fresh field is accepted whole.
        let (styled_dom, state) = rendered(TextInput::create());
        let filler: String = "x".repeat(80);
        let (_, _, _) = run(Env::new(styled_dom).insert(&filler), |info| {
            default_on_text_input(state.clone(), info)
        });
        let after = state_of(&state);
        assert_eq!(after.max_len, usize::MAX);
        assert_eq!(after.text.len(), 80);
    }
    #[test]
    fn typing_past_max_len_is_vetoed() {
        // maxlength: a keystroke that would GROW the value past `max_len` is
        // vetoed — the widget state keeps the old text and `PreventDefault`
        // stops the engine from applying the recorded changeset. (Programmatic
        // `set_text` stays uncapped; see `set_text_does_not_enforce_max_len`.)
        let mut input = TextInput::create().with_text("abc".into());
        input.text_input_state.inner.max_len = 3;
        let (styled_dom, state) = rendered(input);
        let (_, changes, _) = run(Env::new(styled_dom).insert("d"), |info| {
            default_on_text_input(state.clone(), info)
        });
        assert_eq!(
            state_of(&state).get_text(),
            "abc",
            "the over-limit keystroke was applied anyway",
        );
        assert!(
            changes
                .iter()
                .any(|c| matches!(c, CallbackChange::PreventDefault)),
            "the over-limit keystroke did not veto the engine changeset: {changes:?}",
        );
    }
    // ==================================================================
    // default_on_virtual_key_down
    // ==================================================================
    #[test]
    fn virtual_key_down_without_a_pressed_key_does_nothing() {
        let probe = recorder(Update::RefreshDom, TextInputValid::Yes);
        let (styled_dom, state) = rendered(
            TextInput::create()
                .with_text("ab".into())
                .with_on_virtual_key_down(
                    probe.clone(),
                    record_virtual_key as TextInputOnVirtualKeyDownCallbackType,
                ),
        );
        let (update, changes, _) = run(Env::new(styled_dom), |info| {
            default_on_virtual_key_down(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(
            recorded(&probe).is_empty(),
            "the hook fired without a key being down"
        );
        assert_eq!(state_of(&state).get_text(), "ab");
    }
    #[test]
    fn backspace_is_the_engines_default_action_not_the_widgets() {
        // Deletion is `SystemChange::ApplySelectionOp` on the engine side; a
        // widget that also popped its own buffer would double-delete.
        let (styled_dom, state) = rendered(TextInput::create().with_text("abc".into()));
        let (update, changes, _) = run(Env::new(styled_dom).key(VirtualKeyCode::Back), |info| {
            default_on_virtual_key_down(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "backspace still mutated the DOM: {changes:?}"
        );
        assert_eq!(
            state_of(&state).get_text(),
            "abc",
            "the widget deleted behind the engine"
        );
    }
    #[test]
    fn every_key_reaches_the_hook_and_leaves_the_buffer_alone() {
        for key in [
            VirtualKeyCode::A,
            VirtualKeyCode::Back,
            VirtualKeyCode::Return,
        ] {
            let probe = recorder(Update::RefreshDom, TextInputValid::Yes);
            let (styled_dom, state) = rendered(
                TextInput::create()
                    .with_text("ab".into())
                    .with_on_virtual_key_down(
                        probe.clone(),
                        record_virtual_key as TextInputOnVirtualKeyDownCallbackType,
                    ),
            );
            let (update, changes, _) = run(Env::new(styled_dom).key(key), |info| {
                default_on_virtual_key_down(state.clone(), info)
            });
            assert_eq!(
                update,
                Update::RefreshDom,
                "{key:?} swallowed the hook's Update"
            );
            if matches!(key, VirtualKeyCode::Return) {
                // Single-line field: Enter must never edit the value, so the
                // handler vetoes the engine's "\n" default — and nothing else.
                assert_eq!(
                    changes.len(),
                    1,
                    "Return must veto exactly once: {changes:?}"
                );
                assert!(
                    matches!(changes[0], CallbackChange::PreventDefault),
                    "Return must veto the engine line break, and only that: {changes:?}"
                );
            } else {
                assert!(
                    changes.is_empty(),
                    "{key:?} repainted the value: {changes:?}"
                );
            }
            assert_eq!(state_of(&state).get_text(), "ab");
            assert_eq!(recorded(&probe).len(), 1, "the hook must see {key:?} too");
        }
    }
    #[test]
    fn a_rejecting_hook_vetoes_the_engines_default_and_keeps_its_update() {
        let probe = recorder(Update::RefreshDomAllWindows, TextInputValid::No);
        let (styled_dom, state) = rendered(
            TextInput::create()
                .with_text("abc".into())
                .with_on_virtual_key_down(
                    probe.clone(),
                    record_virtual_key as TextInputOnVirtualKeyDownCallbackType,
                ),
        );
        let (update, changes, _) = run(Env::new(styled_dom).key(VirtualKeyCode::Back), |info| {
            default_on_virtual_key_down(state.clone(), info)
        });
        assert_eq!(update, Update::RefreshDomAllWindows);
        assert_eq!(
            changes.len(),
            1,
            "a veto must push nothing but the preventDefault: {changes:?}",
        );
        assert!(matches!(changes[0], CallbackChange::PreventDefault));
        assert_eq!(state_of(&state).get_text(), "abc");
        assert_eq!(state_of(&state).cursor_pos, 3);
    }
    #[test]
    fn the_virtual_key_hook_is_shown_the_state_from_before_the_key_is_handled() {
        // The hook runs first so that it can veto; that means it necessarily sees
        // the pre-edit buffer. Pinned because "which side of the edit does the
        // hook see" is exactly the thing a refactor gets wrong.
        let probe = recorder(Update::DoNothing, TextInputValid::Yes);
        let (styled_dom, state) = rendered(
            TextInput::create()
                .with_text("abc".into())
                .with_on_virtual_key_down(
                    probe.clone(),
                    record_virtual_key as TextInputOnVirtualKeyDownCallbackType,
                ),
        );
        let (_, _, _) = run(Env::new(styled_dom).key(VirtualKeyCode::Back), |info| {
            default_on_virtual_key_down(state.clone(), info)
        });
        let seen = recorded(&probe);
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].get_text(), "abc");
        assert_eq!(seen[0].cursor_pos, 3);
    }
    #[test]
    fn virtual_key_down_on_a_none_hit_node_skips_the_hook_entirely() {
        let probe = recorder(Update::RefreshDom, TextInputValid::Yes);
        let (styled_dom, state) = rendered(
            TextInput::create()
                .with_text("abc".into())
                .with_on_virtual_key_down(
                    probe.clone(),
                    record_virtual_key as TextInputOnVirtualKeyDownCallbackType,
                ),
        );
        let (result, changes, _) = run(
            Env::new(styled_dom)
                .hit(node_none())
                .key(VirtualKeyCode::Back),
            |info| default_on_virtual_key_down_inner(state.clone(), info),
        );
        assert_eq!(result, None);
        assert!(changes.is_empty());
        assert!(
            recorded(&probe).is_empty(),
            "the hook fired on a hit node that does not exist"
        );
        assert_eq!(state_of(&state).get_text(), "abc");
    }
    #[test]
    fn virtual_key_down_with_a_foreign_payload_is_an_inert_no_op() {
        let (styled_dom, _) = rendered(TextInput::create());
        let foreign = RefAny::new(vec![1_u32, 2, 3]);
        let (update, changes, _) = run(Env::new(styled_dom).key(VirtualKeyCode::Back), |info| {
            default_on_virtual_key_down(foreign.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn repeated_key_presses_are_idempotent_on_the_widget_state() {
        // Six backspaces over a three-scalar buffer: the widget must not move a
        // single unit — every one of them belongs to the engine.
        let (_, state) = rendered(TextInput::create().with_text("abc".into()));
        for i in 0..6 {
            // The tree shape does not depend on what the buffer holds, so a fresh
            // container is enough to navigate; the live state is `state`.
            let (styled_dom, _) = rendered(TextInput::create());
            let (update, _, _) = run(Env::new(styled_dom).key(VirtualKeyCode::Back), |info| {
                default_on_virtual_key_down(state.clone(), info)
            });
            assert_eq!(
                update,
                Update::DoNothing,
                "backspace #{i} reported work to do"
            );
        }
        let after = state_of(&state);
        assert_eq!(after.get_text(), "abc");
        assert_eq!(after.cursor_pos, 3);
    }
    // ==================================================================
    // default_on_mouse_hover
    // ==================================================================
    #[test]
    fn mouse_hover_is_inert_for_every_payload_and_every_hit_node() {
        let (styled_dom, state) = rendered(TextInput::create().with_text("abc".into()));
        let (update, changes, _) = run(Env::new(styled_dom), |info| {
            default_on_mouse_hover(state.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(
            state_of(&state).get_text(),
            "abc",
            "hovering edited the buffer"
        );
        let (styled_dom, _) = rendered(TextInput::create());
        let foreign = RefAny::new(0_u8);
        let (update, changes, _) = run(Env::new(styled_dom).hit(node_none()), |info| {
            default_on_mouse_hover(foreign.clone(), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
}