icedwright-semantics 0.0.1

The icedwright semantic tree: inference from recorded widget operations, stable node paths, hit testing, diffs and YAML
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! The semantic tree as YAML: one line per node with its role, quoted name, attributes in
//! brackets and a value or text after a colon. Unnamed generics are hoisted away and owned
//! subtrees print under their owner.
//!
//! ```yaml
//! - dialog "Delete item?" [modal]:
//!   - heading "Delete item?" [level=2]
//!   - text: Water the beans will be removed.
//!   - button "Delete"
//! - textbox "New item": Sow the leeks
//! ```
//!
//! States print bare when true (`[disabled]`) and with a value otherwise (`[expanded=false]`,
//! `[checked=mixed]`); derived flags print only when set. A node with both a value and
//! children carries the value as a first child `- /value: ..`.
//!
//! The output is always valid YAML: a key containing `: ` or ` #` is single-quoted, a value
//! YAML would read differently is double-quoted with YAML's escapes, and a key longer than
//! YAML's 1024-character limit for one-line keys is written as an explicit `? key` entry.
//! [`normalise`] folds those forms back into one line per entry for [`read`] and the template
//! parser.

use std::borrow::Cow;
use std::fmt::Write as _;

use icedwright_protocol::{WidgetId, WindowId};
use icedwright_types::{Point, Rect, Role, Size, StateName, StateValue};

use crate::build::{self, Draft, Mode, named_from_content};
use crate::error::Error;
use crate::path::Cursor;
use crate::tree::{Kind, NameSource, Node, NodeId, SemanticTree, StateSource, Value};

/// What [`write()`] includes.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct YamlOptions {
    /// A trailing `@ x,y wxh`, rounded to whole logical pixels.
    pub include_bounds: bool,
    /// Test ids and widget ids.
    pub include_ids: bool,
    /// Unnamed generics instead of hoisting their children.
    pub include_ignored: bool,
    /// Props written as `***`.
    pub mask_props: Vec<String>,
    /// Levels below the top-level entries; `Some(0)` writes only those.
    pub depth: Option<usize>,
    /// The most lines written; the rest are cut with `- ...`.
    pub max_lines: Option<usize>,
    /// `[ref=eN]` on every interactive node.
    pub refs: bool,
}

/// Every state name, in the order the writer and the selector printer use.
pub const STATE_NAMES: &[(StateName, &str)] = &[
    (StateName::Disabled, "disabled"),
    (StateName::Readonly, "readonly"),
    (StateName::Checked, "checked"),
    (StateName::Pressed, "pressed"),
    (StateName::Expanded, "expanded"),
    (StateName::Selected, "selected"),
    (StateName::Focused, "focused"),
    (StateName::Current, "current"),
    (StateName::Busy, "busy"),
    (StateName::Required, "required"),
    (StateName::Invalid, "invalid"),
    (StateName::Multiline, "multiline"),
    (StateName::Multiselectable, "multiselectable"),
    (StateName::Modal, "modal"),
    (StateName::Focusable, "focusable"),
    (StateName::Hidden, "hidden"),
    (StateName::Offscreen, "offscreen"),
    (StateName::Inert, "inert"),
];

const fn is_flag(state: StateName) -> bool {
    matches!(
        state,
        StateName::Modal
            | StateName::Focusable
            | StateName::Hidden
            | StateName::Offscreen
            | StateName::Inert
    )
}

struct Line {
    depth: usize,
    text: String,
    /// Whether the line starts an entry with `- `; the second line of an explicit key does
    /// not.
    bullet: bool,
}

impl Line {
    fn entry(depth: usize, text: String) -> Self {
        Self {
            depth,
            text,
            bullet: true,
        }
    }
}

/// The longest key YAML allows before `:` on one line, in characters.
const IMPLICIT_KEY_LIMIT: usize = 1024;

