1
//! Multi-line text input (text area) widget.
2
//!
3
//! A multi-line sibling of [`crate::widgets::text_input::TextInput`], built on
4
//! the same flow: the container is a `contenteditable` host carrying the tab
5
//! index and the focus callbacks, so the engine's `TextEditManager` owns the
6
//! caret, the selection and the buffer, and edits run through
7
//! `record_text_input` / `apply_text_changeset`. Caret and selection are
8
//! display-list items driven by that manager; the widget emits no cursor node.
9
//!
10
//! Value and placeholder are `<p>` blocks wrapping a bare text node — a
11
//! [`NodeType::Text`](azul_core::dom::NodeType::Text) node is always
12
//! inline-level and owns no rect, so box-model properties on one are inert.
13
//! Line wrapping relies on the text layout honouring `white-space: pre-wrap`.
14
//!
15
//! [`TextAreaState`] is a *mirror* of the engine's state, refreshed from its
16
//! changesets so the public callbacks keep the shape existing hosts bind
17
//! against. The widget reuses [`TextInput`]'s [`OnTextInputReturn`] /
18
//! [`TextInputValid`] return types for its `on_text_input` callback so existing
19
//! host bindings and validation logic apply unchanged; a `TextInputValid::No`
20
//! answer turns into `CallbackInfo::prevent_default`, which stops the engine
21
//! from applying the edit it recorded.
22
//!
23
//! KNOWN GAP: caret-relative *deletion* (Backspace/Delete) and Enter are engine
24
//! default actions and the mirror cannot see their result, because the engine
25
//! exposes no post-apply text for a node whose value sits under a block
26
//! wrapper. Enter in a contenteditable host records a structural block split
27
//! rather than inserting a `'\n'` into the buffer, so a multi-paragraph value
28
//! no longer round-trips through [`TextAreaState::get_text`] as newlines.
29
//!
30
//! Key types: [`TextArea`], [`TextAreaState`], [`TextAreaOnTextInput`],
31
//! [`TextAreaOnVirtualKeyDown`], [`TextAreaOnFocusLost`].
32

            
33
use alloc::{string::String, vec::Vec};
34

            
35
use azul_core::{
36
    callbacks::{CoreCallback, CoreCallbackData, Update},
37
    dom::{Dom, DomNodeId},
38
    refany::RefAny,
39
};
40
use azul_css::{
41
    dynamic_selector::{
42
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
43
    },
44
    impl_option_inner,
45
    props::{
46
        basic::{ColorU, StyleFontFamily, StyleFontFamilyVec, StyleFontSize},
47
        layout::{
48
            LayoutBoxSizing, LayoutDisplay, LayoutFlexGrow, LayoutHeight, LayoutLeft,
49
            LayoutMinHeight, LayoutOverflow, LayoutPaddingBottom, LayoutPaddingLeft,
50
            LayoutPaddingRight, LayoutPaddingTop, LayoutPosition, LayoutTop,
51
        },
52
        property::{CssProperty, StyleWhiteSpaceValue},
53
        style::{
54
            BorderStyle, LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
55
            LayoutBorderTopWidth, StyleBackgroundContent, StyleBackgroundContentVec,
56
            StyleBorderBottomColor, StyleBorderBottomStyle, StyleBorderLeftColor,
57
            StyleBorderLeftStyle, StyleBorderRightColor, StyleBorderRightStyle,
58
            StyleBorderTopColor, StyleBorderTopStyle, StyleCursor, StyleOpacity, StyleTextAlign,
59
            StyleTextColor, StyleWhiteSpace,
60
        },
61
    },
62
    AzString, OptionString, U32Vec,
63
};
64

            
65
use crate::{
66
    callbacks::{Callback, CallbackInfo},
67
    widgets::text_input::{OnTextInputReturn, TextInputValid},
68
};
69

            
70
// ---- colours ----
71
const BACKGROUND_COLOR: ColorU = ColorU {
72
    r: 255,
73
    g: 255,
74
    b: 255,
75
    a: 255,
76
}; // white
77
const COLOR_9B9B9B: ColorU = ColorU {
78
    r: 155,
79
    g: 155,
80
    b: 155,
81
    a: 255,
82
}; // #9b9b9b border
83
const COLOR_4286F4: ColorU = ColorU {
84
    r: 66,
85
    g: 134,
86
    b: 244,
87
    a: 255,
88
}; // #4286f4 focus/hover
89
const COLOR_4C4C4C: ColorU = ColorU {
90
    r: 76,
91
    g: 76,
92
    b: 76,
93
    a: 255,
94
}; // #4C4C4C text
95

            
96
const BACKGROUND_THEME_LIGHT: &[StyleBackgroundContent] =
97
    &[StyleBackgroundContent::Color(BACKGROUND_COLOR)];
98
const BACKGROUND_COLOR_LIGHT: StyleBackgroundContentVec =
99
    StyleBackgroundContentVec::from_const_slice(BACKGROUND_THEME_LIGHT);
100

            
101
const SANS_SERIF_STR: &str = "system:ui";
102
const SANS_SERIF: AzString = AzString::from_const_str(SANS_SERIF_STR);
103
const SANS_SERIF_FAMILIES: &[StyleFontFamily] = &[StyleFontFamily::System(SANS_SERIF)];
104
const SANS_SERIF_FAMILY: StyleFontFamilyVec =
105
    StyleFontFamilyVec::from_const_slice(SANS_SERIF_FAMILIES);
106

            
107
/// Minimum height of the editable area (~4 lines).
108
const MIN_HEIGHT_PX: isize = 64;
109

            
110
// -- container style (cross-platform single style) --
111
pub static TEXT_AREA_CONTAINER_PROPS: &[CssPropertyWithConditions] = &[
112
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
113
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Text)),
114
    CssPropertyWithConditions::simple(CssProperty::const_box_sizing(LayoutBoxSizing::BorderBox)),
115
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
116
    CssPropertyWithConditions::simple(CssProperty::const_min_height(LayoutMinHeight::const_px(
117
        MIN_HEIGHT_PX,
118
    ))),
119
    // A DEFINITE height, not just a floor. A `<textarea>` in a browser is sized
120
    // by its `rows`, never by its content — and that is exactly what makes it
121
    // scroll. With `height: auto` the flex path (Taffy, which has no equivalent
122
    // of the block path's `skip_expansion` guard in solver3/cache.rs) grew this
123
    // box to its max-content height inside an auto-height flex column, so the
124
    // text NEVER overflowed: no overflow means no scroll node is registered
125
    // (scroll_registration.rs bails on `!needs_vertical && !needs_horizontal`),
126
    // and a wheel over the textarea therefore found no scrollable node under
127
    // the pointer and chained straight to the page. `flex-grow: 1` above still
128
    // lets it stretch inside a definite-height column.
129
    CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(
130
        MIN_HEIGHT_PX,
131
    ))),
132
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(13))),
133
    CssPropertyWithConditions::simple(CssProperty::const_background_content(
134
        BACKGROUND_COLOR_LIGHT,
135
    )),
136
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
137
        inner: COLOR_4C4C4C,
138
    })),
139
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
140
        LayoutPaddingLeft::const_px(4),
141
    )),
142
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
143
        LayoutPaddingRight::const_px(4),
144
    )),
145
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
146
        4,
147
    ))),
148
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
149
        LayoutPaddingBottom::const_px(4),
150
    )),
151
    // border: 1px inset #9b9b9b
152
    CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
153
        LayoutBorderTopWidth::const_px(1),
154
    )),
155
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
156
        LayoutBorderBottomWidth::const_px(1),
157
    )),
158
    CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
159
        LayoutBorderLeftWidth::const_px(1),
160
    )),
161
    CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
162
        LayoutBorderRightWidth::const_px(1),
163
    )),
164
    CssPropertyWithConditions::simple(CssProperty::const_border_top_style(StyleBorderTopStyle {
165
        inner: BorderStyle::Inset,
166
    })),
167
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
168
        StyleBorderBottomStyle {
169
            inner: BorderStyle::Inset,
170
        },
171
    )),
172
    CssPropertyWithConditions::simple(CssProperty::const_border_left_style(StyleBorderLeftStyle {
173
        inner: BorderStyle::Inset,
174
    })),
175
    CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
176
        StyleBorderRightStyle {
177
            inner: BorderStyle::Inset,
178
        },
179
    )),
180
    CssPropertyWithConditions::simple(CssProperty::const_border_top_color(StyleBorderTopColor {
181
        inner: COLOR_9B9B9B,
182
    })),
183
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
184
        StyleBorderBottomColor {
185
            inner: COLOR_9B9B9B,
186
        },
187
    )),
188
    CssPropertyWithConditions::simple(CssProperty::const_border_left_color(StyleBorderLeftColor {
189
        inner: COLOR_9B9B9B,
190
    })),
191
    CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
192
        StyleBorderRightColor {
193
            inner: COLOR_9B9B9B,
194
        },
195
    )),
196
    CssPropertyWithConditions::simple(CssProperty::const_overflow_x(LayoutOverflow::Hidden)),
197
    // `auto`, not `scroll`: the web-model textarea shows a scrollbar only
198
    // once the content overflows — an EMPTY field with a permanent track +
199
    // full-length thumb was the reported artifact.
200
    CssPropertyWithConditions::simple(CssProperty::const_overflow_y(LayoutOverflow::Auto)),
201
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Left)),
202
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SANS_SERIF_FAMILY)),
203
    // Preserve newlines + wrap long lines.
204
    CssPropertyWithConditions::simple(CssProperty::WhiteSpace(StyleWhiteSpaceValue::Exact(
205
        StyleWhiteSpace::PreWrap,
206
    ))),
207
    // Hover and focus border states are NOT here. They live in the theme
208
    // modules (`flat::FIELD_BORDER_STATES`, `flora::FIELD_BORDER_STATES`) and
209
    // are appended by `flat::text_area` / `flora::text_area`, because the dark
210
    // half of each pair needs the theme's `DARK_ACC` — a colour this file cannot
211
    // see. Declared here, they could only ever name the light-mode blue, which
212
    // is why a hovered field kept its light ring on a dark surface.
213
];
214

            
215
// -- label style (the `<p>` block wrapping the multi-line value) --
216
pub static TEXT_AREA_LABEL_PROPS: &[CssPropertyWithConditions] = &[
217
    // See text_input: the prompt's colour through the `::placeholder`
218
    // cascade, overridable by any app rule.
219
    CssPropertyWithConditions::on_placeholder(CssProperty::const_text_color(StyleTextColor {
220
        inner: COLOR_9B9B9B,
221
    })),
222
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
223
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
224
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
225
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(13))),
226
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
227
        inner: COLOR_4C4C4C,
228
    })),
229
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SANS_SERIF_FAMILY)),
230
    CssPropertyWithConditions::simple(CssProperty::WhiteSpace(StyleWhiteSpaceValue::Exact(
231
        StyleWhiteSpace::PreWrap,
232
    ))),
233
];
234

            
235
/// Multi-line text input widget.
236
#[derive(Debug, Clone, PartialEq, Eq)]
237
#[repr(C)]
238
pub struct TextArea {
239
    pub text_area_state: TextAreaStateWrapper,
240
    pub container_style: OptionCssPropertyWithConditionsVec,
241
    pub label_style: OptionCssPropertyWithConditionsVec,
242
    /// What this control is CALLED, for assistive technology.
243
    ///
244
    /// Carried by the WIDGET so it knows at build time whether it was named;
245
    /// forwarded into the accessibility declaration it already builds.
246
    pub accessibility_name: OptionString,
247
    pub theme: crate::widgets::themes::OptionUiTheme,
248
}
249

            
250
/// Editable state of a text area (text buffer + cursor position).
251
#[derive(Debug, Clone, PartialEq, Eq)]
252
#[repr(C)]
253
pub struct TextAreaState {
254
    /// The text buffer as `Vec<char>` (newlines included).
255
    pub text: U32Vec,
256
    pub placeholder: OptionString,
257
    pub max_len: usize,
258
    pub cursor_pos: usize,
259
}
260

            
261
/// [`TextAreaState`] together with optional user callbacks.
262
#[derive(Debug, Clone, PartialEq, Eq)]
263
#[repr(C)]
264
pub struct TextAreaStateWrapper {
265
    pub inner: TextAreaState,
266
    pub on_text_input: OptionTextAreaOnTextInput,
267
    pub on_focus_lost: OptionTextAreaOnFocusLost,
268
    pub update_text_area_before_calling_focus_lost_fn: bool,
269
    // appended at the END of the repr(C) struct for ABI stability
270
    pub on_virtual_key_down: OptionTextAreaOnVirtualKeyDown,
271
}
272

            
273
// -- callbacks --
274

            
275
/// Invoked on each text edit. Returns whether the edit is valid (reusing
276
/// [`TextInput`](crate::widgets::text_input::TextInput)'s [`OnTextInputReturn`]).
277
pub type TextAreaOnTextInputCallbackType =
278
    extern "C" fn(RefAny, CallbackInfo, TextAreaState) -> OnTextInputReturn;
