1
//! Post-layout developer warnings for misused raw text nodes.
2
//!
3
//! Browsers wrap a raw text run in an ANONYMOUS BLOCK whenever it needs one;
4
//! azul does not. A bare `NodeType::Text` therefore has no box of its own —
5
//! no rect, no clip, no layout constraints — and every box-model CSS
6
//! property, every id or class a stylesheet could reach it by, and every
7
//! pointer or focus callback, `tab_index` or `dataset` attached to one is
8
//! silently inert. (Lifecycle and window listeners are not: they are
9
//! delivered by node identity, not through a box - see
10
//! `has_box_dependent_callback`.) That silence has shipped real bugs (text
11
//! escaping its widget, click targets that never fire), which is why the raw
12
//! constructor is named `create_text_do_not_use_without_block_level_wrapper`
13
//! and why this pass exists: after layout, every text node in a shape azul
14
//! cannot honor is reported to the developer, once per unique finding.
15
//!
16
//! The checks are structural (DOM + computed display), deliberately not
17
//! geometric: they fire deterministically on the first layout of a DOM,
18
//! before any symptom is visible on screen.
19
//!
20
//! This runs after EVERY layout pass, in release, so it is built to cost
21
//! nothing on a clean DOM: the scan allocates only once a finding exists,
22
//! message text (two allocations for the snippet alone) is rendered only for
23
//! a warning that is actually printed, and the per-parent questions ("is
24
//! there a block-level child?", "how many items?") are answered once per
25
//! parent instead of once per text child.
26

            
27
use std::{
28
    collections::BTreeSet,
29
    hash::{Hash, Hasher},
30
    mem::discriminant,
31
    sync::Mutex,
32
};
33

            
34
use azul_core::{
35
    dom::{AttributeType, NodeType},
36
    events::EventFilter,
37
    id::NodeId,
38
    styled_dom::{NodeHierarchyItem, StyledDom},
39
};
40
use azul_css::props::layout::LayoutDisplay;
41

            
42
use crate::solver3::getters::{get_display_property, MultiValue};
43

            
44
/// Distinct findings kept alive process-wide. A DOM that is wrong in a
45
/// hundred places has one bug, not a hundred; past this the developer is
46
/// told the tap was closed rather than having the log drowned.
47
const MAX_DISTINCT_WARNINGS: usize = 32;
48

            
49
/// Findings already reported, keyed by [`dedup_key`], process-wide. Layouts
50
/// re-run constantly (every DOM refresh); a warning that repeats 60 times a
51
/// second is a warning nobody reads.
52
struct Emitted {
53
    keys: BTreeSet<u64>,
54
    capped: bool,
55
}
56

            
57
static EMITTED: Mutex<Emitted> = Mutex::new(Emitted {
58
    keys: BTreeSet::new(),
59
    capped: false,
60
});
61

            
62
/// The suppression tag for this lint, honored from the `AZ_SUPPRESS`
63
/// environment variable (comma-separated list; the common misspelling
64
/// `AZ_SUPRESS` is accepted too). Every emitted warning names it.
65
pub const SUPPRESS_TAG: &str = "bare_text";
66

            
67
/// `AZ_SUPPRESS=bare_text` (checked once): the developer has read the
68
/// warnings and wants them off — e.g. a codebase that deliberately renders
69
/// raw text and accepts the differences from browser behavior.
70
7990
fn is_suppressed() -> bool {
71
    static SUPPRESSED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
72
7990
    *SUPPRESSED.get_or_init(|| {
73
32
        let v = std::env::var("AZ_SUPPRESS")
74
32
            .or_else(|_| std::env::var("AZ_SUPRESS"))
75
32
            .unwrap_or_default();
76
32
        v.split(',')
77
32
            .any(|t| t.trim().eq_ignore_ascii_case(SUPPRESS_TAG))
78
32
    })
79
7990
}
80

            
81
/// State on a text node that a text node cannot carry, as a bitset so the
82
/// scan can record a finding without allocating.
83
const INERT_CSS: u8 = 1 << 0;
84
const INERT_IDS_CLASSES: u8 = 1 << 1;
85
const INERT_CALLBACKS: u8 = 1 << 2;
86
const INERT_TAB_INDEX: u8 = 1 << 3;
87
const INERT_DATASET: u8 = 1 << 4;
88
const INERT_CHILDREN: u8 = 1 << 5;
89

            
90
/// One finding, kept as a tag until a message is known to be needed.
91
#[derive(Clone, Copy)]
92
enum Finding {
93
    /// W1 — box-less node carrying state (bitset of the `INERT_*` flags).
94
    Inert(u8),
95
    /// W2 — the text run is the root: nothing owns its box.
96
    NoParent,
97
    /// W2 — text nested directly inside text.
98
    TextParent,
99
    /// W2 — one of several items in a flex/grid container.
100
    FlexItem {
101
        display: LayoutDisplay,
102
        child_count: usize,
103
    },
104
    /// W2 — mixed inline/block content: no line box of its own.
105
    BlockSibling,
106
}
107

            
108
impl Finding {
109
    /// Orders findings on the same node the way the checks are written
110
    /// (state first, placement second) — the scan visits a text node and its
111
    /// parent in different iterations, so the sort needs the tie-break.
112
77034
    const fn rank(self) -> u8 {
113
77034
        match self {
114
341
            Self::Inert(_) => 0,
115
            Self::NoParent => 1,
116
15
            Self::TextParent => 2,
117
33092
            Self::FlexItem { .. } => 3,
118
43586
            Self::BlockSibling => 4,
119
        }
120
77034
    }
121
}
122

            
123
825535
const fn is_text(node_type: &NodeType) -> bool {
124
825535
    matches!(node_type, NodeType::Text(_))
125
825535
}
126

            
127
112143
fn has_ids_or_classes(data: &azul_core::dom::NodeData) -> bool {
128
112143
    data.attributes()
129
112143
        .as_ref()
130
112143
        .iter()
131
112143
        .any(|a| matches!(a, AttributeType::Id(_) | AttributeType::Class(_)))
132
112143
}
133

            
134
/// Does the node carry a callback that can only be reached THROUGH ITS BOX?
135
///
136
/// Pointer events find their target by hit-testing a rect, and focus events
137
/// need a node that can hold focus - a text node has neither, so a `Hover` or
138
/// `Focus` listener on one can never fire. `Window` listeners fire on every
139
/// node for a window-level event, and `Component` (lifecycle) listeners are
140
/// delivered by NODE IDENTITY from the reconcile diff - `AfterMount` on a text
141
/// node fires like on any other node (`dll/tests/headless_lifecycle` relies on
142
/// it). Calling those inert would be a lie, and the lie has a cost: it once
143
/// sent the diagnosis of a dead lifecycle pipeline chasing the test's DOM.
144
112143
fn has_box_dependent_callback(data: &azul_core::dom::NodeData) -> bool {
145
112143
    data.get_callbacks()
146
112143
        .as_ref()
147
112143
        .iter()
148
112143
        .any(|cb| matches!(cb.event, EventFilter::Hover(_) | EventFilter::Focus(_)))
149
112143
}
150

            
151
98110
fn display_of(styled_dom: &StyledDom, node_id: NodeId) -> LayoutDisplay {
152
98110
    match get_display_property(styled_dom, Some(node_id)) {
153
98110
        MultiValue::Exact(d) => d,
154
        _ => LayoutDisplay::Block,
155
    }
156
98110
}
157

            
158
97373
const fn is_flex_or_grid(display: LayoutDisplay) -> bool {
159
85648
    matches!(
160
97373
        display,
161
        LayoutDisplay::Flex
162
            | LayoutDisplay::InlineFlex
163
            | LayoutDisplay::Grid
164
            | LayoutDisplay::InlineGrid
165
    )
166
97373
}
167

            
168
737
const fn is_block_level(display: LayoutDisplay) -> bool {
169
727
    !matches!(
170
737
        display,
171
        LayoutDisplay::Inline
172
            | LayoutDisplay::InlineBlock
173
            | LayoutDisplay::InlineFlex
174
            | LayoutDisplay::InlineGrid
175
            | LayoutDisplay::InlineTable
176
            | LayoutDisplay::None
177
    )
178
737
}
179

            
180
/// Walk `styled_dom` and tag every text node used in a shape azul cannot
181
/// honor. Allocation-free while nothing is wrong.
182
8047
fn collect_findings(styled_dom: &StyledDom) -> Vec<(usize, Finding)> {
183
8047
    let node_data = styled_dom.node_data.as_container();
184
8047
    let hierarchy = styled_dom.node_hierarchy.as_container();
185
8047
    let mut found: Vec<(usize, Finding)> = Vec::new();
186

            
187
291100
    for idx in 0..node_data.len() {
188
291100
        let node_id = NodeId::new(idx);
189
291100
        let data = &node_data[node_id];
190
291100
        let Some(h) = hierarchy.get(node_id) else {
191
            continue;
192
        };
193

            
194
291100
        if is_text(data.get_node_type()) {
195
            // W1 — state on a box-less node: every one of these is inert on
196
            // a text node, because only the wrapping block box carries a
197
            // rect. An id or a class counts: it is how a stylesheet reaches
198
            // the node, and every rule it selects computes onto a node that
199
            // never gets one.
200
112143
            let mut inert = 0u8;
201
112143
            if !data.get_style().rules.as_ref().is_empty() {
202
2
                inert |= INERT_CSS;
203
112141
            }
204
112143
            if has_ids_or_classes(data) {
205
125
                inert |= INERT_IDS_CLASSES;
206
112018
            }
207
112143
            if has_box_dependent_callback(data) {
208
1
                inert |= INERT_CALLBACKS;
209
112142
            }
210
112143
            if data.get_tab_index().is_some() {
211
1
                inert |= INERT_TAB_INDEX;
212
112142
            }
213
112143
            if data.get_dataset().is_some() {
214
                inert |= INERT_DATASET;
215
112143
            }
216
112143
            if h.first_child_id(node_id).is_some() {
217
3
                inert |= INERT_CHILDREN;
218
112140
            }
219
112143
            if inert != 0 {
220
127
                found.push((idx, Finding::Inert(inert)));
221
112016
            }
222

            
223
            // W2 — no containing block the text can live in. Browsers would
224
            // generate an anonymous block here; azul does not. The remaining
225
            // W2 shapes depend only on the PARENT, so they are decided once
226
            // in the parent's own iteration below.
227
112143
            match h.parent_id() {
228
                None => found.push((idx, Finding::NoParent)),
229
112143
                Some(parent_id) if is_text(node_data[parent_id].get_node_type()) => {
230
3
                    found.push((idx, Finding::TextParent));
231
3
                }
232
112140
                Some(_) => {}
233
            }
234
112143
            continue;
235
178957
        }
236

            
237
        // Parent-major placement checks. Answering "does this parent have a
238
        // block-level child / how many items does it have?" once per parent
239
        // keeps the pass linear; asking it per text child made a wide parent
240
        // with several text children quadratic.
241
178957
        let mut child_count = 0usize;
242
178957
        let mut has_text_child = false;
243
178957
        let mut child = h.first_child_id(node_id);
244
462006
        while let Some(cc) = child {
245
283049
            child_count += 1;
246
283049
            has_text_child |= is_text(node_data[cc].get_node_type());
247
283049
            child = hierarchy
248
283049
                .get(cc)
249
283049
                .and_then(NodeHierarchyItem::next_sibling_id);
250
283049
        }
251
178957
        if !has_text_child {
252
            // The overwhelmingly common case: no display lookup, no second
253
            // sweep, nothing allocated.
254
81584
            continue;
255
97373
        }
256

            
257
97373
        let parent_display = display_of(styled_dom, node_id);
258
97373
        let finding = if is_flex_or_grid(parent_display) {
259
            // A text leaf as the SOLE child of a flex/grid box is the
260
            // sanctioned wrapper pattern (the parent is the box that carries
261
            // the styling — badge, the converted labels). The hazard is text
262
            // as ONE OF SEVERAL items: it competes in item layout with no box
263
            // of its own.
264
11725
            if child_count <= 1 {
265
100
                continue;
266
11625
            }
267
11625
            Finding::FlexItem {
268
11625
                display: parent_display,
269
11625
                child_count,
270
11625
            }
271
        } else {
272
            // Mixed inline + block content under one parent: the text has no
273
            // dedicated line box of its own next to block siblings.
274
85648
            let mut has_block_child = false;
275
85648
            let mut sibling = h.first_child_id(node_id);
276
171979
            while let Some(sib) = sibling {
277
87058
                if !is_text(node_data[sib].get_node_type())
278
737
                    && is_block_level(display_of(styled_dom, sib))
279
                {
280
727
                    has_block_child = true;
281
727
                    break;
282
86331
                }
283
86331
                sibling = hierarchy
284
86331
                    .get(sib)
285
86331
                    .and_then(NodeHierarchyItem::next_sibling_id);
286
            }
287
85648
            if !has_block_child {
288
84921
                continue;
289
727
            }
290
727
            Finding::BlockSibling
291
        };
292

            
293
12352
        let mut child = h.first_child_id(node_id);
294
64537
        while let Some(cc) = child {
295
52185
            if is_text(node_data[cc].get_node_type()) {
296
26459
                found.push((cc.index(), finding));
297
26460
            }
298
52185
            child = hierarchy
299
52185
                .get(cc)
300
52185
                .and_then(NodeHierarchyItem::next_sibling_id);
301
        }
302
    }
303

            
304
    // Node order, so a finding reads in the order the DOM was written.
305
50557
    found.sort_by_key(|(idx, finding)| (*idx, finding.rank()));
306
8047
    found
307
8047
}
308

            
309
/// Walk `styled_dom` and return one message per text node that is used in a
310
/// shape azul cannot honor. Pure — the caller decides how to report.
311
#[must_use]
312
57
pub fn collect_text_placement_warnings(styled_dom: &StyledDom) -> Vec<String> {
313
57
    let found = collect_findings(styled_dom);
314
57
    if found.is_empty() {
315
50
        return Vec::new();
316
7
    }
317
7
    let node_data = styled_dom.node_data.as_container();
318
7
    found
319
7
        .into_iter()
320
9
        .map(|(idx, finding)| render(&node_data[NodeId::new(idx)], idx, finding))
321
7
        .collect()
322
57
}
323

            
324
/// Build the developer-facing text. Only called for a finding that is about
325
/// to be printed — the snippet alone costs two allocations.
326
193
fn render(data: &azul_core::dom::NodeData, idx: usize, finding: Finding) -> String {
327
193
    let snippet = match data.get_node_type() {
328
193
        NodeType::Text(t) => snippet_of(t.as_str()),
329
        _ => String::new(),
330
    };
331
193
    match finding {
332
36
        Finding::Inert(flags) => {
333
36
            let mut inert = Vec::new();
334
36
            if flags & INERT_CSS != 0 {
335
1
                inert.push("css properties");
336
35
            }
337
36
            if flags & INERT_IDS_CLASSES != 0 {
338
34
                inert.push("ids/classes");
339
35
            }
340
36
            if flags & INERT_CALLBACKS != 0 {
341
1
                inert.push("pointer/focus callbacks");
342
35
            }
343
36
            if flags & INERT_TAB_INDEX != 0 {
344
1
                inert.push("a tab_index");
345
35
            }
346
36
            if flags & INERT_DATASET != 0 {
347
                inert.push("a dataset");
348
36
            }
349
36
            if flags & INERT_CHILDREN != 0 {
350
2
                inert.push("element children");
351
35
            }
352
36
            format!(
353
36
                "text node {idx} ({snippet}) carries {} — INERT: a text node has no box. Move \
354
36
                 them onto a block wrapper (create_p_with_text / create_div_with_text) instead of \
355
36
                 the raw text node.",
356
36
                inert.join(" + "),
357
            )
358
        }
359
        Finding::NoParent => format!(
360
            "text node {idx} ({snippet}) has no parent — a raw text run needs a block-level \
361
             container (p / div / ...) to own its box.",
362
        ),
363
1
        Finding::TextParent => format!(
364
1
            "text node {idx} ({snippet}) is the child of another text node — wrap both in a \
365
1
             block-level container (p / div / ...).",
366
        ),
367
        Finding::FlexItem {
368
73
            display,
369
73
            child_count,
370
73
        } => format!(
371
73
            "text node {idx} ({snippet}) is one of {child_count} items in a {display:?} container \
372
73
             — a raw text run competes in flex/grid layout with no box of its own (browsers \
373
73
             auto-wrap it in an anonymous block; azul does not). Wrap it: create_p_with_text / \
374
73
             create_div_with_text.",
375
        ),
376
83
        Finding::BlockSibling => format!(
377
83
            "text node {idx} ({snippet}) sits NEXT TO block-level siblings — browsers would wrap \
378
83
             it in an anonymous block, azul does not, so it has no line box of its own. Wrap it: \
379
83
             create_p_with_text / create_div_with_text.",
380
        ),
381
    }
382
193
}
383

            
384
/// Identify the PROBLEM, not the node.
385
///
386
/// Node indices shift on every structural edit — i.e. on every keystroke in
387
/// a live document — so an index-derived key re-hashes each frame: the same
388
/// finding re-prints forever AND the dedup set grows without bound. The kind
389
/// of finding plus the styling identity of the text node and its parent is
390
/// stable across edits, and it is what the developer actually fixes: one
391
/// construction site.
392
26580
fn dedup_key(styled_dom: &StyledDom, node_id: NodeId, finding: Finding) -> u64 {
393
26580
    let node_data = styled_dom.node_data.as_container();
394
26580
    let hierarchy = styled_dom.node_hierarchy.as_container();
395
26580
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
396

            
397
26580
    finding.rank().hash(&mut hasher);
398
26580
    match finding {
399
124
        Finding::Inert(flags) => flags.hash(&mut hasher),
400
        // NOT the child_count: adding an item to the container is not a new
401
        // bug.
402
11831
        Finding::FlexItem { display, .. } => display.hash(&mut hasher),
403
14625
        _ => {}
404
    }
405

            
406
26580
    hash_identity(&node_data[node_id], &mut hasher);
407
26580
    match hierarchy
408
26580
        .get(node_id)
409
26580
        .and_then(NodeHierarchyItem::parent_id)
410
    {
411
        None => 0u8.hash(&mut hasher),
412
26580
        Some(parent_id) => {
413
26580
            1u8.hash(&mut hasher);
414
26580
            hash_identity(&node_data[parent_id], &mut hasher);
415
26580
        }
416
    }
417
26580
    hasher.finish()
418
26580
}
419

            
420
/// The part of a node that survives a DOM rebuild: what it is and how it is
421
/// selected. Deliberately not its text, which may be per-frame data.
422
53160
fn hash_identity(data: &azul_core::dom::NodeData, hasher: &mut impl Hasher) {
423
53160
    discriminant(data.get_node_type()).hash(hasher);
424
53160
    for attr in data.attributes().as_ref() {
425
15198
        match attr {
426
548
            AttributeType::Id(s) => {
427
548
                0u8.hash(hasher);
428
548
                s.as_str().hash(hasher);
429
548
            }
430
14650
            AttributeType::Class(s) => {
431
14650
                1u8.hash(hasher);
432
14650
                s.as_str().hash(hasher);
433
14650
            }
434
            _ => {}
435
        }
436
    }
437
53160
}
438

            
439
/// Report every finding from [`collect_text_placement_warnings`] to stderr,
440
/// once per unique finding per process. Call after layout.
441
7990
pub fn warn_text_without_block_container(styled_dom: &StyledDom) {
442
7990
    if is_suppressed() {
443
        return;
444
7990
    }
445
7990
    let found = collect_findings(styled_dom);
446
7990
    if found.is_empty() {
447
5870
        return;
448
2120
    }
449
2120
    let Ok(mut emitted) = EMITTED.lock() else {
450
        return;
451
    };
452
2120
    if emitted.capped {
453
        return;
454
2120
    }
455
2120
    let node_data = styled_dom.node_data.as_container();
456
28700
    for (idx, finding) in found {
457
26580
        let node_id = NodeId::new(idx);
458
26580
        if !emitted.keys.insert(dedup_key(styled_dom, node_id, finding)) {
459
26396
            continue;
460
184
        }
461
184
        if emitted.keys.len() > MAX_DISTINCT_WARNINGS {
462
            emitted.capped = true;
463
            eprintln!(
464
                "[azul][text-without-block] {MAX_DISTINCT_WARNINGS} distinct findings reported — \
465
                 further warnings suppressed (suppress the whole lint with \
466
                 AZ_SUPPRESS={SUPPRESS_TAG})"
467
            );
468
            return;
469
184
        }
470
184
        eprintln!(
471
184
            "[azul][text-without-block] WARNING: {} (suppress with AZ_SUPPRESS={SUPPRESS_TAG})",
472
184
            render(&node_data[node_id], idx, finding),
473
        );
474
    }
475
7990
}
476

            
477
193
fn snippet_of(text: &str) -> String {
478
193
    let mut s: String = text.chars().take(24).collect();
479
193
    if text.chars().count() > 24 {
480
34
        s.push_str("...");
481
159
    }
482
193
    format!("{s:?}")
483
193
}
484

            
485
#[cfg(test)]
486
mod autotest_generated {
487
    use azul_core::{
488
        dom::{Dom, IdOrClass, IdOrClassVec, TabIndex},
489
        events::{ComponentEventFilter, EventFilter, HoverEventFilter},
490
        refany::RefAny,
491
        styled_dom::StyledDom,
492
    };
493
    use azul_css::css::Css;
494

            
495
    use super::collect_text_placement_warnings;
496

            
497
    fn styled(mut dom: Dom, css: &str) -> StyledDom {
498
        let css = if css.is_empty() {
499
            Css::empty()
500
        } else {
501
            Css::from_string(css.into())
502
        };
503
        StyledDom::create(&mut dom, css)
504
    }
505

            
506
    fn raw_text(s: &str) -> Dom {
507
        Dom::create_text_do_not_use_without_block_level_wrapper(s)
508
    }
509

            
510
    #[test]
511
    fn a_correctly_wrapped_text_produces_no_warning() {
512
        let sd = styled(
513
            Dom::create_body().with_child(Dom::create_p_with_text("hello")),
514
            "",
515
        );
516
        assert_eq!(collect_text_placement_warnings(&sd), Vec::<String>::new());
517
    }
518

            
519
    #[test]
520
    fn text_inside_an_inline_span_inside_a_block_is_fine() {
521
        let sd = styled(
522
            Dom::create_body()
523
                .with_child(Dom::create_p().with_child(Dom::create_span_with_text("hi"))),
524
            "",
525
        );
526
        assert_eq!(collect_text_placement_warnings(&sd), Vec::<String>::new());
527
    }
528

            
529
    #[test]
530
    fn state_on_a_text_node_is_reported_as_inert() {
531
        let text = raw_text("styled").with_tab_index(TabIndex::Auto);
532
        let sd = styled(
533
            Dom::create_body().with_child(Dom::create_p().with_child(text)),
534
            "",
535
        );
536
        let w = collect_text_placement_warnings(&sd);
537
        assert_eq!(w.len(), 1, "{w:?}");
538
        assert!(w[0].contains("INERT"), "{w:?}");
539
        assert!(w[0].contains("tab_index"), "{w:?}");
540
    }
541

            
542
    #[test]
543
    fn a_pointer_callback_on_a_text_node_is_reported_as_inert() {
544
        let text = raw_text("clickable").with_callback(
545
            EventFilter::Hover(HoverEventFilter::MouseUp),
546
            RefAny::new(()),
547
            0usize,
548
        );
549
        let sd = styled(
550
            Dom::create_body().with_child(Dom::create_p().with_child(text)),
551
            "",
552
        );
553
        let w = collect_text_placement_warnings(&sd);
554
        assert_eq!(w.len(), 1, "{w:?}");
555
        assert!(w[0].contains("pointer/focus callbacks"), "{w:?}");
556
    }
557

            
558
    #[test]
559
    fn a_lifecycle_callback_on_a_text_node_is_not_inert() {
560
        // Delivered by node identity from the reconcile diff, not by hit-test:
561
        // it fires, so the lint must not call it dead.
562
        let text = raw_text("mounted").with_callback(
563
            EventFilter::Component(ComponentEventFilter::AfterMount),
564
            RefAny::new(()),
565
            0usize,
566
        );
567
        let sd = styled(
568
            Dom::create_body().with_child(Dom::create_p().with_child(text)),
569
            "",
570
        );
571
        let w = collect_text_placement_warnings(&sd);
572
        assert!(w.is_empty(), "{w:?}");
573
    }
574

            
575
    #[test]
576
    fn ids_and_classes_on_a_text_node_are_reported_as_inert() {
577
        // The shipped menu_renderer defect: the checkmark's three classes
578
        // ended up on the text node instead of the icon <div> that boxes it.
579
        // The text is that div's only child — the shape every placement check
580
        // calls sanctioned — so the classes are the only thing left to report.
581
        let icon = raw_text("✓").with_ids_and_classes(IdOrClassVec::from_vec(vec![
582
            IdOrClass::Class("menu-item-icon".into()),
583
            IdOrClass::Class("menu-item-checkbox".into()),
584
            IdOrClass::Class("menu-item-checkbox-checked".into()),
585
        ]));
586
        let sd = styled(
587
            Dom::create_body().with_child(Dom::create_div().with_child(icon)),
588
            "",
589
        );
590
        let w = collect_text_placement_warnings(&sd);
591
        assert_eq!(w.len(), 1, "{w:?}");
592
        assert!(w[0].contains("INERT"), "{w:?}");
593
        assert!(w[0].contains("ids/classes"), "{w:?}");
594
    }
595

            
596
    #[test]
597
    fn a_sole_text_leaf_in_a_flex_wrapper_is_the_sanctioned_pattern() {
598
        // badge / the converted labels: the flex box IS the wrapper.
599
        let sd = styled(
600
            Dom::create_body().with_child(Dom::create_div().with_child(raw_text("flexed"))),
601
            "div { display: flex; }",
602
        );
603
        assert_eq!(collect_text_placement_warnings(&sd), Vec::<String>::new());
604
    }
605

            
606
    #[test]
607
    fn text_competing_with_other_flex_items_is_reported() {
608
        // The tree_view/radio_group shape: a raw label beside element items.
609
        let sd = styled(
610
            Dom::create_body().with_child(
611
                Dom::create_div()
612
                    .with_child(Dom::create_div())
613
                    .with_child(raw_text("flexed")),
614
            ),
615
            "body > div { display: flex; }",
616
        );
617
        let w = collect_text_placement_warnings(&sd);
618
        assert_eq!(w.len(), 1, "{w:?}");
619
        assert!(w[0].contains("competes in flex/grid"), "{w:?}");
620
    }
621

            
622
    #[test]
623
    fn text_next_to_a_block_sibling_is_reported() {
624
        // The audited frame.rs shape: a title wedged between two divs.
625
        let sd = styled(
626
            Dom::create_body().with_child(
627
                Dom::create_div()
628
                    .with_child(Dom::create_div())
629
                    .with_child(raw_text("title"))
630
                    .with_child(Dom::create_div()),
631
            ),
632
            "",
633
        );
634
        let w = collect_text_placement_warnings(&sd);
635
        assert_eq!(w.len(), 1, "{w:?}");
636
        assert!(w[0].contains("block-level siblings"), "{w:?}");
637
    }
638

            
639
    #[test]
640
    fn several_text_children_of_one_parent_are_all_reported() {
641
        // The per-parent memo must not swallow the sibling text runs it was
642
        // computed for.
643
        let sd = styled(
644
            Dom::create_body().with_child(
645
                Dom::create_div()
646
                    .with_child(raw_text("a"))
647
                    .with_child(Dom::create_div())
648
                    .with_child(raw_text("b")),
649
            ),
650
            "",
651
        );
652
        let w = collect_text_placement_warnings(&sd);
653
        assert_eq!(w.len(), 2, "{w:?}");
654
        assert!(w[0].contains("\"a\""), "{w:?}");
655
        assert!(w[1].contains("\"b\""), "{w:?}");
656
    }
657

            
658
    #[test]
659
    fn findings_are_reported_in_node_order() {
660
        // The two text runs are found via DIFFERENT parents (one nested, one
661
        // directly under body), so the scan reaches them out of order and the
662
        // sort has to put them back.
663
        let sd = styled(
664
            Dom::create_body()
665
                .with_child(
666
                    Dom::create_div()
667
                        .with_child(Dom::create_div())
668
                        .with_child(raw_text("deep")),
669
                )
670
                .with_child(raw_text("shallow"))
671
                .with_child(Dom::create_div()),
672
            "",
673
        );
674
        let w = collect_text_placement_warnings(&sd);
675
        assert_eq!(w.len(), 2, "{w:?}");
676
        let indices: Vec<usize> = w
677
            .iter()
678
            .map(|m| {
679
                m.split_whitespace()
680
                    .nth(2)
681
                    .and_then(|n| n.parse().ok())
682
                    .unwrap_or_else(|| panic!("no node index in {m:?}"))
683
            })
684
            .collect();
685
        assert!(indices[0] < indices[1], "{indices:?} / {w:?}");
686
    }
687

            
688
    #[test]
689
    fn every_widget_dom_is_warning_free() {
690
        // The runtime twin of the widgets' label-convention test: none of the
691
        // shipped widgets may trip the developer warning.
692
        for (name, dom) in crate::widgets::all_widget_doms_for_lint() {
693
            let sd = styled(Dom::create_body().with_child(dom), "");
694
            let w = collect_text_placement_warnings(&sd);
695
            assert_eq!(
696
                w,
697
                Vec::<String>::new(),
698
                "widget {name} trips the text lint: {w:?}"
699
            );
700
        }
701
    }
702
}
703

            
704
// ============================================================================
705
// Suppression, once, for every lint
706
// ============================================================================
707

            
708
/// Is `tag` suppressed via `AZ_SUPPRESS`?
709
///
710
/// Comma-separated; the common misspelling `AZ_SUPRESS` is accepted too.
711
/// `AZ_SUPPRESS=all` turns every engine lint off in one move — a shipped app
712
/// that has read its warnings and does not want them in a customer's console
713
/// should not have to enumerate them, and a new lint must not suddenly start
714
/// talking in that app's logs.
715
///
716
/// Read once per tag and cached: these run inside the layout pass.
717
24627
pub fn lint_suppressed(tag: &str) -> bool {
718
    use std::{
719
        collections::BTreeMap,
720
        sync::{Mutex, OnceLock},
721
    };
722
    static CACHE: OnceLock<Mutex<BTreeMap<String, bool>>> = OnceLock::new();
723
24627
    let cache = CACHE.get_or_init(|| Mutex::new(BTreeMap::new()));
724
24627
    if let Ok(c) = cache.lock() {
725
24627
        if let Some(hit) = c.get(tag) {
726
24520
            return *hit;
727
107
        }
728
    }
729
107
    let v = std::env::var("AZ_SUPPRESS")
730
107
        .or_else(|_| std::env::var("AZ_SUPRESS"))
731
107
        .unwrap_or_default();
732
107
    let hit = v.split(',').any(|t| {
733
107
        let t = t.trim();
734
107
        t.eq_ignore_ascii_case(tag) || t.eq_ignore_ascii_case("all")
735
107
    });
736
107
    if let Ok(mut c) = cache.lock() {
737
107
        c.insert(tag.to_string(), hit);
738
107
    }
739
107
    hit
740
24627
}
741

            
742
// ============================================================================
743
// Lint: a <div> that holds nothing but text
744
// ============================================================================
745

            
746
/// Suppression tag for [`warn_div_used_as_text_container`].
747
pub const DIV_TEXT_SUPPRESS_TAG: &str = "div_as_text";
748

            
749
7993
fn div_text_suppressed() -> bool {
750
7993
    lint_suppressed(DIV_TEXT_SUPPRESS_TAG)
751
7993
}
752

            
753
/// A `<div>` whose only child is a text node is almost always the wrong
754
/// element.
755
///
756
/// `div` is a generic CONTAINER — it says "a box, meaning unspecified". Text
757
/// that is a label, a caption, or a control's text belongs in `<span>`
758
/// (inline), and text that is prose belongs in `<p>`. Reaching for `div` is
759
/// usually a sign that someone wanted "a box around this text" and took the
760
/// first constructor that provided one.
761
///
762
/// It matters beyond tidiness. Assistive technology reads the element to decide
763
/// what a thing IS: a `div` conveys nothing, while `p` announces a paragraph
764
/// and `span` stays inline inside its label. It also affects layout — a `div`
765
/// is block-level, so a label inside a button becomes a block box where an
766
/// inline one was meant.
767
///
768
/// Not an error: a `div` with text is legal and occasionally right (a sizing
769
/// box that happens to contain a word). Hence a warning, and a suppression tag.
770
7993
pub fn warn_div_used_as_text_container(styled_dom: &StyledDom) {
771
7993
    if div_text_suppressed() {
772
        return;
773
7993
    }
774

            
775
7993
    let nodes = styled_dom.node_data.as_container();
776
7993
    let hierarchy = styled_dom.node_hierarchy.as_container();
777

            
778
7993
    let mut reported = 0usize;
779
282462
    for (node_id, node) in nodes
780
7993
        .linear_iter()
781
282462
        .filter_map(|id| nodes.get(id).map(|n| (id, n)))
782
    {
783
282462
        if !matches!(node.get_node_type(), NodeType::Div) {
784
209776
            continue;
785
72686
        }
786
        // Exactly one child, and that child is a text node.
787
72686
        let Some(item) = hierarchy.get(node_id) else {
788
            continue;
789
        };
790
72686
        let Some(first) = item.first_child_id(node_id) else {
791
5315
            continue;
792
        };
793
67371
        let only_child = hierarchy
794
67371
            .get(first)
795
67371
            .is_some_and(|c| c.next_sibling_id().is_none());
796
67371
        if !only_child {
797
34102
            continue;
798
33269
        }
799
33269
        let Some(child) = nodes.get(first) else {
800
            continue;
801
        };
802
33269
        let NodeType::Text(text) = child.get_node_type() else {
803
27925
            continue;
804
        };
805

            
806
5344
        reported += 1;
807
5344
        if reported > 8 {
808
170
            break; // one screenful is enough to act on
809
5174
        }
810
5174
        let preview: String = text.as_str().chars().take(24).collect();
811
5174
        azul_core::diagnostics::emit(format!(
812
5174
            "[azul][div-as-text] node {} is a <div> whose only child is the text {preview:?}. A \
813
5174
             div is a generic container and says nothing about what the text IS. Use \
814
5174
             create_span_with_text for a label or a control's text (inline, stays inside its line \
815
5174
             box) or create_p_with_text for prose (block, announced as a paragraph). Assistive \
816
5174
             technology reads the element to decide what a thing is, and a div tells it nothing. \
817
5174
             (suppress with AZ_SUPPRESS={DIV_TEXT_SUPPRESS_TAG})",
818
5174
            node_id.index()
819
        ));
820
    }