/// Writes the subtree at `root`. A window root writes its content without a line of its own.
#[must_use]
pub fn write(tree: &SemanticTree, root: NodeId, options: &YamlOptions) -> String {
    let mut lines = Vec::new();
    let Some(node) = tree.get(root) else {
        return String::new();
    };
    if node.role == Role::Window && node.parent.is_none() {
        for child in visible_children(tree, node, options) {
            write_node(tree, child, 0, options, &mut lines);
        }
    } else {
        write_node(tree, node, 0, options, &mut lines);
    }
    if let Some(max) = options.max_lines
        && lines.len() > max
    {
        let cut = max.saturating_sub(1);
        let depth = lines.get(cut).map_or(0, |l| l.depth);
        lines.truncate(cut);
        if lines
            .last()
            .is_some_and(|l| l.bullet && l.text.starts_with("? "))
        {
            lines.pop();
        }
        lines.push(Line::entry(depth, "...".to_owned()));
    }
    let mut out = String::new();
    for line in lines {
        let bullet = if line.bullet { "- " } else { "  " };
        let _ = writeln!(out, "{}{bullet}{}", "  ".repeat(line.depth), line.text);
    }
    out
}

/// Puts each entry back on one line: a key YAML needed quoted or explicit is folded into the
/// plain `- key: value` form the line grammar reads, and the second line of an explicit key
/// becomes blank, so line numbers still match the source. [`read`] does this first, and so
/// does the template parser in `icedwright-check`.
#[must_use]
pub fn normalise(source: &str) -> Cow<'_, str> {
    let needs = source.lines().any(|line| {
        let item = line.trim_start_matches(' ');
        item.starts_with("- '") || item.starts_with("- ? ")
    });
    if !needs {
        return Cow::Borrowed(source);
    }
    let lines: Vec<&str> = source.lines().collect();
    let mut out = String::with_capacity(source.len());
    let mut index = 0;
    while let Some(line) = lines.get(index) {
        index += 1;
        let indent = line.len() - line.trim_start_matches(' ').len();
        let Some(item) = line.get(indent..).and_then(|l| l.strip_prefix("- ")) else {
            out.push_str(line);
            out.push('\n');
            continue;
        };
        let (key, explicit) = match item.strip_prefix("? ") {
            Some(key) => (key, true),
            None => (item, false),
        };
        let mut folded = unwrap_key(key);
        let value_line = lines.get(index).filter(|next| {
            let next_indent = next.len() - next.trim_start_matches(' ').len();
            explicit && next_indent == indent + 2 && next.trim_start().starts_with(':')
        });
        if let Some(value_line) = value_line {
            folded.push_str(value_line.trim_start());
            index += 1;
        }
        out.push_str(line.get(..indent).unwrap_or_default());
        out.push_str("- ");
        out.push_str(&folded);
        out.push('\n');
        if value_line.is_some() {
            out.push('\n');
        }
    }
    Cow::Owned(out)
}

/// A double-quoted YAML scalar, using only escapes YAML and [`read`] both understand.
fn quoted(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for c in text.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '\r' => out.push_str("\\r"),
            c if needs_escape(c) => {
                let _ = write!(out, "\\u{:04x}", u32::from(c));
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

/// Characters YAML does not allow unescaped in a document, all below U+10000.
fn needs_escape(c: char) -> bool {
    c.is_control()
        || matches!(
            c,
            '\u{feff}' | '\u{2028}' | '\u{2029}' | '\u{fffe}' | '\u{ffff}'
        )
}

/// The node's key as a YAML scalar: plain when YAML reads it back unchanged, otherwise in
/// single quotes, whose only escape is a doubled quote.
fn yaml_key(key: &str) -> String {
    let plain = !key.contains(": ") && !key.contains(" #") && !key.ends_with(':');
    if plain {
        return key.to_owned();
    }
    format!("'{}'", key.replace('\'', "''"))
}

/// An entry with a single-quoted key unquoted, followed by whatever came after the key. An
/// entry whose quote never closes is left as it is, for the reader to report.
fn unwrap_key(item: &str) -> String {
    let Some(rest) = item.strip_prefix('\'') else {
        return item.to_owned();
    };
    let mut key = String::new();
    let mut chars = rest.char_indices().peekable();
    while let Some((at, c)) = chars.next() {
        if c != '\'' {
            key.push(c);
            continue;
        }
        if chars.next_if(|(_, next)| *next == '\'').is_some() {
            key.push('\'');
            continue;
        }
        key.push_str(rest.get(at + 1..).unwrap_or_default());
        return key;
    }
    item.to_owned()
}

/// The children a node prints: its own, then what it owns, with ignored generics hoisted and
/// owned nodes left for their owner.
fn visible_children<'t>(
    tree: &'t SemanticTree,
    node: &'t Node,
    options: &YamlOptions,
) -> Vec<&'t Node> {
    let mut out = Vec::new();
    for child in &node.children {
        let Some(child) = tree.get(*child) else {
            continue;
        };
        if child.relations.owner.is_some() {
            continue;
        }
        if child.ignored && !options.include_ignored {
            out.extend(visible_children(tree, child, options));
            continue;
        }
        out.push(child);
    }
    for owned in &node.relations.owns {
        if let Some(owned) = tree.get(*owned) {
            out.push(owned);
        }
    }
    out
}