279
impl_widget_callback!(
280
    TextAreaOnTextInput,
281
    OptionTextAreaOnTextInput,
282
    TextAreaOnTextInputCallback,
283
    TextAreaOnTextInputCallbackType
284
);
285

            
286
azul_core::impl_managed_callback! {
287
    wrapper:        TextAreaOnTextInputCallback,
288
    info_ty:        CallbackInfo,
289
    return_ty:      OnTextInputReturn,
290
    default_ret:    OnTextInputReturn { update: Update::DoNothing, valid: TextInputValid::Yes },
291
    invoker_static: TEXT_AREA_ON_TEXT_INPUT_INVOKER,
292
    invoker_ty:     AzTextAreaOnTextInputCallbackInvoker,
293
    thunk_fn:       az_text_area_on_text_input_callback_thunk,
294
    setter_fn:      AzApp_setTextAreaOnTextInputCallbackInvoker,
295
    from_handle_fn: AzTextAreaOnTextInputCallback_createFromHostHandle,
296
    extra_args:     [ state: TextAreaState ],
297
}
298

            
299
/// Invoked on every virtual-key press while the text area is focused (reusing
300
/// [`TextInput`](crate::widgets::text_input::TextInput)'s [`OnTextInputReturn`]).
301
pub type TextAreaOnVirtualKeyDownCallbackType =
302
    extern "C" fn(RefAny, CallbackInfo, TextAreaState) -> OnTextInputReturn;
303
impl_widget_callback!(
304
    TextAreaOnVirtualKeyDown,
305
    OptionTextAreaOnVirtualKeyDown,
306
    TextAreaOnVirtualKeyDownCallback,
307
    TextAreaOnVirtualKeyDownCallbackType
308
);
309

            
310
azul_core::impl_managed_callback! {
311
    wrapper:        TextAreaOnVirtualKeyDownCallback,
312
    info_ty:        CallbackInfo,
313
    return_ty:      OnTextInputReturn,
314
    default_ret:    OnTextInputReturn { update: Update::DoNothing, valid: TextInputValid::Yes },
315
    invoker_static: TEXT_AREA_ON_VIRTUAL_KEY_DOWN_INVOKER,
316
    invoker_ty:     AzTextAreaOnVirtualKeyDownCallbackInvoker,
317
    thunk_fn:       az_text_area_on_virtual_key_down_callback_thunk,
318
    setter_fn:      AzApp_setTextAreaOnVirtualKeyDownCallbackInvoker,
319
    from_handle_fn: AzTextAreaOnVirtualKeyDownCallback_createFromHostHandle,
320
    extra_args:     [ state: TextAreaState ],
321
}
322

            
323
/// Invoked when the text area loses focus.
324
pub type TextAreaOnFocusLostCallbackType =
325
    extern "C" fn(RefAny, CallbackInfo, TextAreaState) -> Update;