821
7993
}
822

            
823
// ============================================================================
824
// Lint: an interactive node with no accessible name
825
// ============================================================================
826

            
827
/// Suppression tag for [`warn_interactive_without_accessibility`].
828
pub const A11Y_SUPPRESS_TAG: &str = "a11y";
829

            
830
7992
fn a11y_suppressed() -> bool {
831
7992
    lint_suppressed(A11Y_SUPPRESS_TAG)
832
7992
}
833

            
834
/// A node the user can CLICK, with nothing that names it to assistive
835
/// technology.
836
///
837
/// A screen reader announces a control by its accessible name. Without one it
838
/// reads "button" — or nothing at all — and the control is unusable without
839
/// sight. Azul builds its accessibility tree from `NodeData::accessibility`,
840
/// so a node with a click callback and no `AccessibilityInfo` is invisible to
841
/// that tree even though it is plainly visible on screen.
842
///
843
/// The fix is one call:
844
///
845
/// ```ignore
846
/// dom.with_accessibility_info(AccessibilityInfo {
847
///     accessibility_name: Some("Mute microphone".into()).into(),
848
///     ..Default::default()
849
/// })
850
/// ```
851
///
852
/// A node whose text child already spells out its label is NOT reported: azul
853
/// derives a name from the text in that case, so the control does announce
854
/// itself. What this catches is the icon-only button — the one whose label is a
855
/// glyph, where a sighted user infers "mute" from a picture and a screen reader
856
/// gets a private-use codepoint.
857
7992
pub fn warn_interactive_without_accessibility(styled_dom: &StyledDom) {
858
7992
    if a11y_suppressed() {
859
        return;
860
7992
    }
861

            
862
7992
    let nodes = styled_dom.node_data.as_container();
863
7992
    let hierarchy = styled_dom.node_hierarchy.as_container();
864

            
865
7992
    let mut reported = 0usize;
866
290436
    for (node_id, node) in nodes
867
7992
        .linear_iter()
868
290436
        .filter_map(|id| nodes.get(id).map(|n| (id, n)))
869
    {
870
        // "Interactive" = the app attached a callback to it.
871
290436
        if node.get_callbacks().is_empty() {
872
266754
            continue;
873
23682
        }
874
23682
        if node.accessibility.is_some() {
875
2590
            continue; // already named
876
21092
        }
877

            
878
        // Does a descendant text node spell out a usable label? Azul derives a
879
        // name from it, so those controls DO announce themselves.
880
        // Walk DESCENDANTS, not just direct children. A well-built control puts
881
        // its label in a <span> — the shape this crate recommends — so the text
882
        // is a grandchild. Scanning one level deep flagged every correctly
883
        // written button, which a test caught before this shipped.
884
21092
        let mut has_readable_text = false;
885
21092
        let mut stack = vec![node_id];
886
21092
        let mut visited = 0usize;
887
63617
        while let Some(cur) = stack.pop() {
888
63616
            visited += 1;
889
63616
            if visited > 64 {
890
                break; // a label is never buried this deep; bound the walk
891
63616
            }
892
63616
            if let Some(cn) = nodes.get(cur) {
893
63616
                if let NodeType::Text(t) = cn.get_node_type() {
894
                    // A private-use glyph is an ICON, not a name: it reads as a
895
                    // meaningless codepoint.
896
21262
                    if t.as_str()
897
21262
                        .chars()
898
21262
                        .any(|ch| ch.is_alphanumeric() && !('\u{e000}'..='\u{f8ff}').contains(&ch))
899
                    {
900
21091
                        has_readable_text = true;
901
21091
                        break;
902
171
                    }
903
42354
                }
904
            }
905
42525
            if let Some(item) = hierarchy.get(cur) {
906
42525
                if let Some(first) = item.first_child_id(cur) {
907
42354
                    let mut sib = Some(first);
908
96238
                    while let Some(sid) = sib {
909
53884
                        stack.push(sid);
910
53884
                        sib = hierarchy
911
53884
                            .get(sid)
912
53884
                            .and_then(NodeHierarchyItem::next_sibling_id);
913
53884
                    }
914
171
                }
915
            }
916
        }
917
21092
        if has_readable_text {
918
21091
            continue;
919
1
        }
920

            
921
1
        reported += 1;
922
1
        if reported > 8 {
923
            break;
924
1
        }
925
1
        azul_core::diagnostics::emit(format!(
926
1
            "[azul][a11y] node {} has a callback but no accessible name, and no text child that \
927
1
             could serve as one — an icon-only control reads to a screen reader as a private-use \
928
1
             codepoint, or as nothing. Add one: .with_accessibility_info(AccessibilityInfo {{ \
929
1
             accessibility_name: Some(\"...\".into()).into(), ..Default::default() }}). (suppress \
930
1
             with AZ_SUPPRESS={A11Y_SUPPRESS_TAG})",
931
1
            node_id.index()
932
        ));
933
    }
934
7992
}
935

            
936
#[cfg(all(test, feature = "std"))]
937
mod semantic_and_a11y_lint_tests {
938
    use azul_core::dom::Dom;
939

            
940
    use super::*;
941

            
942
    // The lints share the global diagnostics ring, so they must not run
943
    // concurrently. The lock is workspace-wide and lives beside the ring:
944
    // see azul_core::diagnostics::test_lock.
945

            
946
5
    fn styled(dom: Dom) -> StyledDom {
947
5
        StyledDom::create_from_dom(dom)
948
5
    }
949

            
950
    #[test]
951
1
    fn a_div_holding_only_text_is_reported() {
952
1
        let _g = azul_core::diagnostics::test_lock().lock();
953
1
        azul_core::diagnostics::clear();
954

            
955
1
        warn_div_used_as_text_container(&styled(
956
1
            Dom::create_body().with_child(Dom::create_div_with_text("Unmute mic")),
957
1
        ));
958
1
        assert!(
959
1
            azul_core::diagnostics::any_contains("div-as-text"),
960
            "a <div> whose only child is text must be reported: {:?}",
961
            azul_core::diagnostics::recorded()
962
        );
963

            
964
        // ...and the alternatives must NOT be.
965
1
        azul_core::diagnostics::clear();
966
1
        warn_div_used_as_text_container(&styled(
967
1
            Dom::create_body()
968
1
                .with_child(Dom::create_span_with_text("Unmute mic"))
969
1
                .with_child(Dom::create_p_with_text("A paragraph of prose.")),
970
1
        ));
971
1
        assert!(
972
1
            !azul_core::diagnostics::any_contains("div-as-text"),
973
            "span and p are the RECOMMENDED forms and must not be flagged: {:?}",
974
            azul_core::diagnostics::recorded()
975
        );
976
1
        azul_core::diagnostics::clear();
977
1
    }
978

            
979
    /// A div that contains other elements is a container doing its job.
980
    #[test]
981
1
    fn a_div_with_element_children_is_not_reported() {
982
1
        let _g = azul_core::diagnostics::test_lock().lock();
983
1
        azul_core::diagnostics::clear();
984
1
        warn_div_used_as_text_container(&styled(
985
1
            Dom::create_body().with_child(
986
1
                Dom::create_div()
987
1
                    .with_child(Dom::create_span_with_text("a"))
988
1
                    .with_child(Dom::create_span_with_text("b")),
989
1
            ),
990
1
        ));
991
1
        assert!(!azul_core::diagnostics::any_contains("div-as-text"));
992
1
        azul_core::diagnostics::clear();
993
1
    }
994

            
995
    /// An ICON-only control — its label is a private-use glyph — announces
996
    /// nothing to a screen reader and must be reported.
997
    #[test]
998
1
    fn an_icon_only_control_without_a_name_is_reported() {
999
1
        let _g = azul_core::diagnostics::test_lock().lock();
1
        azul_core::diagnostics::clear();
1
        let icon_button = Dom::create_div()
1
            .with_child(Dom::create_span_with_text("\u{e161}")) // a Material icon
1
            .with_callback(
1
                azul_core::dom::EventFilter::Hover(
1
                    azul_core::dom::HoverEventFilter::MouseUp,
1
                ),
1
                azul_core::refany::RefAny::new(()),
1
                crate::callbacks::Callback::from_ptr(noop_cb),
            );
1
        warn_interactive_without_accessibility(&styled(Dom::create_body().with_child(icon_button)));
1
        assert!(
1
            azul_core::diagnostics::any_contains("[azul][a11y]"),
            "an icon-only control with no accessible name must be reported: {:?}",
            azul_core::diagnostics::recorded()
        );
1
        azul_core::diagnostics::clear();
1
    }
    /// A control whose text spells out its label DOES announce itself — azul
    /// derives a name from it — so reporting it would be noise.
    #[test]
1
    fn a_control_with_a_readable_label_is_not_reported() {
1
        let _g = azul_core::diagnostics::test_lock().lock();
1
        azul_core::diagnostics::clear();
1
        let text_button = Dom::create_div()
1
            .with_child(Dom::create_span_with_text("Unmute mic"))
1
            .with_callback(
1
                azul_core::dom::EventFilter::Hover(azul_core::dom::HoverEventFilter::MouseUp),
1
                azul_core::refany::RefAny::new(()),
1
                crate::callbacks::Callback::from_ptr(noop_cb),
            );
1
        warn_interactive_without_accessibility(&styled(Dom::create_body().with_child(text_button)));
1
        assert!(
1
            !azul_core::diagnostics::any_contains("[azul][a11y]"),
            "a control with a readable text label already announces itself: {:?}",
            azul_core::diagnostics::recorded()
        );
1
        azul_core::diagnostics::clear();
1
    }
    extern "C" fn noop_cb(
        _: azul_core::refany::RefAny,
        _: crate::callbacks::CallbackInfo,
    ) -> azul_core::callbacks::Update {
        azul_core::callbacks::Update::DoNothing
    }
}
/// The azul widget a node came from, if it says so.
///
/// Widgets tag themselves `__azul-native-<name>`, which lets the FRAMEWORK lint
/// give WIDGET-specific advice — naming the type and the exact builder call —
/// without the widget having to warn at build time.
///
/// That distinction matters: a widget cannot warn about a missing name itself,
/// because the name arrives AFTER it is built. `Slider::new(..).dom()` runs
/// first, `.with_accessibility_name("Volume")` second. A build-time warning
/// would fire on every correctly-named slider in existence. The lint runs on
/// the finished DOM, so it sees the answer.
600
fn azul_widget_kind(node: &azul_core::dom::NodeData) -> Option<String> {
600
    node.get_ids_and_classes().iter().find_map(|ic| {
600
        let s = match ic {
600
            azul_core::dom::IdOrClass::Class(c) => c.as_str(),
            azul_core::dom::IdOrClass::Id(_) => return None,
        };
600
        let rest = s.strip_prefix("__azul-native-")?;
        // "__azul-native-slider-thumb" -> "slider": the first segment is the
        // widget; the rest names a part inside it.
600
        let name = rest.split('-').next()?;
600
        if name.is_empty() {
            return None;
600
        }
600
        let mut c = name.chars();
600
        Some(c.next()?.to_uppercase().collect::<String>() + c.as_str())
600
    })
600
}
/// Does a readable text label exist at or beneath `node_id`?
///
/// "Readable" excludes private-use codepoints: an icon glyph is a picture, and
/// reads to a screen reader as a meaningless character rather than a name.
///
/// Shared by the a11y lints because both need the same question answered, and
/// answering it differently in two places is how a lint acquires false
/// positives — the shape lint reported every labelled checkbox as "anonymous"
/// until it used this.
1051
fn has_readable_text_label(styled_dom: &StyledDom, node_id: NodeId) -> bool {
1051
    let nodes = styled_dom.node_data.as_container();
1051
    let hierarchy = styled_dom.node_hierarchy.as_container();
1051
    let mut stack = vec![node_id];
1051
    let mut visited = 0usize;
3223
    while let Some(cur) = stack.pop() {
2623
        visited += 1;
2623
        if visited > 64 {
            break; // a label is never buried this deep; bound the walk
2623
        }
2623
        if let Some(cn) = nodes.get(cur) {
2623
            if let NodeType::Text(t) = cn.get_node_type() {
481
                if t.as_str()
481
                    .chars()
481
                    .any(|ch| ch.is_alphanumeric() && !('\u{e000}'..='\u{f8ff}').contains(&ch))
                {
451
                    return true;
30
                }
2142
            }
        }
2172
        if let Some(item) = hierarchy.get(cur) {
2172
            if let Some(first) = item.first_child_id(cur) {
1572
                let mut sib = Some(first);
3385
                while let Some(sid) = sib {
1813
                    stack.push(sid);
1813
                    sib = hierarchy
1813
                        .get(sid)
1813
                        .and_then(NodeHierarchyItem::next_sibling_id);
1813
                }
600
            }
        }
    }
600
    false
1051
}
// ============================================================================
// Lint: what this node's SHAPE says it should declare
// ============================================================================
/// Suppression tag for [`warn_a11y_shape`].
pub const A11Y_SHAPE_SUPPRESS_TAG: &str = "a11y_shape";
/// Tell a developer, from the shape of the DOM, which accessibility attributes
/// this particular node is missing — and why each one matters.
///
/// ## The distinction this exists to teach
///
/// Azul builds its accessibility tree from `NodeData::accessibility`. A node
/// with `None` there is **not in that tree**: it is on screen and absent from
/// the interface a screen-reader user actually has. This is not "less
/// accessible", it is *invisible*, and it is the default for every node you
/// build. There is no partial credit and no automatic fallback beyond a name
/// derived from text.
///
/// `AccessibilityInfo` carries far more than a name — a role out of 118, a
/// value, a description, states, `labelled_by` / `described_by` relations, a
/// default action, an accelerator, and a live-region flag. Nobody discovers
/// that by reading `core/src/a11y.rs`, so this lint reads the node's shape and
/// names the specific field it is missing:
///
/// | shape observed                      | what to declare        |
/// |-------------------------------------|------------------------|
/// | interactive, no accessibility at all | `accessibility_name`, plus a `role` |
/// | declared, but role is `Unknown`       | `role` — "what IS this" |
/// | `Slider` / `ProgressBar` / `ScrollBar` | `accessibility_value` |
/// | `CheckButton` / `RadioButton`         | a checked state       |
/// | `PushButton` with no action named     | `default_action`      |
/// | an image with no name                | `accessibility_name` or `description` |
/// | keyboard-focusable, no role          | `role`                 |
///
/// Suppress with `AZ_SUPPRESS=a11y_shape`, or `AZ_SUPPRESS=all` for every lint.
7990
pub fn warn_a11y_shape(styled_dom: &StyledDom) {
7990
    if lint_suppressed(A11Y_SHAPE_SUPPRESS_TAG) {
        return;
7990
    }
    use azul_core::a11y::{AccessibilityRole, AccessibilityState};
7990
    let nodes = styled_dom.node_data.as_container();
7990
    let hierarchy = styled_dom.node_hierarchy.as_container();
7990
    let mut reported = 0usize;
290418
    for (node_id, node) in nodes
7990
        .linear_iter()
290418
        .filter_map(|id| nodes.get(id).map(|n| (id, n)))
    {
290418
        if reported >= 8 {
2
            break; // one screenful is enough to act on
290416
        }
290416
        let idx = node_id.index();
290416
        let interactive = !node.get_callbacks().is_empty();
290416
        let focusable = node.get_tab_index().is_some();
290416
        let Some(info) = node.accessibility.as_ref() else {
            // The no-a11y case is handled by warn_interactive_without_accessibility,
            // which already reports interactive nodes. Here, add the shapes that
            // are worth naming even when they are not clickable.
272816
            if matches!(node.get_node_type(), NodeType::Image(_)) {
123
                reported += 1;
123
                azul_core::diagnostics::emit(format!(
123
                    "[azul][a11y-shape] node {idx} is an IMAGE with no accessibility info, so it \
123
                     is absent from the accessibility tree entirely — a screen reader announces \
123
                     nothing where a sighted user sees a picture. Give it \
123
                     .with_accessibility_info(AccessibilityInfo {{ accessibility_name: \
123
                     Some(\"what it shows\".into()).into(), role: AccessibilityRole::Graphic, \
123
                     ..Default::default() }}), or, when it only decorates something named \
123
                     elsewhere, mark it decorative with `role: AccessibilityRole::Nothing` and no \
123
                     name. (suppress with AZ_SUPPRESS={A11Y_SHAPE_SUPPRESS_TAG})"
123
                ));
272693
            } else if focusable {
780
                reported += 1;
780
                azul_core::diagnostics::emit(format!(
780
                    "[azul][a11y-shape] node {idx} is KEYBOARD-FOCUSABLE (it has a tab_index) but \
780
                     declares no accessibility info, so tabbing lands on something the screen \
780
                     reader cannot describe. At minimum give it a `role` and an \
780
                     `accessibility_name`. (suppress with AZ_SUPPRESS={A11Y_SHAPE_SUPPRESS_TAG})"
780
                ));
271913
            }
272816
            continue;
        };
        // It DECLARED accessibility — now check that the declaration matches the
        // shape. A half-filled AccessibilityInfo is the subtler failure: the node
        // is in the tree, so nothing looks broken, and it still announces wrongly.
17600
        let role = info.role;
17600
        let has_name = info.accessibility_name.as_ref().is_some();
17600
        let has_value = info.accessibility_value.as_ref().is_some();
17600
        if matches!(role, AccessibilityRole::Unknown) && (interactive || focusable) {
            reported += 1;
            azul_core::diagnostics::emit(format!(
                "[azul][a11y-shape] node {idx} is interactive and declares accessibility, but its \
                 `role` is Unknown — a screen reader can say its name and not what it IS. Pick \
                 from AccessibilityRole (PushButton, CheckBox, ComboBox, Slider, Link, Tab, \
                 MenuItem, …). (suppress with AZ_SUPPRESS={A11Y_SHAPE_SUPPRESS_TAG})"
            ));
            continue;
17600
        }
17600
        if matches!(
17600
            role,
            AccessibilityRole::Slider
                | AccessibilityRole::ProgressBar
                | AccessibilityRole::ScrollBar
        ) && !has_value
        {
            reported += 1;
            azul_core::diagnostics::emit(format!(
                "[azul][a11y-shape] node {idx} has role {role:?} but no `accessibility_value`. \
                 The value IS the content of these controls — without it a screen reader \
                 announces \"slider\" and never how far along it is. Set accessibility_value on \
                 every change, not once. (suppress with AZ_SUPPRESS={A11Y_SHAPE_SUPPRESS_TAG})"
            ));
            continue;
17600
        }
16910
        if matches!(
17600
            role,
            AccessibilityRole::CheckButton | AccessibilityRole::RadioButton
        ) {
690
            let states = info.states.as_ref();
690
            let declares_checked = states.iter().any(|s| {
                matches!(
690
                    s,
                    AccessibilityState::CheckedTrue
                        | AccessibilityState::CheckedFalse
                        | AccessibilityState::Selected
                )
690
            });
690
            if !declares_checked {
                reported += 1;
                azul_core::diagnostics::emit(format!(
                    "[azul][a11y-shape] node {idx} has role {role:?} but declares no \
                     CheckedTrue/CheckedFalse/Selected state, so it always announces as unchecked \
                     no matter what it renders. Push the state into AccessibilityInfo::states \
                     when the control toggles. (suppress with \
                     AZ_SUPPRESS={A11Y_SHAPE_SUPPRESS_TAG})"
                ));
                continue;
690
            }
16910
        }
        // An explicit `role: Nothing` with no name on something nobody can click
        // or tab to is the DECORATIVE mark (ARIA's role="presentation"): the
        // picture is part of a whole that is named elsewhere, like one tile of a
        // map whose container carries the name. Demanding a name here would make
        // a screen reader read out every tile.
17600
        if matches!(role, AccessibilityRole::Nothing) && !has_name && !interactive && !focusable {
            continue;
17600
        }
        // A control whose visible label is a text node DOES announce itself —
        // azul derives the name from that text. Reporting those was a false
        // positive on every correctly-built labelled checkbox and slider.
17600
        if !has_name
1051
            && info.labelled_by.as_ref().is_none()
1051
            && !has_readable_text_label(styled_dom, node_id)
        {
600
            reported += 1;
            // Name the WIDGET when the node admits which one it is. "Slider has
            // no name; add .with_accessibility_name(..)" is a fix someone can
            // apply; "node 40 is anonymous" is a puzzle they have to solve
            // first.
600
            let who = azul_widget_kind(node)
600
                .map_or_else(|| format!("node {idx}"), |w| format!("node {idx} (a {w})"));
600
            azul_core::diagnostics::emit(format!(
600
                "[azul][a11y-shape] {who} declares accessibility (role {role:?}) but has neither \
600
                 an `accessibility_name` nor a `labelled_by`. It is in the tree and anonymous. \
600
                 This control has no text of its own to derive a name from, and only the CALL \
600
                 SITE knows what it is called: add `.with_accessibility_name(\"…\")` there — it \
600
                 MERGES, so the role, value and states above survive — or point at the label you \
600
                 already render with `.with_accessibility_labelled_by(node)`, which cannot drift \
600
                 out of sync the way a copied string does. (suppress with \
600
                 AZ_SUPPRESS={A11Y_SHAPE_SUPPRESS_TAG})"
            ));
17000
        }
    }
7990
}