fn write_node(
    tree: &SemanticTree,
    node: &Node,
    depth: usize,
    options: &YamlOptions,
    lines: &mut Vec<Line>,
) {
    let children = if options.depth.is_some_and(|max| depth >= max) {
        Vec::new()
    } else {
        visible_children(tree, node, options)
    };
    let key = yaml_key(&key(tree, node, options));
    let colon_value = colon_value(tree, node);
    let after = match (&colon_value, children.is_empty()) {
        (Some(value), true) => format!(": {}", scalar(value)),
        (None, true) => String::new(),
        (_, false) => ":".to_owned(),
    };
    if after.is_empty() || key.chars().count() <= IMPLICIT_KEY_LIMIT {
        lines.push(Line::entry(depth, key + &after));
    } else {
        lines.push(Line::entry(depth, format!("? {key}")));
        lines.push(Line {
            depth,
            text: after,
            bullet: false,
        });
    }
    if children.is_empty() {
        return;
    }
    if let Some(value) = colon_value {
        lines.push(Line::entry(
            depth + 1,
            format!("/value: {}", scalar(&value)),
        ));
    }
    for child in children {
        write_node(tree, child, depth + 1, options, lines);
    }
}

fn is_text_role(role: Role) -> bool {
    matches!(role, Role::Text | Role::Paragraph)
}

fn text_named_by_content(tree: &SemanticTree, node: &Node) -> bool {
    is_text_role(node.role)
        && (node.name_source == NameSource::Text
            || node.name.as_deref() == Some(tree.text_content(node.id)))
}

fn colon_value(tree: &SemanticTree, node: &Node) -> Option<String> {
    if text_named_by_content(tree, node) {
        return node.name.clone();
    }
    if is_text_role(node.role) {
        let text = tree.text_content(node.id);
        return (!text.is_empty() && node.name.as_deref() != Some(text)).then(|| text.to_owned());
    }
    match &node.value {
        Some(Value::Text(text)) => Some(text.clone()),
        _ => None,
    }
}

/// A value as a YAML scalar: plain when YAML and the template reader read it back unchanged,
/// otherwise double-quoted.
fn scalar(text: &str) -> String {
    let starts_plain = text
        .chars()
        .next()
        .is_some_and(|c| !"-?:,[]{}#&*!|>'\"%@`/".contains(c));
    let plain = starts_plain
        && text.trim() == text
        && !text.contains(": ")
        && !text.contains(" #")
        && !text.ends_with(':')
        && !text.chars().any(|c| c == '\t' || needs_escape(c));
    if plain {
        return text.to_owned();
    }
    quoted(text)
}

fn number(value: f64) -> String {
    format!("{value}")
}