326
impl_widget_callback!(
327
    TextAreaOnFocusLost,
328
    OptionTextAreaOnFocusLost,
329
    TextAreaOnFocusLostCallback,
330
    TextAreaOnFocusLostCallbackType
331
);
332

            
333
azul_core::impl_managed_callback! {
334
    wrapper:        TextAreaOnFocusLostCallback,
335
    info_ty:        CallbackInfo,
336
    return_ty:      Update,
337
    default_ret:    Update::DoNothing,
338
    invoker_static: TEXT_AREA_ON_FOCUS_LOST_INVOKER,
339
    invoker_ty:     AzTextAreaOnFocusLostCallbackInvoker,
340
    thunk_fn:       az_text_area_on_focus_lost_callback_thunk,
341
    setter_fn:      AzApp_setTextAreaOnFocusLostCallbackInvoker,
342
    from_handle_fn: AzTextAreaOnFocusLostCallback_createFromHostHandle,
343
    extra_args:     [ state: TextAreaState ],
344
}
345

            
346
impl Default for TextAreaState {
347
590
    fn default() -> Self {
348
590
        Self {
349
590
            text: Vec::new().into(),
350
590
            placeholder: None.into(),
351
590
            // Unlimited, like a browser <textarea> without `maxlength`. The
352
590
            // old default was an arbitrary 1000 that nothing enforced; now
353
590
            // that typing past `max_len` is vetoed (default_on_text_input),
354
590
            // keeping it would have silently capped every existing area.
355
590
            max_len: usize::MAX,
356
590
            cursor_pos: 0,
357
590
        }
358
590
    }
359
}
360

            
361
impl TextAreaState {
362
    /// Reconstructs the (multi-line) string, including `'\n'` characters.
363
    #[must_use]
364
205
    pub fn get_text(&self) -> String {
365
205
        self.text
366
205
            .iter()
367
380519
            .filter_map(|c| core::char::from_u32(*c))
368
205
            .collect()
369
205
    }
370
}
371

            
372
impl Default for TextAreaStateWrapper {
373
489
    fn default() -> Self {
374
489
        Self {
375
489
            inner: TextAreaState::default(),
376
489
            on_text_input: None.into(),
377
489
            on_focus_lost: None.into(),
378
489
            update_text_area_before_calling_focus_lost_fn: true,
379
489
            on_virtual_key_down: None.into(),
380
489
        }
381
489
    }
382
}
383

            
384
impl Default for TextArea {
385
397
    fn default() -> Self {
386
397
        Self {
387
397
            text_area_state: TextAreaStateWrapper::default(),
388
397
            container_style: OptionCssPropertyWithConditionsVec::None,
389
397
            label_style: OptionCssPropertyWithConditionsVec::None,
390
397
            accessibility_name: OptionString::None,
391
397
            theme: crate::widgets::themes::OptionUiTheme::Some(
392
397
                crate::widgets::themes::UiTheme::Flat,
393
397
            ),
394
397
        }
395
397
    }
396
}
397

            
398
impl TextArea {
399
    /// The container style this widget renders with.
400
    ///
401
    /// `None` means no opinion, so the widget's default applies — the same
402
    /// answer both themes give, asked in one place.
403
    #[must_use]
404
275
    pub fn resolved_container_style(&self) -> CssPropertyWithConditionsVec {
405
275
        self.container_style
406
275
            .clone()
407
275
            .into_option()
408
275
            .unwrap_or_else(|| {
409
271
                CssPropertyWithConditionsVec::from_const_slice(TEXT_AREA_CONTAINER_PROPS)
410
271
            })
411
275
    }
412

            
413
    /// The label style this widget renders with.
414
    ///
415
    /// `None` means no opinion, so the widget's default applies — the same
416
    /// answer both themes give, asked in one place.
417
    #[must_use]
418
3
    pub fn resolved_label_style(&self) -> CssPropertyWithConditionsVec {
419
3
        self.label_style.clone().into_option().unwrap_or_else(|| {
420
3
            CssPropertyWithConditionsVec::from_const_slice(TEXT_AREA_LABEL_PROPS)
421
3
        })
422
3
    }
423

            
424
    /// Name this control for assistive technology.
425
    #[must_use]
426
    pub fn with_accessibility_name<S: Into<AzString>>(mut self, name: S) -> Self {
427
        self.accessibility_name = Some(name.into()).into();
428
        self
429
    }
430

            
431
    #[must_use]
432
386
    pub fn create() -> Self {
433
386
        Self::default()
434
386
    }
435

            
436
    /// Sets the (multi-line) text. Newlines in `text` are preserved.
437
    #[allow(clippy::needless_pass_by_value)] // public by-value setter; builder with_text moves the
438
                                             // arg in
439
233
    pub fn set_text(&mut self, text: AzString) {
440
233
        self.text_area_state.inner.text = text
441
233
            .as_str()
442
233
            .chars()
443
543279
            .map(|c| c as u32)
444
233
            .collect::<Vec<_>>()
445
233
            .into();
446
233
    }
447

            
448
    #[must_use]
449
204
    pub fn with_text(mut self, text: AzString) -> Self {
450
204
        self.set_text(text);
451
204
        self
452
204
    }
453

            
454
    /// Pick the widget theme. Unset (`None`), the widget renders in the
455
    /// default theme (`crate::widgets::themes::UiTheme::default()`).
456
    pub const fn set_theme(&mut self, theme: crate::widgets::themes::UiTheme) {
457
        self.theme = crate::widgets::themes::OptionUiTheme::Some(theme);
458
    }
459

            
460
    /// [`Self::set_theme`] for the builder chain.
461
    #[must_use]
462
    pub const fn with_theme(mut self, theme: crate::widgets::themes::UiTheme) -> Self {
463
        self.set_theme(theme);
464
        self
465
    }
466

            
467
33
    pub fn set_placeholder(&mut self, placeholder: AzString) {
468
33
        self.text_area_state.inner.placeholder = Some(placeholder).into();
469
33
    }
470

            
471
    #[must_use]
472
30
    pub fn with_placeholder(mut self, placeholder: AzString) -> Self {
473
30
        self.set_placeholder(placeholder);
474
30
        self
475
30
    }
476

            
477
6
    pub fn set_on_text_input<C: Into<TextAreaOnTextInputCallback>>(
478
6
        &mut self,
479
6
        refany: RefAny,
480
6
        callback: C,
481
6
    ) {
482
6
        self.text_area_state.on_text_input = Some(TextAreaOnTextInput {
483
6
            callback: callback.into(),
484
6
            refany,
485
6
        })
486
6
        .into();
487
6
    }
488

            
489
    #[must_use]
490
4
    pub fn with_on_text_input<C: Into<TextAreaOnTextInputCallback>>(
491
4
        mut self,
492
4
        refany: RefAny,
493
4
        callback: C,
494
4
    ) -> Self {
495
4
        self.set_on_text_input(refany, callback);
496
4
        self
497
4
    }
498

            
499
2
    pub fn set_on_virtual_key_down<C: Into<TextAreaOnVirtualKeyDownCallback>>(
500
2
        &mut self,
501
2
        refany: RefAny,
502
2
        callback: C,
503
2
    ) {
504
2
        self.text_area_state.on_virtual_key_down = Some(TextAreaOnVirtualKeyDown {
505
2
            callback: callback.into(),
506
2
            refany,
507
2
        })
508
2
        .into();
509
2
    }
510

            
511
    #[must_use]
512
2
    pub fn with_on_virtual_key_down<C: Into<TextAreaOnVirtualKeyDownCallback>>(
513
2
        mut self,
514
2
        refany: RefAny,
515
2
        callback: C,
516
2
    ) -> Self {
517
2
        self.set_on_virtual_key_down(refany, callback);
518
2
        self
519
2
    }
520

            
521
5
    pub fn set_on_focus_lost<C: Into<TextAreaOnFocusLostCallback>>(
522
5
        &mut self,
523
5
        refany: RefAny,
524
5
        callback: C,
525
5
    ) {
526
5
        self.text_area_state.on_focus_lost = Some(TextAreaOnFocusLost {
527
5
            callback: callback.into(),
528
5
            refany,
529
5
        })
530
5
        .into();
531
5
    }
532

            
533
    #[must_use]
534
4
    pub fn with_on_focus_lost<C: Into<TextAreaOnFocusLostCallback>>(
535
4
        mut self,
536
4
        refany: RefAny,
537
4
        callback: C,
538
4
    ) -> Self {
539
4
        self.set_on_focus_lost(refany, callback);
540
4
        self
541
4
    }
542

            
543
4
    pub fn set_container_style(&mut self, style: CssPropertyWithConditionsVec) {
544
4
        self.container_style = OptionCssPropertyWithConditionsVec::Some(style);
545
4
    }
546

            
547
    #[must_use]
548
3
    pub fn with_container_style(mut self, style: CssPropertyWithConditionsVec) -> Self {
549
3
        self.set_container_style(style);
550
3
        self
551
3
    }
552

            
553
    #[must_use]
554
4
    pub fn swap_with_default(&mut self) -> Self {
555
4
        let mut s = Self::default();
556
4
        core::mem::swap(&mut s, self);
557
4
        s
558
4
    }
559

            
560
    /// Renders the widget.
561
    ///
562
    /// The container is the `contenteditable` host — the flag, the tab index and
563
    /// the focus callbacks all sit on it, because focus events do not bubble and
564
    /// the engine records an edit against the *focused* node. Its two children
565
    /// are `<p>` blocks wrapping a bare text node each; nothing else is emitted,
566
    /// in particular no caret node.
567
    #[must_use]
568
267
    pub fn dom(self) -> Dom {
569
267
        match self.theme {
570
            crate::widgets::themes::OptionUiTheme::None => Dom::create_div(),
571
            crate::widgets::themes::OptionUiTheme::Some(crate::widgets::themes::UiTheme::Flat) => {
572
267
                crate::widgets::themes::flat::text_area(self)
573
            }
574
            crate::widgets::themes::OptionUiTheme::Some(crate::widgets::themes::UiTheme::Flora) => {
575
                crate::widgets::themes::flora::text_area(self)
576
            }
577
        }
578
267
    }
579
}
580

            
581
/// The value `<p>` - the editable line the engine paints the `placeholder`
582
/// attribute's prompt into while it is empty and unfocused.
583
///
584
/// Resolved through the same hierarchy hop the container's own layout
585
/// guarantees; a subtree of any other shape yields `None` and every handler
586
/// bails out. (Was `label_nodes`, returning an overlay node too, until the
587
/// prompt became an engine-painted attribute.)
588
94
fn value_node(info: &CallbackInfo) -> Option<DomNodeId> {
589
94
    let child = info.get_first_child(info.get_hit_node())?;
590
    // SHAPE GUARD: the value `<p>` always wraps exactly one text leaf, so a
591
    // childless first child means the hit node was NOT the container (it was
592
    // the value line itself, whose first child IS that leaf). The two-child
593
    // layout used to get this for free - `first child -> next sibling` walked
594
    // off the end - and a handler that mutates the buffer on a malformed
595
    // subtree silently diverges the model from the screen.
596
83
    let node = child.node.into_crate_internal()?;
597
83
    if info.get_children_count(child.dom, node) == 0 {
598
        return None;
599
83
    }
600
83
    Some(child)
601
94
}
602

            
603
/// Adopts the engine's text for `node` into the widget's mirror.
604
///
605
/// The engine owns the buffer, so its answer wins — except that an empty answer
606
/// is ambiguous: `get_text_before_textinput` also yields nothing for a node
607
/// whose text sits under a block wrapper it does not descend into. An empty
608
/// read therefore never clears a non-empty mirror.
609
83
fn adopt_engine_text(state: &mut TextAreaState, info: &CallbackInfo, node: DomNodeId) {
610
83
    let Some(text) = info.get_node_text_content(node) else {
611
        return;
612
    };
613
83
    if text.is_empty() && !state.text.is_empty() {
614
44
        return;
615
39
    }
616
39
    state.text = text.chars().map(|c| c as u32).collect::<Vec<_>>().into();
617
83
}
618

            
619
/// Mirrors the insertion the engine is about to apply.
620
///
621
/// The engine inserts at the caret, so the mirror does too whenever the caret
622
/// is readable and lands on a character boundary; otherwise it appends, which
623
/// is where the caret sits for every append-only path. `cursor_pos` stays a
624
/// byte offset, as it has always been.
625
71
fn mirror_insertion(state: &mut TextAreaState, inserted: &str, caret: Option<usize>) {
626
71
    let text = state.get_text();
627
71
    let at = caret
628
71
        .filter(|at| *at <= text.len() && text.is_char_boundary(*at))
629
71
        .unwrap_or(text.len());
630

            
631
71
    let mut next = String::with_capacity(text.len() + inserted.len());
632
71
    next.push_str(&text[..at]);
633
71
    next.push_str(inserted);
634
71
    next.push_str(&text[at..]);
635

            
636
160320
    state.text = next.chars().map(|c| c as u32).collect::<Vec<_>>().into();
637
71
    state.cursor_pos = at.saturating_add(inserted.len());
638
71
}
639

            
640
/// The caret's byte offset inside the edited node, if the engine has one.
641
43
fn engine_caret(info: &CallbackInfo, node: DomNodeId) -> Option<usize> {
642
43
    info.get_node_cursor_position(node)
643
43
        .map(|c| c.cluster_id.start_byte_in_run as usize)
644
43
}
645

            
646
#[must_use]
647
10
pub extern "C" fn default_on_focus_received(
648
10
    mut text_area: RefAny,
649
10
    mut info: CallbackInfo,
650
10
) -> Update {
651
10
    let Some(mut text_area) = text_area.downcast_mut::<TextAreaStateWrapper>() else {
652
1
        return Update::DoNothing;
653
    };
654

            
655
9
    let text_area = &mut *text_area;
656

            
657
9
    let Some(_value) = value_node(&info) else {
658
3
        return Update::DoNothing;
659
    };
660

            
661
6
    let container = info.get_hit_node();
662
6
    adopt_engine_text(&mut text_area.inner, &info, container);
663

            
664
    // The prompt hides itself: the engine paints it only while the value is
665
    // empty AND unfocused, recomputed per display list.
666

            
667
    // The engine seeds the caret at the end of the value when focus lands on a
668
    // contenteditable host; the mirror follows it.
669
6
    let end_of_text = text_area.inner.text.len();
670
6
    text_area.inner.cursor_pos = engine_caret(&info, container).unwrap_or(end_of_text);
671

            
672
6
    Update::DoNothing
673
10
}
674

            
675
#[must_use]
676
9
pub extern "C" fn default_on_focus_lost(mut text_area: RefAny, mut info: CallbackInfo) -> Update {
677
9
    let Some(mut text_area) = text_area.downcast_mut::<TextAreaStateWrapper>() else {
678
1
        return Update::DoNothing;
679
    };
680

            
681
8
    let text_area = &mut *text_area;
682

            
683
8
    let Some(_value) = value_node(&info) else {
684
2
        return Update::DoNothing;
685
    };
686

            
687
6
    let container = info.get_hit_node();
688
6
    adopt_engine_text(&mut text_area.inner, &info, container);
689

            
690
    // The prompt reappears on its own once the blur lands.
691

            
692
6
    let text_area = &mut *text_area;
693
6
    let onfocuslost = &mut text_area.on_focus_lost;
694
6
    let inner = text_area.inner.clone();
695

            
696
6
    match onfocuslost.as_mut() {
697
2
        Some(TextAreaOnFocusLost { callback, refany }) => {
698
2
            (callback.cb)(refany.clone(), info, inner)
699
        }
700
4
        None => Update::DoNothing,
701
    }
702
9
}
703

            
704
#[must_use]
705
1
pub extern "C" fn default_on_text_input(text_area: RefAny, info: CallbackInfo) -> Update {
706
1
    default_on_text_input_inner(text_area, info).unwrap_or(Update::DoNothing)
707
1
}
708

            
709
44
fn default_on_text_input_inner(mut text_area: RefAny, mut info: CallbackInfo) -> Option<Update> {
710
44
    let mut text_area = text_area.downcast_mut::<TextAreaStateWrapper>()?;
711

            
712
    // The engine records the edit before the callbacks run and applies it after
713
    // them; this handler only observes it and mirrors it into the widget state.
714
    // An `Input` WITHOUT a pending record is a post-edit NOTIFICATION: an edit
715
    // committed outside the record pipeline (deletion, the Enter line break,
716
    // programmatic edit) that is already applied — adopt it and inform the
717
    // user hook; `valid` cannot veto what already happened.
718
43
    let inserted_text = info
719
43
        .get_text_changeset()
720
43
        .map(|c| c.inserted_text.as_str().to_string())
721
43
        .unwrap_or_default();
722

            
723
43
    let _value = value_node(&info)?;
724
40
    let container = info.get_hit_node();
725

            
726
40
    if inserted_text.is_empty() {
727
        // Idempotent: a notification that changed nothing observable stays a
728
        // strict no-op, so the no-changeset pins keep holding.
729
3
        let before = text_area.inner.get_text();
730
3
        adopt_engine_text(&mut text_area.inner, &info, container);
731
3
        if text_area.inner.get_text() == before {
732
3
            return None;
733
        }
734
        let result = {
735
            let text_area = &mut *text_area;
736
            let inner_clone = text_area.inner.clone();
737
            match text_area.on_text_input.as_mut() {
738
                Some(TextAreaOnTextInput { callback, refany }) => {
739
                    (callback.cb)(refany.clone(), info, inner_clone)
740
                }
741
                None => OnTextInputReturn {
742
                    update: Update::DoNothing,
743
                    valid: TextInputValid::Yes,
744
                },
745
            }
746
        };
747
        return Some(result.update);
748
37
    }
749

            
750
37
    let caret = engine_caret(&info, container);
751
37
    adopt_engine_text(&mut text_area.inner, &info, container);
752

            
753
    // maxlength: veto an insertion that would GROW the value past `max_len`
754
    // (counted in characters, the stored unit). Replacement-aware: the engine
755
    // deletes the live selection before inserting, so the prospective length
756
    // is current − selected + inserted. An edit that shrinks or holds the
757
    // length always passes, and a value pushed over the limit programmatically
758
    // (`set_text` is deliberately NOT capped) can still be edited back down.
759
    {
760
37
        let current = text_area.inner.get_text();
761
37
        let current_chars = current.chars().count();
762
37
        let selected_chars = info
763
37
            .get_node_selection_ranges(container)
764
37
            .as_ref()
765
37
            .first()
766
37
            .map_or(0, |range| {
767
                let from = range.start.cluster_id.start_byte_in_run as usize;
768
                let to = range.end.cluster_id.start_byte_in_run as usize;
769
                let (a, b) = (from.min(to), from.max(to));
770
                if b <= current.len() && current.is_char_boundary(a) && current.is_char_boundary(b)
771
                {
772
                    current[a..b].chars().count()
773
                } else {
774
                    0
775
                }
776
            });
777
37
        let prospective = current_chars
778
37
            .saturating_sub(selected_chars)
779
37
            .saturating_add(inserted_text.chars().count());
780
37
        if prospective > text_area.inner.max_len && prospective > current_chars {
781
1
            info.prevent_default();
782
1
            return Some(Update::DoNothing);
783
36
        }
784
    }
785

            
786
36
    let result = {
787
36
        let text_area = &mut *text_area;
788
36
        let ontextinput = &mut text_area.on_text_input;
789

            
790
        // inner_clone has the new (would-be) text
791
36
        let mut inner_clone = text_area.inner.clone();
792
36
        mirror_insertion(&mut inner_clone, &inserted_text, caret);
793

            
794
36
        match ontextinput.as_mut() {
795
2
            Some(TextAreaOnTextInput { callback, refany }) => {
796
2
                (callback.cb)(refany.clone(), info, inner_clone)
797
            }
798
34
            None => OnTextInputReturn {
799
34
                update: Update::DoNothing,
800
34
                valid: TextInputValid::Yes,
801
34
            },
802
        }
803
    };
804

            
805
36
    if result.valid == TextInputValid::Yes {
806
35
        // No placeholder bookkeeping: the first accepted character makes the
807
35
        // value non-empty and the engine stops painting the prompt.
808
35
        mirror_insertion(&mut text_area.inner, &inserted_text, caret);
809
35
    } else {
810
1
        // The engine applies the recorded changeset once the callbacks return,
811
1
        // unless one of them vetoes it.
812
1
        info.prevent_default();
813
1
    }
814

            
815
36
    Some(result.update)
816
44
}
817

            
818
#[must_use]
819
1
pub extern "C" fn default_on_virtual_key_down(text_area: RefAny, info: CallbackInfo) -> Update {
820
1
    default_on_virtual_key_down_inner(text_area, info).unwrap_or(Update::DoNothing)
821
1
}
822

            
823
37
fn default_on_virtual_key_down_inner(
824
37
    mut text_area: RefAny,
825
37
    mut info: CallbackInfo,
826
37
) -> Option<Update> {
827
37
    let mut text_area = text_area.downcast_mut::<TextAreaStateWrapper>()?;
828
36
    let keyboard_state = info.get_current_keyboard_state();
829

            
830
36
    let _keycode = keyboard_state.current_virtual_keycode.into_option()?;
831
34
    let _value = value_node(&info)?;
832

            
833
31
    let container = info.get_hit_node();
834
31
    adopt_engine_text(&mut text_area.inner, &info, container);
835

            
836
    // Editing keys (Backspace, Delete, the arrows, Enter) are the engine's
837
    // default actions; this handler only forwards the key to the user's hook
838
    // and lets a rejection stop the default from running.
839
31
    let result = {
840
        // rustc doesn't understand the borrowing lifetime here
841
31
        let text_area = &mut *text_area;
842
31
        let inner_clone = text_area.inner.clone();
843
31
        match text_area.on_virtual_key_down.as_mut() {
844
4
            Some(TextAreaOnVirtualKeyDown { callback, refany }) => {
845
4
                (callback.cb)(refany.clone(), info, inner_clone)
846
            }
847
27
            None => OnTextInputReturn {
848
27
                update: Update::DoNothing,
849
27
                valid: TextInputValid::Yes,
850
27
            },
851
        }
852
    };
853

            
854
31
    if result.valid == TextInputValid::No {
855
2
        info.prevent_default();
856
29
    }
857

            
858
31
    Some(result.update)
859
37
}
860

            
861
impl From<TextArea> for Dom {
862
    fn from(t: TextArea) -> Self {
863
        t.dom()
864
    }
865
}
866

            
867
#[cfg(test)]
868
// `redundant_closure`: NOT redundant here. `run()` takes
869
// `impl FnOnce(RefAny, CallbackInfo) -> R`; `CallbackInfo` carries an elided
870
// lifetime, so the bound is higher-ranked (`for<'a> FnOnce(_, CallbackInfo<'a>)`).
871
// The handlers are `extern "C" fn` items, which do NOT satisfy a higher-ranked
872
// `FnOnce` bound — passing one bare fails to compile with E0277. The `|r, ci| f(r, ci)`
873
// wrapper is what makes the coercion happen and must stay.
874
#[allow(clippy::redundant_closure)]
875
mod autotest_generated {
876
    use std::{
877
        collections::{BTreeMap, HashMap},
878
        sync::{Arc, Mutex},
879
    };
880

            
881
    use azul_core::{
882
        dom::{
883
            AttributeType, DomId, DomNodeId, EventFilter, FocusEventFilter, NodeId, NodeType,
884
            TabIndex,
885
        },
886
        geom::{LogicalRect, OptionLogicalPosition},
887
        gl::OptionGlContextPtr,
888
        hit_test::ScrollPosition,
889
        refany::OptionRefAny,
890
        resources::RendererResources,
891
        styled_dom::{NodeHierarchyItemId, StyledDom},
892
        window::{MonitorVec, RawWindowHandle, VirtualKeyCode},
893
    };
894
    use azul_css::dynamic_selector::{DynamicSelector, PseudoStateType, ThemeCondition};
895
    use rust_fontconfig::FcFontCache;
896

            
897
    use super::*;
898
    #[cfg(feature = "icu")]
899
    use crate::icu::IcuLocalizerHandle;
900
    use crate::{
901
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
902
        managers::text_input::PendingTextEdit,
903
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
904
        widgets::theme_probe,
905
        window::{DomLayoutResult, LayoutWindow},
906
        window_state::FullWindowState,
907
    };
908

            
909
    // ==================================================================
910
    // Sample data
911
    // ==================================================================
912

            
913
    /// Strings the buffer must round-trip verbatim through `set_text` ->
914
    /// `get_text`. Every entry is a valid Rust `str`, so none of them can be
915
    /// lost to the `char::from_u32` filter in `get_text` — anything that does
916
    /// not come back is real damage, not an encoding limit.
917
    const ROUND_TRIP: [&str; 22] = [
918
        "",
919
        " ",
920
        "a",
921
        "hello",
922
        "\n",
923
        "\n\n\n",
924
        "a\nb",
925
        "a\r\nb", // CRLF: *both* units have to survive
926
        "trailing\n",
927
        "\nleading",
928
        "\t\ttabbed",
929
        "\0", // NUL is a perfectly good `char`
930
        "line1\nline2\nline3",
931
        "ünïcödé",
932
        "e\u{301}", // combining acute: 2 chars, 1 grapheme
933
        "😀",       // astral plane: 1 char, 4 bytes
934
        "👩‍👩‍👧‍👦",       // ZWJ family: 7 chars, 25 bytes
935
        "🇩🇪",       // regional-indicator pair
936
        "مرحبا",    // RTL
937
        "日本語",
938
        "a\u{200b}b", // zero-width space wedged between two letters
939
        "\u{10FFFF}", // the largest scalar value there is
940
    ];
941

            
942
    /// `u32` values that are *not* Unicode scalar values. The buffer is a
943
    /// `U32Vec`, not a `String`, so it can hold them — `get_text` has to drop
944
    /// them rather than panic.
945
    const NON_SCALAR: [u32; 6] = [
946
        0xD800, // lone high surrogate
947
        0xDBFF,
948
        0xDC00, // lone low surrogate
949
        0xDFFF,
950
        0x0011_0000, // one past the last scalar value
951
        u32::MAX,
952
    ];
953

            
954
    // ==================================================================
955
    // Fixtures
956
    // ==================================================================
957

            
958
    /// A state buffer built from a `&str` exactly the way `set_text` builds it.
959
    fn buffer(text: &str) -> U32Vec {
960
        text.chars().map(|c| c as u32).collect::<Vec<_>>().into()
961
    }
962

            
963
    /// A `TextAreaStateWrapper` with no user hooks, holding `text`.
964
    fn wrapper(text: &str) -> TextAreaStateWrapper {
965
        TextAreaStateWrapper {
966
            inner: TextAreaState {
967
                text: buffer(text),
968
                ..TextAreaState::default()
969
            },
970
            ..TextAreaStateWrapper::default()
971
        }
972
    }
973

            
974
    /// The state currently stored behind a `TextAreaStateWrapper` payload.
975
    fn read(state: &RefAny) -> TextAreaState {
976
        let mut handle = state.clone();
977
        let w = handle
978
            .downcast_ref::<TextAreaStateWrapper>()
979
            .expect("the payload must still be a TextAreaStateWrapper");
980
        w.inner.clone()
981
    }
982

            
983
    /// Mutates the shared state behind a payload (the borrow is released before
984
    /// this returns, so a handler may be invoked right afterwards).
985
    fn poke(state: &RefAny, f: impl FnOnce(&mut TextAreaStateWrapper)) {
986
        let mut handle = state.clone();
987
        let mut w = handle
988
            .downcast_mut::<TextAreaStateWrapper>()
989
            .expect("the payload must still be a TextAreaStateWrapper");
990
        f(&mut w);
991
    }
992

            
993
    /// `n` properties lifted off the default container style — an easy way to
994
    /// mint pairwise-distinct style vectors without hard-coding CSS.
995
    fn style(n: usize) -> CssPropertyWithConditionsVec {
996
        let all: Vec<CssPropertyWithConditions> = TextArea::default()
997
            .resolved_container_style()
998
            .as_slice()
999
            .to_vec();
        assert!(n <= all.len(), "not enough default properties to slice");
        CssPropertyWithConditionsVec::from_vec(all.into_iter().take(n).collect())
    }
    /// The text a node carries, looking through the `<p>` block wrapper the
    /// widget convention mandates (`p > text`).
    fn text_of(node: &Dom) -> Option<&str> {
        match node.root.get_node_type() {
            NodeType::Text(s) => Some(s.as_ref().as_str()),
            NodeType::P => match node.children.as_ref() {
                [only] => match only.root.get_node_type() {
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
                    _ => None,
                },
                _ => None,
            },
            _ => None,
        }
    }
    // ---- recording hooks -------------------------------------------------
    //
    // NOTE: each hook below has a deliberately *different* body. Identical
    // function bodies can be folded onto a single symbol by the linker, and
    // these callbacks are compared by function-pointer identity.
    /// Records every `TextAreaState` an `on_text_input` / `on_virtual_key_down`
    /// hook is handed, and answers with a fixed verdict.
    struct EditLog {
        seen: Vec<TextAreaState>,
        ret: OnTextInputReturn,
    }
    /// Records every `TextAreaState` an `on_focus_lost` hook is handed.
    struct FocusLog {
        seen: Vec<TextAreaState>,
        ret: Update,
    }
    extern "C" fn record_text_input(
        mut data: RefAny,
        _: CallbackInfo,
        state: TextAreaState,
    ) -> OnTextInputReturn {
        let Some(mut log) = data.downcast_mut::<EditLog>() else {
            return OnTextInputReturn {
                update: Update::DoNothing,
                valid: TextInputValid::Yes,
            };
        };
        log.seen.push(state);
        log.ret
    }
    extern "C" fn record_virtual_key(
        mut data: RefAny,
        _: CallbackInfo,
        state: TextAreaState,
    ) -> OnTextInputReturn {
        match data.downcast_mut::<EditLog>() {
            Some(mut log) => {
                log.seen.push(state.clone());
                log.ret
            }
            None => OnTextInputReturn {
                update: Update::RefreshDom,
                valid: TextInputValid::Yes,
            },
        }
    }
    extern "C" fn record_focus_lost(
        mut data: RefAny,
        _: CallbackInfo,
        state: TextAreaState,
    ) -> Update {
        let mut update = Update::DoNothing;
        if let Some(mut log) = data.downcast_mut::<FocusLog>() {
            log.seen.push(state);
            update = log.ret;
        }
        update
    }
    fn edit_log(ret: OnTextInputReturn) -> RefAny {
        RefAny::new(EditLog {
            seen: Vec::new(),
            ret,
        })
    }
    fn focus_log(ret: Update) -> RefAny {
        RefAny::new(FocusLog {
            seen: Vec::new(),
            ret,
        })
    }
    fn edits_seen(log: &RefAny) -> Vec<TextAreaState> {
        let mut handle = log.clone();
        let l = handle
            .downcast_ref::<EditLog>()
            .expect("the payload must still be an EditLog");
        l.seen.clone()
    }
    fn focus_seen(log: &RefAny) -> Vec<TextAreaState> {
        let mut handle = log.clone();
        let l = handle
            .downcast_ref::<FocusLog>()
            .expect("the payload must still be a FocusLog");
        l.seen.clone()
    }
    const ACCEPT: OnTextInputReturn = OnTextInputReturn {
        update: Update::RefreshDom,
        valid: TextInputValid::Yes,
    };
    const REJECT: OnTextInputReturn = OnTextInputReturn {
        update: Update::RefreshDomAllWindows,
        valid: TextInputValid::No,
    };
    // ==================================================================
    // CallbackInfo harness
    // ==================================================================
    /// Flattened node indices of a `TextArea::dom()`.
    #[derive(Copy, Clone, Debug)]
    struct Nodes {
        container: usize,
        label: usize,
        label_text: usize,
    }
    /// Which node the event hit.
    #[derive(Copy, Clone, Debug)]
    enum Hit {
        /// `NodeHierarchyItemId::NONE` — no node was hit at all.
        Nothing,
        Container,
        /// The value's bare text leaf: it has no children, so every handler
        /// must bail out.
        TextLeaf,
    }
    /// Flattened indices of every node carrying `class`, in tree order.
    fn nodes_with_class(styled: &StyledDom, class: &str) -> Vec<usize> {
        styled
            .node_data
            .as_ref()
            .iter()
            .enumerate()
            .filter(|(_, nd)| nd.has_class(class))
            .map(|(i, _)| i)
            .collect()
    }
    /// A styled, but never laid out, `TextArea::dom()` — the handlers only walk
    /// `styled_dom.node_hierarchy`, so no real layout (and no font) is needed.
    /// The DOM here is a pure *navigation skeleton*: the state a handler edits
    /// is always the `RefAny` passed to it, never this DOM's own dataset.
    fn skeleton() -> (StyledDom, Nodes) {
        let styled = StyledDom::create_from_dom(TextArea::create().dom());
        fn one(styled: &StyledDom, class: &str) -> usize {
            let found = nodes_with_class(styled, class);
            assert_eq!(found.len(), 1, "expected exactly one `{class}` node");
            found[0]
        }
        let label = one(&styled, "__azul-native-text-area-label");
        let nodes = Nodes {
            container: one(&styled, "__azul-native-text-area-container"),
            label,
            label_text: first_child(&styled, label),
        };
        (styled, nodes)
    }
    /// The flattened index of `node`'s first child.
    fn first_child(styled: &StyledDom, node: usize) -> usize {
        styled
            .node_hierarchy
            .as_ref()
            .get(node)
            .and_then(|item| item.first_child_id(NodeId::new(node)))
            .expect("expected a child node")
            .index()
    }
    fn dom_node(idx: usize) -> DomNodeId {
        DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
        }
    }
    /// A `DomLayoutResult` with an empty layout tree and no display list.
    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 the handlers read out of the window.
    struct Env {
        /// `false` installs a `LayoutWindow` with no layout result at all — the
        /// "callback fired before the first layout" case.
        with_dom: bool,
        changeset: Option<PendingTextEdit>,
        keycode: Option<VirtualKeyCode>,
        hit: Hit,
    }
    impl Default for Env {
        fn default() -> Self {
            Self {
                with_dom: true,
                changeset: None,
                keycode: None,
                hit: Hit::Container,
            }
        }
    }
    impl Env {
        fn typed(text: &str) -> Self {
            Self {
                changeset: Some(PendingTextEdit {
                    node: dom_node(0),
                    inserted_text: AzString::from(text),
                    old_text: AzString::from(""),
                }),
                ..Self::default()
            }
        }
        fn key(code: VirtualKeyCode) -> Self {
            Self {
                keycode: Some(code),
                ..Self::default()
            }
        }
        fn hitting(mut self, hit: Hit) -> Self {
            self.hit = hit;
            self
        }
    }
    /// Invokes `call` against a `LayoutWindow` built from `env`. Returns the
    /// handler's value, every recorded `CallbackChange`, and the node indices.
    fn run<R>(
        env: Env,
        data: &RefAny,
        call: impl FnOnce(RefAny, CallbackInfo) -> R,
    ) -> (R, Vec<CallbackChange>, Nodes) {
        let (styled, nodes) = skeleton();
        let mut layout_window =
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
        if env.with_dom {
            layout_window
                .layout_results
                .insert(DomId::ROOT_ID, layout_result(styled));
        }
        if let Some(changeset) = env.changeset {
            layout_window.text_input_manager.set_changeset(changeset);
        }
        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(azul_css::system::SystemStyle::default()),
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
            #[cfg(feature = "icu")]
            icu_localizer: IcuLocalizerHandle::default(),
            ctx: OptionRefAny::None,
        };
        let hit = match env.hit {
            Hit::Nothing => DomNodeId {
                dom: DomId::ROOT_ID,
                node: NodeHierarchyItemId::NONE,
            },
            Hit::Container => dom_node(nodes.container),
            Hit::TextLeaf => dom_node(nodes.label_text),
        };
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
        let info = CallbackInfo::new(
            &ref_data,
            &changes,
            hit,
            OptionLogicalPosition::None,
            OptionLogicalPosition::None,
        );
        let out = call(data.clone(), info);
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
        (out, recorded, nodes)
    }
    /// Every opacity write in the change log, as `(node index, normalized opacity)`.
    fn opacity_writes(changes: &[CallbackChange]) -> Vec<(usize, f32)> {
        let mut out = Vec::new();
        for change in changes {
            if let CallbackChange::ChangeNodeCssProperties {
                node_id,
                properties,
                ..
            } = change
            {
                for p in properties.as_ref() {
                    if let CssProperty::Opacity(v) = p {
                        if let Some(o) = v.get_property() {
                            out.push((node_id.index(), o.inner.normalized()));
                        }
                    }
                }
            }
        }
        out
    }
    /// Every text write in the change log, as `(node index, new text)`.
    fn text_writes(changes: &[CallbackChange]) -> Vec<(usize, String)> {
        changes
            .iter()
            .filter_map(|change| match change {
                CallbackChange::ChangeNodeText { node_id, text } => Some((
                    node_id
                        .node
                        .into_crate_internal()
                        .expect("a text write always targets a real node")
                        .index(),
                    text.as_str().to_string(),
                )),
                _ => None,
            })
            .collect()
    }
    // ==================================================================
    // TextAreaState::get_text
    // ==================================================================
    #[test]
    fn get_text_on_a_default_state_is_empty() {
        let state = TextAreaState::default();
        assert_eq!(state.get_text(), "");
        assert!(state.text.is_empty());
        assert_eq!(state.cursor_pos, 0);
        // Unlimited by default, like a <textarea> without `maxlength`.
        assert_eq!(state.max_len, usize::MAX);
        assert!(state.placeholder.is_none());
    }
    #[test]
    fn get_text_round_trips_every_sample_string() {
        for s in ROUND_TRIP {
            let area = TextArea::create().with_text(AzString::from(s));
            assert_eq!(
                area.text_area_state.inner.get_text(),
                s,
                "set_text -> get_text must be lossless for {s:?}"
            );
            assert_eq!(
                area.text_area_state.inner.text.len(),
                s.chars().count(),
                "the buffer counts chars, not bytes, for {s:?}"
            );
        }
    }
    #[test]
    fn get_text_drops_code_units_that_are_not_scalar_values() {
        // A `U32Vec` is not a `String`: it can hold surrogates and out-of-range
        // values. `get_text` must silently drop them, never panic.
        for unit in NON_SCALAR {
            let state = TextAreaState {
                text: vec![unit].into(),
                ..TextAreaState::default()
            };
            assert_eq!(
                state.get_text(),
                "",
                "0x{unit:X} is not a scalar value and must not reach the string"
            );
            assert_eq!(state.text.len(), 1, "the raw buffer keeps the unit");
        }
    }
    #[test]
    fn get_text_keeps_the_scalars_around_dropped_units() {
        let mut units = vec!['a' as u32];
        units.extend(NON_SCALAR);
        units.push('b' as u32);
        let state = TextAreaState {
            text: units.into(),
            ..TextAreaState::default()
        };
        assert_eq!(
            state.get_text(),
            "ab",
            "only the non-scalars may be dropped"
        );
        assert_eq!(state.text.len(), NON_SCALAR.len() + 2);
    }
    #[test]
    fn get_text_accepts_the_boundary_scalars() {
        // The exact edges of the two legal ranges: 0, the last code point below
        // the surrogate block, the first above it, and the very last scalar.
        let units = vec![0x0000, 0xD7FF, 0xE000, 0x0010_FFFF];
        let state = TextAreaState {
            text: units.clone().into(),
            ..TextAreaState::default()
        };
        assert_eq!(
            state.get_text().chars().count(),
            units.len(),
            "every boundary scalar must survive"
        );
    }
    #[test]
    fn get_text_handles_a_very_large_buffer() {
        let big: String = "line 😀 ünicode\n".repeat(20_000);
        let area = TextArea::create().with_text(AzString::from(big.as_str()));
        assert_eq!(area.text_area_state.inner.text.len(), big.chars().count());
        assert_eq!(area.text_area_state.inner.get_text(), big);
    }
    // ==================================================================
    // TextArea::create
    // ==================================================================
    #[test]
    fn create_equals_default() {
        assert_eq!(TextArea::create(), TextArea::default());
    }
    #[test]
    fn create_starts_empty_with_no_hooks() {
        let area = TextArea::create();
        let s = &area.text_area_state;
        assert!(s.inner.text.is_empty());
        assert!(s.inner.placeholder.is_none());
        assert_eq!(s.inner.max_len, usize::MAX);
        assert_eq!(s.inner.cursor_pos, 0);
        assert!(s.on_text_input.is_none());
        assert!(s.on_virtual_key_down.is_none());
        assert!(s.on_focus_lost.is_none());
        assert!(s.update_text_area_before_calling_focus_lost_fn);
    }
    #[test]
    fn create_ships_both_style_vectors_non_empty() {
        // Two slots, not three: the prompt is styled through the
        // `::placeholder` cascade (an `on_placeholder` declaration on the
        // label), not through a separate vector with no node to apply to.
        let area = TextArea::create();
        assert!(!area.resolved_container_style().as_ref().is_empty());
        assert!(!area.resolved_label_style().as_ref().is_empty());
    }
    #[test]
    fn create_is_repeatable_and_unshared() {
        // Two areas must be equal but must not alias: editing one may not be
        // visible in the other.
        let mut a = TextArea::create();
        let b = TextArea::create();
        a.set_text(AzString::from("mutated"));
        assert_ne!(a, b);
        assert_eq!(b.text_area_state.inner.get_text(), "");
    }
    // ==================================================================
    // TextArea::set_text / with_text
    // ==================================================================
    #[test]
    fn set_text_preserves_newlines() {
        let mut area = TextArea::create();
        area.set_text(AzString::from("a\nb\n\nc\n"));
        assert_eq!(area.text_area_state.inner.get_text(), "a\nb\n\nc\n");
        assert_eq!(
            area.text_area_state
                .inner
                .text
                .iter()
                .filter(|c| **c == '\n' as u32)
                .count(),
            4,
            "all four newlines have to be stored"
        );
    }
    #[test]
    fn set_text_replaces_rather_than_appends() {
        let mut area = TextArea::create();
        area.set_text(AzString::from("first"));
        area.set_text(AzString::from("second"));
        assert_eq!(area.text_area_state.inner.get_text(), "second");
        assert_eq!(area.text_area_state.inner.text.len(), 6);
    }
    #[test]
    fn set_text_with_an_empty_string_clears_the_buffer() {
        let mut area = TextArea::create().with_text(AzString::from("something"));
        area.set_text(AzString::from(""));
        assert!(area.text_area_state.inner.text.is_empty());
        assert_eq!(area.text_area_state.inner.get_text(), "");
    }
    #[test]
    fn with_text_is_exactly_set_text() {
        for s in ROUND_TRIP {
            let mut a = TextArea::create();
            a.set_text(AzString::from(s));
            let b = TextArea::create().with_text(AzString::from(s));
            assert_eq!(a, b, "the builder and the setter must agree for {s:?}");
        }
    }
    #[test]
    fn set_text_ignores_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.
        let mut area = TextArea::create();
        area.text_area_state.inner.max_len = 3;
        area.set_text(AzString::from("far past the limit"));
        assert_eq!(area.text_area_state.inner.text.len(), 18);
        assert_eq!(area.text_area_state.inner.max_len, 3);
    }
    #[test]
    fn set_text_leaves_a_stale_cursor_behind() {
        // `set_text` does not touch `cursor_pos`, so shrinking the text can
        // leave the cursor pointing past the end. `dom()` is what repairs it.
        let mut area = TextArea::create().with_text(AzString::from("0123456789"));
        area.text_area_state.inner.cursor_pos = 10;
        area.set_text(AzString::from(""));
        assert_eq!(
            area.text_area_state.inner.cursor_pos, 10,
            "the setter deliberately leaves the cursor alone"
        );
        assert!(area.text_area_state.inner.text.is_empty());
        let dom = area.dom();
        let mut dataset = dom
            .root
            .get_dataset()
            .cloned()
            .expect("dom() must attach the state");
        let w = dataset
            .downcast_ref::<TextAreaStateWrapper>()
            .expect("the dataset must be a TextAreaStateWrapper");
        assert_eq!(w.inner.cursor_pos, 0, "dom() must repair the stale cursor");
    }
    #[test]
    fn set_text_does_not_disturb_the_other_fields() {
        let area = TextArea::create()
            .with_placeholder(AzString::from("type here"))
            .with_container_style(style(3))
            .with_text(AzString::from("body"));
        assert_eq!(
            area.text_area_state
                .inner
                .placeholder
                .as_ref()
                .map(AzString::as_str),
            Some("type here")
        );
        assert_eq!(area.resolved_container_style().len(), 3);
        assert_eq!(area.text_area_state.inner.get_text(), "body");
    }
    // ==================================================================
    // TextArea::set_placeholder / with_placeholder
    // ==================================================================
    #[test]
    fn placeholder_round_trips_every_sample_string() {
        for s in ROUND_TRIP {
            let area = TextArea::create().with_placeholder(AzString::from(s));
            assert_eq!(
                area.text_area_state
                    .inner
                    .placeholder
                    .as_ref()
                    .map(AzString::as_str),
                Some(s)
            );
        }
    }
    #[test]
    fn an_empty_placeholder_is_some_not_none() {
        // `Some("")` and `None` are different states: only the former means
        // "the user explicitly asked for no placeholder text".
        let area = TextArea::create().with_placeholder(AzString::from(""));
        assert!(area.text_area_state.inner.placeholder.is_some());
        assert_eq!(
            area.text_area_state
                .inner
                .placeholder
                .as_ref()
                .map(AzString::as_str),
            Some("")
        );
    }
    #[test]
    fn set_placeholder_overwrites_the_previous_one() {
        let mut area = TextArea::create();
        area.set_placeholder(AzString::from("one"));
        area.set_placeholder(AzString::from("two"));
        assert_eq!(
            area.text_area_state
                .inner
                .placeholder
                .as_ref()
                .map(AzString::as_str),
            Some("two")
        );
    }
    #[test]
    fn with_placeholder_is_exactly_set_placeholder() {
        let mut a = TextArea::create();
        a.set_placeholder(AzString::from("hint"));
        let b = TextArea::create().with_placeholder(AzString::from("hint"));
        assert_eq!(a, b);
    }
    #[test]
    fn set_placeholder_does_not_touch_the_text() {
        let area = TextArea::create()
            .with_text(AzString::from("body\ntext"))
            .with_placeholder(AzString::from("hint"));
        assert_eq!(area.text_area_state.inner.get_text(), "body\ntext");
        assert_eq!(area.text_area_state.inner.cursor_pos, 0);
    }
    // ==================================================================
    // TextArea::set_on_* / with_on_*
    // ==================================================================
    #[test]
    fn each_hook_setter_touches_only_its_own_slot() {
        let text_in = TextArea::create().with_on_text_input(
            RefAny::new(1u32),
            record_text_input as TextAreaOnTextInputCallbackType,
        );
        assert!(text_in.text_area_state.on_text_input.is_some());
        assert!(text_in.text_area_state.on_virtual_key_down.is_none());
        assert!(text_in.text_area_state.on_focus_lost.is_none());
        let key_down = TextArea::create().with_on_virtual_key_down(
            RefAny::new(2u32),
            record_virtual_key as TextAreaOnVirtualKeyDownCallbackType,
        );
        assert!(key_down.text_area_state.on_text_input.is_none());
        assert!(key_down.text_area_state.on_virtual_key_down.is_some());
        assert!(key_down.text_area_state.on_focus_lost.is_none());
        let focus = TextArea::create().with_on_focus_lost(
            RefAny::new(3u32),
            record_focus_lost as TextAreaOnFocusLostCallbackType,
        );
        assert!(focus.text_area_state.on_text_input.is_none());
        assert!(focus.text_area_state.on_virtual_key_down.is_none());
        assert!(focus.text_area_state.on_focus_lost.is_some());
    }
    #[test]
    fn hook_setters_keep_the_user_payload_reachable() {
        let payload = RefAny::new(0xDEAD_BEEF_u32);
        let area = TextArea::create().with_on_text_input(
            payload.clone(),
            record_text_input as TextAreaOnTextInputCallbackType,
        );
        let mut stored = area
            .text_area_state
            .on_text_input
            .as_ref()
            .expect("the hook must be stored")
            .refany
            .clone();
        assert_eq!(
            *stored
                .downcast_ref::<u32>()
                .expect("payload type must survive"),
            0xDEAD_BEEF_u32
        );
    }
    #[test]
    fn setting_a_hook_twice_replaces_it_and_keeps_the_old_payload_alive() {
        let first = RefAny::new(11u32);
        let second = RefAny::new(22u32);
        let mut area = TextArea::create();
        area.set_on_text_input(
            first.clone(),
            record_text_input as TextAreaOnTextInputCallbackType,
        );
        area.set_on_text_input(second, record_text_input as TextAreaOnTextInputCallbackType);
        let mut stored = area
            .text_area_state
            .on_text_input
            .as_ref()
            .expect("the hook must be stored")
            .refany
            .clone();
        assert_eq!(*stored.downcast_ref::<u32>().expect("payload"), 22);
        // The replaced handle must not have been freed out from under us.
        let mut first = first;
        assert_eq!(*first.downcast_ref::<u32>().expect("payload"), 11);
    }
    #[test]
    fn with_on_hooks_are_exactly_their_setters() {
        let payload = RefAny::new(7u32);
        let mut a = TextArea::create();
        a.set_on_focus_lost(
            payload.clone(),
            record_focus_lost as TextAreaOnFocusLostCallbackType,
        );
        let b = TextArea::create().with_on_focus_lost(
            payload,
            record_focus_lost as TextAreaOnFocusLostCallbackType,
        );
        assert_eq!(a, b);
    }
    #[test]
    fn all_three_hooks_can_coexist() {
        let area = TextArea::create()
            .with_on_text_input(
                RefAny::new(1u32),
                record_text_input as TextAreaOnTextInputCallbackType,
            )
            .with_on_virtual_key_down(
                RefAny::new(2u32),
                record_virtual_key as TextAreaOnVirtualKeyDownCallbackType,
            )
            .with_on_focus_lost(
                RefAny::new(3u32),
                record_focus_lost as TextAreaOnFocusLostCallbackType,
            )
            .with_text(AzString::from("still here"));
        assert!(area.text_area_state.on_text_input.is_some());
        assert!(area.text_area_state.on_virtual_key_down.is_some());
        assert!(area.text_area_state.on_focus_lost.is_some());
        assert_eq!(area.text_area_state.inner.get_text(), "still here");
    }
    #[test]
    fn hook_setters_leave_a_zero_sized_payload_usable() {
        // A `RefAny` over a ZST is the degenerate case for the refcount /
        // destructor plumbing.
        struct Zst;
        let area = TextArea::create().with_on_text_input(
            RefAny::new(Zst),
            record_text_input as TextAreaOnTextInputCallbackType,
        );
        let mut stored = area
            .text_area_state
            .on_text_input
            .as_ref()
            .expect("the hook must be stored")
            .refany
            .clone();
        assert!(stored.downcast_ref::<Zst>().is_some());
        assert!(
            stored.downcast_ref::<u32>().is_none(),
            "the type tag must still discriminate"
        );
    }
    // ==================================================================
    // TextArea::set_container_style / with_container_style
    // ==================================================================
    #[test]
    fn set_container_style_replaces_the_whole_vector() {
        let mut area = TextArea::create();
        let before = area.resolved_container_style().len();
        area.set_container_style(style(2));
        assert_eq!(area.resolved_container_style().len(), 2);
        assert_ne!(before, 2, "the fixture has to actually change something");
    }
    #[test]
    fn an_empty_container_style_is_accepted() {
        let area = TextArea::create()
            .with_container_style(CssPropertyWithConditionsVec::from_vec(Vec::new()));
        assert!(area.resolved_container_style().as_ref().is_empty());
        // ...and still produces a DOM.
        let dom = area.dom();
        assert_eq!(dom.children.as_ref().len(), 1);
    }
    #[test]
    fn container_style_does_not_leak_into_the_other_style_slots() {
        let default_label = TextArea::create().resolved_label_style();
        let area = TextArea::create().with_container_style(style(1));
        assert_eq!(area.resolved_label_style(), default_label);
    }
    // ==================================================================
    // TextArea::swap_with_default
    // ==================================================================
    #[test]
    fn swap_with_default_hands_back_the_old_value_and_resets_self() {
        let mut area = TextArea::create()
            .with_text(AzString::from("keep\nme"))
            .with_placeholder(AzString::from("hint"));
        let old = area.swap_with_default();
        assert_eq!(old.text_area_state.inner.get_text(), "keep\nme");
        assert_eq!(
            old.text_area_state
                .inner
                .placeholder
                .as_ref()
                .map(AzString::as_str),
            Some("hint")
        );
        assert_eq!(area, TextArea::default(), "self must be a fresh default");
    }
    #[test]
    fn swap_with_default_twice_yields_a_default_the_second_time() {
        let mut area = TextArea::create().with_text(AzString::from("x"));
        let first = area.swap_with_default();
        let second = area.swap_with_default();
        assert_eq!(first.text_area_state.inner.get_text(), "x");
        assert_eq!(second, TextArea::default());
        assert_eq!(area, TextArea::default());
    }
    #[test]
    fn swap_with_default_carries_the_hooks_out_with_it() {
        let payload = RefAny::new(99u32);
        let mut area = TextArea::create().with_on_focus_lost(
            payload,
            record_focus_lost as TextAreaOnFocusLostCallbackType,
        );
        let old = area.swap_with_default();
        assert!(old.text_area_state.on_focus_lost.is_some());
        assert!(area.text_area_state.on_focus_lost.is_none());
        let mut stored = old
            .text_area_state
            .on_focus_lost
            .as_ref()
            .expect("hook")
            .refany
            .clone();
        assert_eq!(*stored.downcast_ref::<u32>().expect("payload"), 99);
    }
    // ==================================================================
    // TextArea::dom
    // ==================================================================
    #[test]
    fn dom_has_the_shape_the_handlers_navigate() {
        let dom = TextArea::create().dom();
        let children = dom.children.as_ref();
        assert_eq!(
            children.len(),
            1,
            "a text area is exactly [label] - the prompt is an ATTRIBUTE on it"
        );
        assert!(dom.root.has_class("__azul-native-text-area-container"));
        assert!(children[0].root.has_class("__azul-native-text-area-label"));
        for block in children {
            assert!(matches!(block.root.get_node_type(), NodeType::P));
            assert_eq!(
                block.children.as_ref().len(),
                1,
                "a label wraps one text node"
            );
            let leaf = &block.children.as_ref()[0];
            assert!(matches!(leaf.root.get_node_type(), NodeType::Text(_)));
            assert!(leaf.children.as_ref().is_empty(), "the text node is a leaf");
        }
    }
    #[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.
        let styled = StyledDom::create_from_dom(TextArea::create().dom());
        assert!(nodes_with_class(&styled, "__azul-native-text-area-cursor").is_empty());
    }
    #[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>.
        fn walk(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() {
                walk(c, is_p, bad);
            }
        }
        for area in [
            TextArea::create(),
            TextArea::create()
                .with_text(AzString::from("a\nb"))
                .with_placeholder(AzString::from("hint")),
        ] {
            let mut bad = Vec::new();
            walk(&area.dom(), false, &mut bad);
            assert!(bad.is_empty(), "text nodes carrying inert state: {bad:?}");
        }
    }
    #[test]
    fn dom_carries_the_themes_hover_and_focus_border_states_with_dark_twins() {
        // The rules moved OUT of `TEXT_AREA_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 the
        // theme silently forgets to append them. Hence this test.
        let dom = TextArea::create().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,
                "{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,
                "{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(),
            "the theme contributed no dark-mode declarations at all"
        );
    }
    #[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 = TextArea::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() {
        // Everything inside a contenteditable host is editable content unless a
        // node blocks the inheritance walk; the prompt must never be typed into.
        let dom = TextArea::create()
            .with_placeholder(AzString::from("hint"))
            .dom();
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 1, "the prompt must not be a node at all");
        assert_eq!(
            children[0].root.get_placeholder(),
            Some("hint"),
            "the prompt rides on the value line as an attribute",
        );
        assert_eq!(
            text_of(&children[0]),
            Some(""),
            "and it is NOT part of the editable content",
        );
    }
    #[test]
    fn dom_renders_the_text_into_the_label_and_the_prompt_into_the_attribute() {
        let dom = TextArea::create()
            .with_text(AzString::from("body\nlines"))
            .with_placeholder(AzString::from("hint"))
            .dom();
        let children = dom.children.as_ref();
        assert_eq!(children[0].root.get_placeholder(), Some("hint"));
        assert_eq!(text_of(&children[0]), Some("body\nlines"));
    }
    #[test]
    fn dom_renders_an_empty_placeholder_attribute_when_none_was_set() {
        // No prompt set: the attribute is present but empty, and the engine
        // paints nothing for an empty prompt.
        let dom = TextArea::create().with_text(AzString::from("x")).dom();
        assert_eq!(dom.children.as_ref()[0].root.get_placeholder(), Some(""));
    }
    #[test]
    fn dom_round_trips_every_sample_string_into_the_label() {
        for s in ROUND_TRIP {
            let dom = TextArea::create().with_text(AzString::from(s)).dom();
            assert_eq!(
                text_of(&dom.children.as_ref()[0]),
                Some(s),
                "the label must render {s:?} verbatim"
            );
        }
    }
    #[test]
    fn dom_drops_non_scalar_units_from_the_label() {
        let mut area = TextArea::create().with_text(AzString::from("ab"));
        let mut units = area
            .text_area_state
            .inner
            .text
            .clone()
            .into_library_owned_vec();
        units.extend(NON_SCALAR);
        area.text_area_state.inner.text = units.into();
        let dom = area.dom();
        assert_eq!(
            text_of(&dom.children.as_ref()[0]),
            Some("ab"),
            "the rendered label may only contain real scalars"
        );
    }
    #[test]
    fn dom_snaps_the_cursor_to_the_end_of_the_buffer() {
        for (text, expected) in [("", 0), ("abc", 3), ("😀😀", 2), ("a\nb", 3)] {
            let mut area = TextArea::create().with_text(AzString::from(text));
            area.text_area_state.inner.cursor_pos = usize::MAX;
            let dom = area.dom();
            let mut dataset = dom.root.get_dataset().cloned().expect("dataset");
            let w = dataset
                .downcast_ref::<TextAreaStateWrapper>()
                .expect("the dataset must be a TextAreaStateWrapper");
            assert_eq!(
                w.inner.cursor_pos, expected,
                "dom() must clamp the cursor to the buffer for {text:?}"
            );
        }
    }
    #[test]
    fn dom_wires_up_all_four_focus_callbacks() {
        let dom = TextArea::create().dom();
        let callbacks = dom.root.get_callbacks();
        assert_eq!(callbacks.len(), 4);
        let expected = [
            (
                EventFilter::Focus(FocusEventFilter::FocusReceived),
                default_on_focus_received as usize,
            ),
            (
                EventFilter::Focus(FocusEventFilter::FocusLost),
                default_on_focus_lost as usize,
            ),
            (
                EventFilter::Focus(FocusEventFilter::TextInput),
                default_on_text_input as usize,
            ),
            (
                EventFilter::Focus(FocusEventFilter::VirtualKeyDown),
                default_on_virtual_key_down as usize,
            ),
        ];
        for (cd, (event, cb)) in callbacks.as_ref().iter().zip(expected) {
            assert_eq!(cd.event, event);
            assert_eq!(cd.callback.cb, cb, "wrong handler wired to {event:?}");
        }
    }
    #[test]
    fn dom_shares_one_state_handle_between_the_dataset_and_every_callback() {
        let dom = TextArea::create().with_text(AzString::from("seed")).dom();
        let dataset = dom.root.get_dataset().cloned().expect("dataset");
        poke(&dataset, |w| w.inner.max_len = 7);
        for cd in dom.root.get_callbacks().as_ref() {
            let mut handle = cd.refany.clone();
            let w = handle
                .downcast_ref::<TextAreaStateWrapper>()
                .expect("every callback must carry the state wrapper");
            assert_eq!(
                w.inner.max_len, 7,
                "every callback must see the *same* state object as the dataset"
            );
        }
    }
    #[test]
    fn dom_survives_a_very_large_buffer() {
        let big: String = "wide 😀 line\n".repeat(20_000);
        let dom = TextArea::create()
            .with_text(AzString::from(big.as_str()))
            .dom();
        assert_eq!(text_of(&dom.children.as_ref()[0]), Some(big.as_str()));
    }
    #[test]
    fn styled_dom_navigation_matches_what_the_handlers_assume() {
        // Every handler walks container -> first child (the value line). If
        // that walk ever stops matching the DOM, all of them silently no-op.
        // (It used to hop container -> placeholder -> next sibling; the
        // prompt is an attribute now, so the value line IS the first child.)
        let (styled, nodes) = skeleton();
        let hierarchy = styled.node_hierarchy.as_container();
        let label = hierarchy[NodeId::new(nodes.container)]
            .first_child_id(NodeId::new(nodes.container))
            .expect("the container must have a first child");
        assert_eq!(label.index(), nodes.label);
        let leaf = hierarchy[label]
            .first_child_id(label)
            .expect("the value block must wrap a text node");
        assert_eq!(leaf.index(), nodes.label_text);
        assert!(
            hierarchy[leaf].first_child_id(leaf).is_none(),
            "the text node is a leaf"
        );
    }
    // ==================================================================
    // default_on_focus_received
    // ==================================================================
    #[test]
    fn focus_received_ignores_a_foreign_payload() {
        let data = RefAny::new(0u8);
        let (update, changes, _) = run(Env::default(), &data, |r, ci| {
            default_on_focus_received(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a foreign payload must not touch the DOM"
        );
    }
    #[test]
    fn focus_received_bails_out_without_a_hit_node() {
        let data = RefAny::new(wrapper(""));
        poke(&data, |w| w.inner.cursor_pos = 42);
        let (update, changes, _) = run(Env::default().hitting(Hit::Nothing), &data, |r, ci| {
            default_on_focus_received(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(
            read(&data).cursor_pos,
            42,
            "the early return happens *before* the cursor is repaired"
        );
    }
    #[test]
    fn focus_received_bails_out_on_a_childless_hit_node() {
        let data = RefAny::new(wrapper("text"));
        let (update, changes, _) = run(Env::default().hitting(Hit::TextLeaf), &data, |r, ci| {
            default_on_focus_received(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn focus_writes_no_placeholder_css_at_all() {
        let empty = RefAny::new(wrapper(""));
        let (update, changes, nodes) = run(Env::default(), &empty, |r, ci| {
            default_on_focus_received(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "focus must write NO css: empty+unfocused is recomputed per display list, so there is \
             no override to set (or to latch)"
        );
        let _ = nodes;
        let filled = RefAny::new(wrapper("typed"));
        let (update, changes, _) = run(Env::default(), &filled, |r, ci| {
            default_on_focus_received(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a non-empty area has nothing to hide — the placeholder is already gone"
        );
    }
    #[test]
    fn focus_received_repairs_a_stale_cursor() {
        for (text, expected) in [("", 0usize), ("abc", 3), ("😀 x", 3)] {
            let data = RefAny::new(wrapper(text));
            poke(&data, |w| w.inner.cursor_pos = usize::MAX);
            let (_, _, _) = run(Env::default(), &data, |r, ci| {
                default_on_focus_received(r, ci)
            });
            assert_eq!(
                read(&data).cursor_pos,
                expected,
                "focus must snap the cursor to the end for {text:?}"
            );
        }
    }
    #[test]
    fn focus_received_does_not_edit_the_buffer() {
        let data = RefAny::new(wrapper("untouched\ntext"));
        let (_, _, _) = run(Env::default(), &data, |r, ci| {
            default_on_focus_received(r, ci)
        });
        assert_eq!(read(&data).get_text(), "untouched\ntext");
    }
    // ==================================================================
    // default_on_focus_lost
    // ==================================================================
    #[test]
    fn focus_lost_ignores_a_foreign_payload() {
        let data = RefAny::new("not a text area".to_string());
        let (update, changes, _) = run(Env::default(), &data, |r, ci| default_on_focus_lost(r, ci));
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn blur_writes_no_placeholder_css_at_all() {
        let empty = RefAny::new(wrapper(""));
        let (update, changes, nodes) =
            run(Env::default(), &empty, |r, ci| default_on_focus_lost(r, ci));
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty(), "blur must write no css either");
        let _ = nodes;
        let filled = RefAny::new(wrapper("typed"));
        let (update, changes, _) = run(Env::default(), &filled, |r, ci| {
            default_on_focus_lost(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn focus_lost_forwards_the_state_to_the_user_hook() {
        let log = focus_log(Update::RefreshDomAllWindows);
        let mut state = wrapper("saved\ntext");
        state.on_focus_lost = Some(TextAreaOnFocusLost {
            callback: (record_focus_lost as TextAreaOnFocusLostCallbackType).into(),
            refany: log.clone(),
        })
        .into();
        let data = RefAny::new(state);
        let (update, _, _) = run(Env::default(), &data, |r, ci| default_on_focus_lost(r, ci));
        assert_eq!(
            update,
            Update::RefreshDomAllWindows,
            "the hook's Update must be propagated verbatim"
        );
        let seen = focus_seen(&log);
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].get_text(), "saved\ntext");
    }
    #[test]
    fn focus_lost_skips_the_user_hook_when_the_dom_has_no_children() {
        // The DOM walk happens *before* the hook is dispatched, so a text area
        // whose node has no children never notifies its owner. Pinned as the
        // current contract, not endorsed as ideal.
        let log = focus_log(Update::RefreshDom);
        let mut state = wrapper("x");
        state.on_focus_lost = Some(TextAreaOnFocusLost {
            callback: (record_focus_lost as TextAreaOnFocusLostCallbackType).into(),
            refany: log.clone(),
        })
        .into();
        let data = RefAny::new(state);
        let (update, changes, _) = run(Env::default().hitting(Hit::TextLeaf), &data, |r, ci| {
            default_on_focus_lost(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(focus_seen(&log).is_empty(), "the hook must not have run");
    }
    #[test]
    fn focus_lost_hands_the_hook_a_snapshot_it_cannot_write_back_through() {
        // The hook receives a *clone* of the inner state; mutating it (which the
        // signature allows, it is by value) must not reach the widget.
        let log = focus_log(Update::DoNothing);
        let mut state = wrapper("original");
        state.on_focus_lost = Some(TextAreaOnFocusLost {
            callback: (record_focus_lost as TextAreaOnFocusLostCallbackType).into(),
            refany: log.clone(),
        })
        .into();
        let data = RefAny::new(state);
        let (_, _, _) = run(Env::default(), &data, |r, ci| default_on_focus_lost(r, ci));
        let mut seen = focus_seen(&log);
        assert_eq!(seen.len(), 1);
        seen[0].text = buffer("clobbered");
        assert_eq!(read(&data).get_text(), "original");
    }
    #[test]
    fn focus_lost_without_a_hook_reports_do_nothing() {
        let data = RefAny::new(wrapper("text"));
        let (update, _, _) = run(Env::default(), &data, |r, ci| default_on_focus_lost(r, ci));
        assert_eq!(update, Update::DoNothing);
    }
    #[test]
    fn focus_lost_does_not_move_the_cursor() {
        let data = RefAny::new(wrapper("abcdef"));
        poke(&data, |w| w.inner.cursor_pos = 2);
        let (_, _, _) = run(Env::default(), &data, |r, ci| default_on_focus_lost(r, ci));
        assert_eq!(
            read(&data).cursor_pos,
            2,
            "only focus-received re-snaps the cursor"
        );
    }
    // ==================================================================
    // default_on_text_input / default_on_text_input_inner
    // ==================================================================
    #[test]
    fn text_input_without_a_changeset_does_nothing() {
        let data = RefAny::new(wrapper("abc"));
        let (out, changes, _) = run(Env::default(), &data, default_on_text_input_inner);
        assert_eq!(out, None);
        assert!(changes.is_empty());
        assert_eq!(read(&data).get_text(), "abc");
    }
    #[test]
    fn text_input_with_an_empty_insertion_does_nothing() {
        let data = RefAny::new(wrapper("abc"));
        let (out, changes, _) = run(Env::typed(""), &data, default_on_text_input_inner);
        assert_eq!(out, None, "an empty insertion is not an edit");
        assert!(changes.is_empty());
        assert_eq!(read(&data).get_text(), "abc");
    }
    #[test]
    fn text_input_ignores_a_foreign_payload() {
        let data = RefAny::new(1234u64);
        let (out, changes, _) = run(Env::typed("x"), &data, default_on_text_input_inner);
        assert_eq!(out, None);
        assert!(changes.is_empty());
    }
    #[test]
    fn text_input_bails_out_on_a_childless_hit_node() {
        let data = RefAny::new(wrapper("abc"));
        let (out, changes, _) = run(
            Env::typed("x").hitting(Hit::TextLeaf),
            &data,
            default_on_text_input_inner,
        );
        assert_eq!(out, None);
        assert!(changes.is_empty());
        assert_eq!(read(&data).get_text(), "abc", "no DOM, no edit");
    }
    #[test]
    fn text_input_bails_out_when_the_hit_node_has_no_sibling_chain() {
        // Hitting the placeholder: its own text leaf has no next sibling, so
        // the walk stops one step in.
        let data = RefAny::new(wrapper("abc"));
        let (out, changes, _) = run(
            Env::typed("x").hitting(Hit::TextLeaf),
            &data,
            default_on_text_input_inner,
        );
        assert_eq!(out, None);
        assert!(changes.is_empty());
        assert_eq!(read(&data).get_text(), "abc");
    }
    #[test]
    fn text_input_mirrors_the_insertion_and_writes_no_placeholder_css() {
        // The FIRST character into an empty area used to write a display /
        // opacity override to hide the overlay prompt. The prompt is an
        // engine-painted attribute now: the line simply stops being empty.
        let data = RefAny::new(wrapper(""));
        let (out, changes, nodes) = run(Env::typed("cd"), &data, default_on_text_input_inner);
        assert_eq!(out, Some(Update::DoNothing), "no hook means no refresh");
        assert_eq!(read(&data).get_text(), "cd");
        assert!(
            opacity_writes(&changes).is_empty(),
            "typing must not toggle any placeholder override"
        );
        let _ = nodes;
        assert!(
            text_writes(&changes).is_empty(),
            "the widget repainted the value itself; the engine owns the buffer"
        );
        // ...and a keystroke into an already-filled area writes NOTHING:
        // the placeholder is already hidden, and re-writing the same
        // display/opacity override charged a full relayout per character
        // (2026-08-29). This test used to pin the redundant write.
        let data = RefAny::new(wrapper("ab"));
        let (out, changes, _) = run(Env::typed("cd"), &data, default_on_text_input_inner);
        assert_eq!(out, Some(Update::DoNothing));
        assert_eq!(read(&data).get_text(), "abcd");
        assert!(
            opacity_writes(&changes).is_empty(),
            "no transition, no placeholder write: {changes:?}"
        );
    }
    #[test]
    fn text_input_preserves_embedded_newlines() {
        let data = RefAny::new(wrapper("first"));
        let (out, changes, _) = run(Env::typed("\nsecond\n"), &data, default_on_text_input_inner);
        assert_eq!(out, Some(Update::DoNothing));
        assert_eq!(read(&data).get_text(), "first\nsecond\n");
        assert!(text_writes(&changes).is_empty());
    }
    #[test]
    fn text_input_stores_pasted_unicode_by_char() {
        for s in ROUND_TRIP {
            if s.is_empty() {
                continue; // an empty insertion is a documented no-op
            }
            let data = RefAny::new(wrapper(""));
            let (out, _, _) = run(Env::typed(s), &data, default_on_text_input_inner);
            assert_eq!(out, Some(Update::DoNothing), "insertion of {s:?}");
            let state = read(&data);
            assert_eq!(state.get_text(), s, "insertion of {s:?} must be lossless");
            assert_eq!(state.text.len(), s.chars().count());
        }
    }
    #[test]
    fn text_input_advances_the_cursor_by_bytes_not_chars() {
        // KNOWN QUIRK: the buffer grows by `chars`, but `cursor_pos` is advanced
        // by `inserted_text.len()`, which is a *byte* count. For any non-ASCII
        // insertion the cursor therefore ends up past the end of the buffer.
        // `dom()` and `default_on_focus_received` both re-snap it, which is why
        // this is survivable — pinned here so the divergence is visible.
        let data = RefAny::new(wrapper(""));
        let (_, _, _) = run(Env::typed("😀"), &data, default_on_text_input_inner);
        let state = read(&data);
        assert_eq!(state.text.len(), 1, "one char went into the buffer");
        assert_eq!(state.cursor_pos, 4, "but the cursor moved by four bytes");
        assert!(
            state.cursor_pos > state.text.len(),
            "the cursor is left past the end of the buffer"
        );
        // ASCII is the case where the two counts happen to agree.
        let ascii = RefAny::new(wrapper(""));
        let (_, _, _) = run(Env::typed("abcd"), &ascii, default_on_text_input_inner);
        let ascii_state = read(&ascii);
        assert_eq!(ascii_state.cursor_pos, ascii_state.text.len());
    }
    #[test]
    fn typing_past_max_len_is_vetoed() {
        // maxlength: a keystroke that would GROW the value past `max_len` is
        // vetoed — the widget keeps the old text and `PreventDefault` stops
        // the engine from applying the recorded changeset. (Programmatic
        // `set_text` stays uncapped; see `set_text_ignores_max_len`.)
        let data = RefAny::new(wrapper("ab"));
        poke(&data, |w| w.inner.max_len = 2);
        let (out, changes, _) = run(Env::typed("cdefgh"), &data, default_on_text_input_inner);
        assert_eq!(out, Some(Update::DoNothing));
        assert_eq!(
            read(&data).get_text(),
            "ab",
            "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:?}",
        );
    }
    #[test]
    fn text_input_shows_the_hook_the_would_be_text_before_committing() {
        let log = edit_log(ACCEPT);
        let mut state = wrapper("old");
        state.on_text_input = Some(TextAreaOnTextInput {
            callback: (record_text_input as TextAreaOnTextInputCallbackType).into(),
            refany: log.clone(),
        })
        .into();
        let data = RefAny::new(state);
        let (out, _, _) = run(Env::typed("+new"), &data, default_on_text_input_inner);
        assert_eq!(out, Some(Update::RefreshDom), "the hook's Update wins");
        let seen = edits_seen(&log);
        assert_eq!(seen.len(), 1);
        assert_eq!(
            seen[0].get_text(),
            "old+new",
            "the hook is shown the text as it *would* be after the edit"
        );
        assert_eq!(read(&data).get_text(), "old+new");
    }
    #[test]
    fn text_input_rejected_by_the_hook_changes_nothing() {
        let log = edit_log(REJECT);
        let mut state = wrapper("locked");
        state.on_text_input = Some(TextAreaOnTextInput {
            callback: (record_text_input as TextAreaOnTextInputCallbackType).into(),
            refany: log.clone(),
        })
        .into();
        let data = RefAny::new(state);
        let (out, changes, _) = run(Env::typed("nope"), &data, default_on_text_input_inner);
        assert_eq!(
            out,
            Some(Update::RefreshDomAllWindows),
            "a rejected edit still returns the hook's Update"
        );
        assert_eq!(
            changes.len(),
            1,
            "a rejected edit must push nothing but the preventDefault: {changes:?}"
        );
        assert!(matches!(changes[0], CallbackChange::PreventDefault));
        let state = read(&data);
        assert_eq!(state.get_text(), "locked");
        assert_eq!(state.cursor_pos, 0, "and must not move the cursor");
        assert_eq!(edits_seen(&log).len(), 1, "the hook still ran exactly once");
    }
    #[test]
    fn text_input_accumulates_across_edits() {
        let data = RefAny::new(wrapper(""));
        for chunk in ["a", "b\n", "c"] {
            let (out, _, _) = run(Env::typed(chunk), &data, default_on_text_input_inner);
            assert_eq!(out, Some(Update::DoNothing));
        }
        let state = read(&data);
        assert_eq!(state.get_text(), "ab\nc");
        assert_eq!(state.cursor_pos, 4);
    }
    #[test]
    fn text_input_drops_non_scalar_units_the_engine_could_never_hold() {
        // The mirror is rebuilt from the *string* the engine works in, so
        // non-scalar units planted directly into the buffer do not survive an
        // edit. Nothing can render them either, so there is nothing to lose.
        let data = RefAny::new(wrapper("a"));
        poke(&data, |w| {
            let mut units = w.inner.text.clone().into_library_owned_vec();
            units.extend(NON_SCALAR);
            w.inner.text = units.into();
        });
        let (out, changes, _) = run(Env::typed("b"), &data, default_on_text_input_inner);
        assert_eq!(out, Some(Update::DoNothing));
        assert!(text_writes(&changes).is_empty());
        assert_eq!(read(&data).get_text(), "ab");
        assert_eq!(read(&data).text.len(), 2);
    }
    #[test]
    fn text_input_extern_wrapper_maps_none_onto_do_nothing() {
        let data = RefAny::new(wrapper("abc"));
        let (update, changes, _) = run(Env::default(), &data, |r, ci| default_on_text_input(r, ci));
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn text_input_survives_a_very_large_insertion() {
        let big: String = "chunk 😀\n".repeat(10_000);
        let data = RefAny::new(wrapper(""));
        let (out, changes, _) = run(Env::typed(&big), &data, default_on_text_input_inner);
        assert_eq!(out, Some(Update::DoNothing));
        assert_eq!(read(&data).text.len(), big.chars().count());
        assert_eq!(read(&data).get_text(), big);
        assert!(text_writes(&changes).is_empty());
    }
    // ==================================================================
    // default_on_virtual_key_down / default_on_virtual_key_down_inner
    // ==================================================================
    #[test]
    fn virtual_key_down_without_a_keycode_does_nothing() {
        let data = RefAny::new(wrapper("abc"));
        let (out, changes, _) = run(Env::default(), &data, default_on_virtual_key_down_inner);
        assert_eq!(out, None);
        assert!(changes.is_empty());
        assert_eq!(read(&data).get_text(), "abc");
    }
    #[test]
    fn virtual_key_down_ignores_a_foreign_payload() {
        let data = RefAny::new(0i64);
        let (out, changes, _) = run(
            Env::key(VirtualKeyCode::Back),
            &data,
            default_on_virtual_key_down_inner,
        );
        assert_eq!(out, None);
        assert!(changes.is_empty());
    }
    #[test]
    fn virtual_key_down_bails_out_on_a_childless_hit_node() {
        let log = edit_log(ACCEPT);
        let mut state = wrapper("abc");
        state.on_virtual_key_down = Some(TextAreaOnVirtualKeyDown {
            callback: (record_virtual_key as TextAreaOnVirtualKeyDownCallbackType).into(),
            refany: log.clone(),
        })
        .into();
        let data = RefAny::new(state);
        let (out, changes, _) = run(
            Env::key(VirtualKeyCode::Back).hitting(Hit::TextLeaf),
            &data,
            default_on_virtual_key_down_inner,
        );
        assert_eq!(out, None);
        assert!(changes.is_empty());
        assert_eq!(read(&data).get_text(), "abc");
        assert!(
            edits_seen(&log).is_empty(),
            "the DOM walk precedes the hook, so it never ran"
        );
    }
    #[test]
    fn no_key_edits_the_buffer_behind_the_engine() {
        // Backspace, Delete and the arrows are `SystemChange::ApplySelectionOp`
        // and Enter records a structural block split — all of them engine
        // default actions. A widget that also edited its own buffer would
        // double-apply every one of them.
        for key in [
            VirtualKeyCode::Back,
            VirtualKeyCode::Delete,
            VirtualKeyCode::Return,
            VirtualKeyCode::NumpadEnter,
            VirtualKeyCode::Left,
            VirtualKeyCode::A,
            VirtualKeyCode::Space,
            VirtualKeyCode::Tab,
            VirtualKeyCode::Escape,
        ] {
            for text in ["", "abc", "a\nb"] {
                let data = RefAny::new(wrapper(text));
                let before = read(&data);
                let (out, changes, _) =
                    run(Env::key(key), &data, default_on_virtual_key_down_inner);
                assert_eq!(out, Some(Update::DoNothing), "{key:?} on {text:?}");
                assert!(
                    changes.is_empty(),
                    "{key:?} on {text:?} mutated the DOM: {changes:?}"
                );
                assert_eq!(read(&data), before, "{key:?} on {text:?} edited the mirror");
            }
        }
    }
    #[test]
    fn the_hook_runs_even_for_keys_that_do_not_edit() {
        let log = edit_log(ACCEPT);
        let mut state = wrapper("abc");
        state.on_virtual_key_down = Some(TextAreaOnVirtualKeyDown {
            callback: (record_virtual_key as TextAreaOnVirtualKeyDownCallbackType).into(),
            refany: log.clone(),
        })
        .into();
        let data = RefAny::new(state);
        let (out, changes, _) = run(
            Env::key(VirtualKeyCode::F1),
            &data,
            default_on_virtual_key_down_inner,
        );
        assert_eq!(
            out,
            Some(Update::RefreshDom),
            "the hook's Update is returned"
        );
        assert!(changes.is_empty());
        let seen = edits_seen(&log);
        assert_eq!(seen.len(), 1);
        assert_eq!(
            seen[0].get_text(),
            "abc",
            "the hook sees the pre-edit state"
        );
    }
    #[test]
    fn a_rejecting_hook_vetoes_the_engines_default_action() {
        for key in [VirtualKeyCode::Back, VirtualKeyCode::Return] {
            let log = edit_log(REJECT);
            let mut state = wrapper("frozen");
            state.on_virtual_key_down = Some(TextAreaOnVirtualKeyDown {
                callback: (record_virtual_key as TextAreaOnVirtualKeyDownCallbackType).into(),
                refany: log.clone(),
            })
            .into();
            let data = RefAny::new(state);
            let (out, changes, _) = run(Env::key(key), &data, default_on_virtual_key_down_inner);
            assert_eq!(out, Some(Update::RefreshDomAllWindows), "{key:?}");
            assert_eq!(
                changes.len(),
                1,
                "{key:?} pushed more than the veto: {changes:?}"
            );
            assert!(
                matches!(changes[0], CallbackChange::PreventDefault),
                "{key:?}"
            );
            assert_eq!(read(&data).get_text(), "frozen", "{key:?} must not edit");
            assert_eq!(edits_seen(&log).len(), 1);
        }
    }
    #[test]
    fn an_accepting_hook_leaves_the_default_action_alone_and_still_sets_the_update() {
        let log = edit_log(ACCEPT);
        let mut state = wrapper("ab");
        state.on_virtual_key_down = Some(TextAreaOnVirtualKeyDown {
            callback: (record_virtual_key as TextAreaOnVirtualKeyDownCallbackType).into(),
            refany: log.clone(),
        })
        .into();
        let data = RefAny::new(state);
        let (out, changes, _) = run(
            Env::key(VirtualKeyCode::Back),
            &data,
            default_on_virtual_key_down_inner,
        );
        assert_eq!(out, Some(Update::RefreshDom));
        assert!(
            changes.is_empty(),
            "an accepted key must push nothing: {changes:?}"
        );
        assert_eq!(read(&data).get_text(), "ab", "the engine owns the deletion");
    }
    #[test]
    fn virtual_key_down_extern_wrapper_maps_none_onto_do_nothing() {
        let data = RefAny::new(wrapper("abc"));
        let (update, changes, _) = run(Env::default(), &data, |r, ci| {
            default_on_virtual_key_down(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn successive_insertions_accumulate_in_the_mirror_without_touching_the_dom() {
        // The engine repaints the value; the widget only tracks what was
        // inserted so its callbacks can hand the host a current state.
        let data = RefAny::new(wrapper(""));
        for (chunk, expected) in [
            ("hello", "hello"),
            ("\n", "hello\n"),
            ("world", "hello\nworld"),
        ] {
            let (_, changes, _) = run(Env::typed(chunk), &data, default_on_text_input_inner);
            assert!(
                text_writes(&changes).is_empty(),
                "the widget repainted the value for {chunk:?}"
            );
            assert_eq!(read(&data).get_text(), expected);
        }
        assert_eq!(read(&data).cursor_pos, "hello\nworld".len());
    }
    // ==================================================================
    // Every handler, fired before the first layout
    // ==================================================================
    /// An `Env` whose `LayoutWindow` holds no layout result at all — the state a
    /// callback sees if it is dispatched before the DOM has ever been laid out.
    fn before_first_layout() -> Env {
        Env {
            with_dom: false,
            ..Env::default()
        }
    }
    #[test]
    fn focus_received_is_inert_before_the_first_layout() {
        let data = RefAny::new(wrapper(""));
        poke(&data, |w| w.inner.cursor_pos = 5);
        let (update, changes, _) = run(before_first_layout(), &data, |r, ci| {
            default_on_focus_received(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(
            read(&data).cursor_pos,
            5,
            "the cursor is not repaired either"
        );
    }
    #[test]
    fn focus_lost_is_inert_before_the_first_layout() {
        let log = focus_log(Update::RefreshDom);
        let mut state = wrapper("");
        state.on_focus_lost = Some(TextAreaOnFocusLost {
            callback: (record_focus_lost as TextAreaOnFocusLostCallbackType).into(),
            refany: log.clone(),
        })
        .into();
        let data = RefAny::new(state);
        let (update, changes, _) = run(before_first_layout(), &data, |r, ci| {
            default_on_focus_lost(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(focus_seen(&log).is_empty());
    }
    #[test]
    fn text_input_is_inert_before_the_first_layout() {
        let data = RefAny::new(wrapper("abc"));
        let env = Env {
            with_dom: false,
            ..Env::typed("xyz")
        };
        let (out, changes, _) = run(env, &data, default_on_text_input_inner);
        assert_eq!(out, None);
        assert!(changes.is_empty());
        assert_eq!(read(&data).get_text(), "abc", "no DOM to walk, no edit");
    }
    #[test]
    fn virtual_key_down_is_inert_before_the_first_layout() {
        for key in [VirtualKeyCode::Back, VirtualKeyCode::Return] {
            let data = RefAny::new(wrapper("abc"));
            let env = Env {
                with_dom: false,
                ..Env::key(key)
            };
            let (out, changes, _) = run(env, &data, default_on_virtual_key_down_inner);
            assert_eq!(out, None, "{key:?}");
            assert!(changes.is_empty(), "{key:?}");
            assert_eq!(read(&data).get_text(), "abc", "{key:?}");
        }
    }
}