fn key(tree: &SemanticTree, node: &Node, options: &YamlOptions) -> String {
    let mut out = node.role.selector_name().to_owned();
    if let Some(name) = &node.name
        && !text_named_by_content(tree, node)
    {
        out.push(' ');
        out.push_str(&quoted(name));
    }
    let mut attr = |text: String| {
        out.push_str(" [");
        out.push_str(&text);
        out.push(']');
    };
    for (state, name) in STATE_NAMES {
        let Some(value) = node.states.get(*state) else {
            continue;
        };
        match value {
            StateValue::Bool(true) => attr((*name).to_owned()),
            StateValue::Bool(false) if is_flag(*state) => {}
            other => attr(format!("{name}={other}")),
        }
    }
    if let Some(level) = node.set.level {
        attr(format!("level={level}"));
    }
    if let Some(position) = node.set.position {
        attr(format!("position={position}"));
    }
    if let Some(size) = node.set.size {
        attr(format!("set-size={size}"));
    }
    for (label, field) in [
        ("description", &node.description),
        ("placeholder", &node.placeholder),
        ("tooltip", &node.tooltip),
    ] {
        if let Some(text) = field {
            attr(format!("{label}={}", quoted(text)));
        }
    }
    if let Some(Value::Number {
        now,
        min,
        max,
        step,
    }) = &node.value
    {
        attr(format!("value={}", number(*now)));
        for (label, bound) in [("min", min), ("max", max), ("step", step)] {
            if let Some(bound) = bound {
                attr(format!("{label}={}", number(*bound)));
            }
        }
    }
    for (prop, value) in &node.props {
        let shown = if options.mask_props.iter().any(|m| m == prop) {
            "***"
        } else {
            value.as_str()
        };
        attr(format!("prop:{prop}={}", quoted(shown)));
    }
    if options.include_ids {
        if let Some(id) = &node.test_id {
            attr(format!("test-id={}", quoted(id)));
        }
        match &node.widget_id {
            Some(WidgetId::Custom(id)) => attr(format!("widget-id={}", quoted(id))),
            Some(WidgetId::Unique(n)) => attr(format!("widget-id=#{n}")),
            None => {}
        }
    }
    if options.refs && node.role.is_interactive() {
        attr(format!("ref={}", node.id));
    }
    if options.include_bounds {
        let b = node.bounds;
        let _ = write!(
            out,
            " @ {},{} {}x{}",
            b.x.round(),
            b.y.round(),
            b.width.round(),
            b.height.round()
        );
    }
    out
}

/// Reads YAML written by [`write()`] or by hand into a tree. Bounds are zero where the YAML has
/// none, and states are taken as written rather than derived. Top-level `window` entries
/// become windows; anything else is wrapped in one unnamed window, so writing that window
/// gives back the same text.
pub fn read(yaml: &str) -> Result<SemanticTree, Error> {
    let yaml = normalise(yaml);
    let mut entries: Vec<(usize, usize, Draft, Option<String>)> = Vec::new();
    for (index, raw_line) in yaml.lines().enumerate() {
        let line_number = index + 1;
        if raw_line.trim().is_empty() {
            continue;
        }
        let indent = raw_line.len() - raw_line.trim_start_matches(' ').len();
        if indent % 2 != 0 {
            return Err(yaml_error(
                line_number,
                indent + 1,
                "indentation must be a multiple of two spaces",
            ));
        }
        let Some(item) = raw_line.get(indent..).and_then(|l| l.strip_prefix("- ")) else {
            return Err(yaml_error(
                line_number,
                indent + 1,
                "expected `- ` to start an entry",
            ));
        };
        if item == "..." {
            continue;
        }
        let column = indent + 3;
        if let Some(value) = item.strip_prefix("/value: ") {
            let value = read_scalar(value)
                .map_err(|(at, m)| yaml_error(line_number, column + 8 + at, &m))?;
            entries.push((
                indent / 2,
                line_number,
                Draft::new(Node::blank(Role::Unknown, yaml_kind(), WindowId(0))),
                Some(value),
            ));
            continue;
        }
        let draft = read_entry(item).map_err(|(at, m)| yaml_error(line_number, column + at, &m))?;
        entries.push((indent / 2, line_number, draft, None));
    }
    let (_, top) = nest(&mut entries.into_iter().peekable(), 0)?;
    let windows = if !top.is_empty() && top.iter().all(|d| d.node.role == Role::Window) {
        top
    } else {
        let mut window = Draft::new(Node::blank(Role::Window, yaml_kind(), WindowId(0)));
        window.children = top;
        vec![window]
    };
    let windows = windows
        .into_iter()
        .enumerate()
        .map(|(i, mut window)| {
            let id = WindowId(u64::try_from(i).unwrap_or(u64::MAX));
            set_window(&mut window, id);
            window
        })
        .collect();
    Ok(build::finish(windows, Mode::Keep))
}

fn set_window(draft: &mut Draft, window: WindowId) {
    draft.node.window = window;
    for child in &mut draft.children {
        set_window(child, window);
    }
}

fn yaml_kind() -> Kind {
    Kind::Annotated(Cow::Borrowed("app"))
}

fn yaml_error(line: usize, column: usize, message: &str) -> Error {
    Error::Yaml {
        line,
        column,
        message: message.to_owned(),
    }
}

type Entry = (usize, usize, Draft, Option<String>);

/// The entries at `depth` and below, with a leading `/value` entry returned apart.
fn nest(
    entries: &mut std::iter::Peekable<impl Iterator<Item = Entry>>,
    depth: usize,
) -> Result<(Option<String>, Vec<Draft>), Error> {
    let mut leading = None;
    let mut out: Vec<Draft> = Vec::new();
    while let Some((entry_depth, line, _, _)) = entries.peek() {
        let (entry_depth, line) = (*entry_depth, *line);
        if entry_depth < depth {
            break;
        }
        if entry_depth > depth {
            let Some(parent) = out.last_mut() else {
                return Err(yaml_error(
                    line,
                    entry_depth * 2 + 1,
                    "entry is indented under nothing",
                ));
            };
            let (value, children) = nest(entries, depth + 1)?;
            if let Some(value) = value {
                parent.node.value = Some(Value::Text(value));
            }
            parent.children.extend(children);
            continue;
        }
        let Some((_, _, draft, value)) = entries.next() else {
            break;
        };
        match value {
            Some(value) if out.is_empty() && leading.is_none() && depth > 0 => {
                leading = Some(value);
            }
            Some(_) => {
                return Err(yaml_error(
                    line,
                    depth * 2 + 1,
                    "`/value` must be the first child of a node",
                ));
            }
            None => out.push(draft),
        }
    }
    Ok((leading, out))
}

fn read_scalar(text: &str) -> Result<String, (usize, String)> {
    if !text.starts_with('"') {
        return Ok(text.to_owned());
    }
    let mut cursor = Cursor::new(text);
    let value = cursor.quoted()?;
    if !cursor.rest().is_empty() {
        return Err((
            cursor.offset,
            "unexpected text after the closing quote".to_owned(),
        ));
    }
    Ok(value)
}

fn read_number(cursor: &mut Cursor<'_>) -> Result<f64, (usize, String)> {
    let at = cursor.offset;
    let text = cursor.take_while(|c| {
        c.is_ascii_digit() || matches!(c, '-' | '.' | 'e' | 'E' | '+' | 'i' | 'n' | 'f' | 'N' | 'a')
    });
    text.parse()
        .map_err(|_| (at, format!("`{text}` is not a number")))
}

fn read_unsigned<T: std::str::FromStr>(cursor: &mut Cursor<'_>) -> Result<T, (usize, String)> {
    let at = cursor.offset;
    let text = cursor.take_while(|c| c.is_ascii_digit());
    text.parse()
        .map_err(|_| (at, "expected a whole number".to_owned()))
}

fn read_entry(item: &str) -> Result<Draft, (usize, String)> {
    let mut cursor = Cursor::new(item);
    let at = cursor.offset;
    let word = cursor.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'));
    let role = Role::from_selector_name(word).ok_or((at, format!("unknown role `{word}`")))?;
    let mut node = Node::blank(role, yaml_kind(), WindowId(0));
    if cursor.rest().starts_with(" \"") {
        cursor.offset += 1;
        node.name = Some(cursor.quoted()?);
        node.name_source = NameSource::Annotation;
    }
    while cursor.rest().starts_with(" [") {
        cursor.offset += 2;
        read_attribute(&mut cursor, &mut node)?;
        if !cursor.eat("]") {
            return Err((cursor.offset, "expected `]`".to_owned()));
        }
    }
    if cursor.eat(" @ ") {
        let x = read_number(&mut cursor)?;
        let y = if cursor.eat(",") {
            read_number(&mut cursor)?
        } else {
            return Err((cursor.offset, "expected `,`".to_owned()));
        };
        if !cursor.eat(" ") {
            return Err((cursor.offset, "expected a space before the size".to_owned()));
        }
        let width = read_number(&mut cursor)?;
        if !cursor.eat("x") {
            return Err((cursor.offset, "expected `x`".to_owned()));
        }
        let height = read_number(&mut cursor)?;
        node.bounds = Rect::new(
            Point::new(x as f32, y as f32),
            Size::new(width as f32, height as f32),
        );
        if node.bounds.area() > 0.0 && !node.states.offscreen {
            node.visible_bounds = Some(node.bounds);
        }
    }
    let mut value = None;
    if cursor.eat(": ") {
        value = Some(read_scalar(cursor.rest()).map_err(|(o, m)| (cursor.offset + o, m))?);
        cursor.offset = cursor.input.len();
    } else {
        cursor.eat(":");
    }
    if !cursor.rest().is_empty() {
        return Err((cursor.offset, format!("unexpected `{}`", cursor.rest())));
    }
    let mut draft = Draft::new(node);
    match value {
        Some(text) if is_text_role(role) && draft.node.name.is_none() => {
            draft.node.name = Some(text.clone());
            draft.node.name_source = NameSource::Text;
            draft.own_text = Some(text);
        }
        Some(text) if is_text_role(role) => draft.own_text = Some(text),
        Some(text) => draft.node.value = Some(Value::Text(text)),
        None => {}
    }
    if is_text_role(role) && draft.own_text.is_none() {
        draft.own_text = draft.node.name.clone();
    }
    if named_from_content(role) {
        draft.own_text = draft.node.name.clone();
    }
    Ok(draft)
}

fn read_attribute(cursor: &mut Cursor<'_>, node: &mut Node) -> Result<(), (usize, String)> {
    let at = cursor.offset;
    let name =
        cursor.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | ':' | '.'));
    let has_value = cursor.eat("=");
    if let Some(prop) = name.strip_prefix("prop:") {
        if !has_value {
            return Err((cursor.offset, "expected `=` after a prop".to_owned()));
        }
        node.props.insert(prop.to_owned(), cursor.quoted()?);
        return Ok(());
    }
    if let Some((state, _)) = STATE_NAMES.iter().find(|(_, n)| *n == name) {
        let value = if has_value {
            let at = cursor.offset;
            let word = cursor.take_while(|c| c.is_ascii_alphabetic());
            word.parse::<StateValue>()
                .map_err(|e| (at, e.to_string()))?
        } else {
            StateValue::Bool(true)
        };
        node.states.set(*state, value, StateSource::Annotation);
        return Ok(());
    }
    if !has_value {
        return Err((at, format!("unknown attribute `{name}`")));
    }
    match name {
        "level" => node.set.level = Some(read_unsigned(cursor)?),
        "position" => node.set.position = Some(read_unsigned(cursor)?),
        "set-size" => node.set.size = Some(read_unsigned(cursor)?),
        "description" => node.description = Some(cursor.quoted()?),
        "placeholder" => node.placeholder = Some(cursor.quoted()?),
        "tooltip" => node.tooltip = Some(cursor.quoted()?),
        "test-id" => node.test_id = Some(cursor.quoted()?),
        "widget-id" if cursor.eat("#") => {
            node.widget_id = Some(WidgetId::Unique(read_unsigned(cursor)?))
        }
        "widget-id" => node.widget_id = Some(WidgetId::Custom(cursor.quoted()?)),
        "ref" => {
            cursor.take_while(|c| c.is_ascii_alphanumeric());
        }
        "value" | "min" | "max" | "step" => {
            let number = read_number(cursor)?;
            let (mut now, mut min, mut max, mut step) = match node.value {
                Some(Value::Number {
                    now,
                    min,
                    max,
                    step,
                }) => (now, min, max, step),
                _ => (0.0, None, None, None),
            };
            match name {
                "value" => now = number,
                "min" => min = Some(number),
                "max" => max = Some(number),
                _ => step = Some(number),
            }
            node.value = Some(Value::Number {
                now,
                min,
                max,
                step,
            });
        }
        other => return Err((at, format!("unknown attribute `{other}`"))),
    }
    Ok(())
}