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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! Typed diagnostic variants emitted from tree normalization, widget
//! validation, and runtime bookkeeping.
//!
//! [`Diagnostic`] is the canonical payload shape for every diagnostic
//! emit site in the SDK, widget SDK, and renderer-lib. Variants carry
//! the structured context the emitter knew (widget ID, prop name,
//! clamped value, etc.); `Display` renders a terse single-line form
//! suitable for logs and test assertions. The type also derives
//! `Serialize` / `Deserialize` so a structured-diagnostic wire
//! channel can carry the same value unchanged if one is added later.
//!
//! The enum is `#[non_exhaustive]` so adding a new variant is not a
//! semver break. New emit sites should add a dedicated variant rather
//! than shoehorn through an existing one.
use serde::{Deserialize, Serialize};
use strum::EnumDiscriminants;
/// A structured diagnostic emitted by the SDK or renderer.
///
/// Variants are additive; consumers that pattern-match exhaustively
/// need to include a `_ => { ... }` arm because the enum is marked
/// `#[non_exhaustive]`.
///
/// The companion [`DiagnosticKind`] enum is auto-generated by strum's
/// [`EnumDiscriminants`] derive so the variant list, the discriminant
/// list, and the [`Diagnostic::kind`] mapping can never drift apart.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, EnumDiscriminants)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[strum_discriminants(name(DiagnosticKind))]
#[strum_discriminants(derive(Hash, Serialize, Deserialize))]
#[strum_discriminants(serde(rename_all = "snake_case"))]
#[strum_discriminants(vis(pub))]
#[non_exhaustive]
pub enum Diagnostic {
/// A widget ID collided with one already declared within the same
/// window scope.
DuplicateId {
/// Fully-qualified (scoped) ID that collided.
id: String,
/// Window scope, if the tree is inside one.
window_id: Option<String>,
},
/// A view declared a widget with an empty ID where a non-empty
/// one was expected. Auto-generated IDs (prefixed `auto:`) and
/// legitimate structural wrappers don't fire this; only an
/// explicit `.id("")` at a user call site does.
EmptyId {
/// Widget type name (e.g. `"container"`).
type_name: String,
},
/// The app returned multiple top-level windows on a target that
/// cannot host peer OS windows. Native transports accept
/// multi-window views directly; WASM targets (which have no
/// OS-level multi-window capability) emit this diagnostic and
/// typically collapse the list to a single visible window.
MultipleTopLevelWindows {
/// IDs of the peer windows observed at the top level.
window_ids: Vec<String>,
},
/// A subscription was declared for a window that is not currently
/// in the tree. The renderer will accept the subscription but
/// never deliver events.
UnknownWindow {
/// Window ID the subscription tried to bind to.
window_id: String,
/// Subscription tag (wire kind).
subscription_tag: String,
},
/// An `__widget__` placeholder in the tree had no registered
/// expander. Indicates an app-level bug: the widget's
/// `.register(widgets)` was skipped while the placeholder was
/// still included in the view tree.
UnrecognizedWidgetPlaceholder {
/// ID of the placeholder node.
id: String,
},
/// Tree traversal reached the global depth cap. The subtree is
/// skipped and (in normalize / render) pruned.
TreeDepthExceeded {
/// ID of the node whose subtree was skipped.
id: String,
/// The depth cap that was hit.
max_depth: usize,
},
/// Duplicate-ID validation stopped collecting after reaching the
/// configured cap. The tree may contain more duplicates than are
/// listed.
TooManyDuplicates {
/// Cap at which collection was stopped.
limit: usize,
},
/// A user-authored widget ID violated the canonical ID ruleset
/// (length, reserved characters).
WidgetIdInvalid {
/// Stable machine-readable reason tag. One of `too_long` or
/// `reserved_char`.
reason: String,
/// Widget type name the ID was declared on.
type_name: String,
/// The offending ID verbatim (may be empty or truncated in
/// `Display` for very long cases).
id: String,
/// Human-readable detail sentence describing the violation.
/// `Display` appends this to `widget_id_invalid: `.
detail: String,
},
/// A widget that requires a screen-reader-announcable name was
/// declared without one.
MissingAccessibleName {
/// Widget type name (e.g. `"button"`).
type_name: String,
/// Scoped ID of the offending widget.
id: String,
},
/// A cross-widget a11y reference (`labelled_by`, `described_by`,
/// `error_message`, `active_descendant`, or a `radio_group`
/// entry) did not resolve to any declared widget.
A11yRefUnresolved {
/// Scoped ID of the widget carrying the reference.
id: String,
/// a11y field name. For `radio_group` entries, this is
/// `"radio_group"`.
key: String,
/// Raw (pre-rewrite) reference value.
value: String,
/// True when the reference appeared as an element of an
/// array-valued a11y field like `radio_group`. Used by
/// `Display` to produce the "member" phrasing.
is_member: bool,
},
/// A numeric prop was outside its declared range and clamped.
PropRangeExceeded {
/// Scoped ID of the widget.
id: String,
/// Widget type name.
type_name: String,
/// Prop name.
prop: String,
/// Raw (pre-clamp) value as it appeared on the wire, captured
/// as a string so non-finite f64 values (`"NaN"`, `"inf"`,
/// `"-inf"`) round-trip cleanly through JSON. JSON has no
/// non-finite number representation, so storing this as `f64`
/// would lose information at serialization time.
raw: String,
/// Clamped value stored back into the prop.
clamped: f64,
/// True when the raw value was non-finite (NaN or Inf);
/// changes the `Display` phrasing.
non_finite: bool,
},
/// A prop value had an unexpected JSON type.
PropTypeMismatch {
/// Scoped ID of the widget.
id: String,
/// Widget type name.
type_name: String,
/// Prop name.
prop: String,
/// Debug-rendered value that failed the type check.
value_debug: String,
/// Debug-rendered expected type enum value.
expected_debug: String,
},
/// A widget carried a prop name not in its declared schema.
PropUnknown {
/// Scoped ID of the widget.
id: String,
/// Widget type name.
type_name: String,
/// The unexpected prop name.
prop: String,
/// Debug-rendered list of known prop names.
known_debug: String,
},
/// A text-like content prop exceeded its per-widget byte cap and
/// was truncated on a UTF-8 char boundary.
ContentLengthExceeded {
/// Widget ID whose content was truncated.
id: String,
/// Field name (`value`, `content`, etc.).
field: String,
/// Actual byte length on input.
actual: usize,
/// Configured cap.
cap: usize,
/// Byte length after truncation (may be < `cap` when the cap
/// fell mid-codepoint).
truncated: usize,
},
/// The leaked font-family-name cache reached its entry cap.
/// Subsequent names still resolve but leak without caching.
FontCacheCapExceeded {
/// Cap value (max cache entries).
max: usize,
},
/// Inline fonts declared in Settings exceeded the process-wide
/// font load cap. Excess entries are dropped.
FontCapExceeded {
/// Process-wide font cap.
max: u32,
/// Entries requested in this Settings call.
requested: u32,
/// Entries granted (loaded).
granted: u32,
/// Entries dropped (`requested - granted`).
dropped: u32,
},
/// A font family from `default_font` or its fallback chain did
/// not resolve to a loaded or built-in family.
FontFamilyNotFound {
/// Family name that could not be resolved.
family: String,
},
/// The Settings payload failed typed `deny_unknown_fields`
/// validation. The per-field `get`-and-coerce path still runs so
/// partial settings take effect.
InvalidSettings {
/// Detail from the serde decode error.
detail: String,
},
/// The Settings handshake declared one or more native widget type
/// names under `required_widgets` that the renderer does not know
/// about. Non-fatal; the renderer emits the diagnostic and keeps
/// running so the host SDK can choose how to react.
RequiredWidgetsMissing {
/// Names declared but not registered.
missing: Vec<String>,
},
/// A non-trusted widget panicked inside the registry's
/// catch_unwind firewall. The renderer ignores the widget's
/// contribution for this call and continues.
WidgetPanic {
/// Scoped ID of the panicking node.
id: String,
/// Widget type name.
type_name: String,
/// Human-readable method label (e.g. `"prepare"`, `"render"`).
label: String,
},
/// SVG decode returned a parse error.
SvgParseError {
/// Scoped ID of the SVG widget.
id: String,
/// Source path or identifier that failed.
source: String,
/// Detail from the parser.
detail: String,
},
/// SVG decode exceeded its wall-clock budget.
SvgDecodeTimeout {
/// Scoped ID of the SVG widget.
id: String,
/// Source path or identifier that timed out.
source: String,
/// Deadline that was exceeded, rendered exactly as `{:?}` on
/// the original `std::time::Duration` for Display parity.
deadline_debug: String,
},
/// The leaked dash-segment cache reached its entry cap. New
/// patterns past the cap fall back to undashed rendering.
DashCacheCapExceeded {
/// Cap value (max cache entries).
max: usize,
},
/// A canvas dash pattern exceeded the per-pattern segment limit
/// and was dropped in favor of undashed rendering.
DashSegmentsCapExceeded {
/// Cap value (max segments per pattern).
max: usize,
},
/// The renderer-lib event coalesce map hit its cap and was
/// force-flushed to keep memory bounded.
EmitterCoalesceCapExceeded {
/// Cap value (max pending entries).
cap: usize,
},
/// A composite widget ID was registered against two different
/// widget types, most commonly because the same ID is reused on
/// distinct custom widgets. The SDK panics after emitting this
/// because silent acceptance would trip the downcast path later
/// with no actionable context.
WidgetIdTypeCollision {
/// ID that collided.
id: String,
/// Type name of the previously-registered widget.
existing_type: String,
/// Type name of the widget that attempted to reuse the ID.
incoming_type: String,
},
/// `A::view()` panicked and was caught by the runtime's safety
/// net. The renderer keeps drawing the last-good tree; after
/// enough consecutive failures it injects a visible error
/// overlay.
ViewPanicked {
/// Consecutive panic count (including this one).
consecutive: u32,
/// Best-effort message extracted from the panic payload.
message: String,
},
/// `A::update()` panicked and was caught by the runtime's safety
/// net. The model is reverted to the last-good snapshot so the
/// app keeps running; the consecutive counter is shared with
/// [`Diagnostic::ViewPanicked`] so the frozen-UI overlay surfaces
/// after enough total panics across either callback.
UpdatePanicked {
/// Consecutive panic count (including this one). Counts any
/// combination of view and update panics since the last
/// successful render.
consecutive: u32,
/// Best-effort message extracted from the panic payload.
message: String,
},
/// A wire message carried a `type` field the SDK does not
/// recognise, or arrived without a `type` field at all. Usually
/// signals host / renderer version skew.
UnknownMessageType {
/// The unrecognised message type string, or an empty string
/// when the message had no `type` field.
msg_type: String,
},
/// A patch operation carried an operation name this renderer does
/// not recognise. The operation is ignored and later operations
/// in the same patch are still attempted.
UnknownPatchOp {
/// The unrecognised patch operation name.
op: String,
/// Full patch operation payload as received on the wire.
#[serde(default)]
payload: serde_json::Value,
},
/// The runtime's command dispatch chain exceeded the configured
/// depth limit, indicating an `update` loop that keeps returning a
/// command whose delivered event produces another command. The
/// offending command is dropped; the app keeps running so a
/// recoverable state is still reachable.
DispatchLoopExceeded {
/// Depth counter that tripped the guard (one past the limit).
depth: usize,
/// Configured depth cap.
limit: usize,
},
/// A single wire message exceeded the protocol's 64 MiB per-message
/// size cap. The frame is rejected and the transport is closed;
/// hosts surface the error to the app through their typed-error
/// channel so retry vs abort is a caller decision.
BufferOverflow {
/// Size of the offending frame in bytes.
size: usize,
/// Configured cap in bytes.
limit: usize,
},
}
impl Diagnostic {
/// Stable kind discriminator.
///
/// Thin wrapper over strum's generated `DiagnosticKind::from(&self)`
/// so call sites don't need to import the conversion trait.
pub fn kind(&self) -> DiagnosticKind {
DiagnosticKind::from(self)
}
}
impl std::fmt::Display for Diagnostic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::DuplicateId {
id,
window_id: Some(wid),
} => write!(f, "duplicate_id: {id} (window {wid})"),
Self::DuplicateId {
id,
window_id: None,
} => write!(f, "duplicate_id: {id}"),
Self::EmptyId { type_name } => {
write!(f, "empty_id: {type_name} declared with empty id")
}
Self::MultipleTopLevelWindows { window_ids } => {
write!(f, "multiple_top_level_windows: [{}]", window_ids.join(", "))
}
Self::UnknownWindow {
window_id,
subscription_tag,
} => write!(
f,
"unknown_window: subscription {subscription_tag} targets {window_id} \
which is not in the tree"
),
Self::UnrecognizedWidgetPlaceholder { id } => write!(
f,
"unrecognized_widget_placeholder: {id} has no registered expander"
),
Self::TreeDepthExceeded { id, max_depth } => write!(
f,
"tree_depth_exceeded: subtree at {id} exceeds MAX_TREE_DEPTH={max_depth}"
),
Self::TooManyDuplicates { limit } => {
write!(f, "too_many_duplicates: stopped at {limit}")
}
Self::WidgetIdInvalid {
reason,
type_name,
id,
detail,
} => write!(
f,
"widget_id_invalid: {type_name} id={id:?} ({reason}): {detail}"
),
Self::MissingAccessibleName { type_name, id } => write!(
f,
"missing_accessible_name: {type_name} {id} has no label, text child, \
a11y.label, or a11y.labelled_by"
),
Self::A11yRefUnresolved {
id,
key,
value,
is_member,
} => {
if *is_member {
write!(
f,
"a11y_ref_unresolved: {id} {key} member {value:?} is not a \
declared widget id"
)
} else {
write!(
f,
"a11y_ref_unresolved: {id} {key}={value:?} is not a declared \
widget id"
)
}
}
Self::PropRangeExceeded {
id,
type_name,
prop,
raw,
clamped,
non_finite,
} => {
let cause = if *non_finite {
"non-finite"
} else {
"out of range"
};
write!(
f,
"prop_range_exceeded: {type_name} {id} prop {prop}={raw} \
({cause}), clamped to {clamped}"
)
}
Self::PropTypeMismatch {
id,
type_name,
prop,
value_debug,
expected_debug,
} => write!(
f,
"prop_type_mismatch: {type_name} {id} prop {prop} got {value_debug}, \
expected {expected_debug}"
),
Self::PropUnknown {
id,
type_name,
prop,
known_debug,
} => write!(
f,
"prop_unknown: {type_name} {id} has no prop {prop:?} (known: {known_debug})"
),
Self::ContentLengthExceeded {
id,
field,
actual,
cap,
truncated,
} => write!(
f,
"content_length_exceeded: {id}.{field} = {actual} bytes, cap {cap}, \
truncated to {truncated}"
),
Self::FontCacheCapExceeded { max } => write!(
f,
"font_cache_cap_exceeded: cache full ({max} entries); new names leak uncached"
),
Self::FontCapExceeded {
max,
requested,
granted,
dropped,
} => write!(
f,
"font_cap_exceeded: {requested} requested, {granted} granted, {dropped} \
dropped (max {max})"
),
Self::FontFamilyNotFound { family } => {
write!(f, "font_family_not_found: {family}")
}
Self::InvalidSettings { detail } => {
write!(f, "invalid_settings: {detail}")
}
Self::RequiredWidgetsMissing { missing } => {
write!(f, "required_widgets_missing: {}", missing.join(", "))
}
Self::WidgetPanic {
id,
type_name,
label,
} => write!(f, "widget_panic: {type_name} {id} panicked in {label}"),
Self::SvgParseError { id, source, detail } => {
write!(f, "svg_parse_error: {id} {source:?}: {detail}")
}
Self::SvgDecodeTimeout {
id,
source,
deadline_debug,
} => write!(
f,
"svg_decode_timeout: {id} {source:?} exceeded {deadline_debug}"
),
Self::DashCacheCapExceeded { max } => write!(
f,
"dash_cache_cap_exceeded: cache full ({max} entries); \
new patterns fall back to undashed rendering"
),
Self::DashSegmentsCapExceeded { max } => write!(
f,
"dash_segments_cap_exceeded: pattern exceeded {max} segments; \
falling back to undashed rendering"
),
Self::EmitterCoalesceCapExceeded { cap } => write!(
f,
"emitter_coalesce_cap_exceeded: pending map hit cap ({cap}); flushing"
),
Self::WidgetIdTypeCollision {
id,
existing_type,
incoming_type,
} => write!(
f,
"widget_id_type_collision: id={id} reused across types: \
`{existing_type}` was previously registered; `{incoming_type}` \
attempted to register against the same slot"
),
Self::ViewPanicked {
consecutive,
message,
} => write!(
f,
"view_panicked: A::view() panicked ({consecutive} consecutive): {message}"
),
Self::UpdatePanicked {
consecutive,
message,
} => write!(
f,
"update_panicked: A::update() panicked ({consecutive} consecutive): {message}"
),
Self::UnknownMessageType { msg_type } if msg_type.is_empty() => {
write!(f, "unknown_message_type: wire message without `type` field")
}
Self::UnknownMessageType { msg_type } => write!(
f,
"unknown_message_type: unrecognised renderer message type `{msg_type}`; \
likely a host or renderer version skew"
),
Self::UnknownPatchOp { op, payload } => write!(
f,
"unknown_patch_op: unrecognized patch operation `{op}` with payload {payload}; \
likely a host or renderer version skew"
),
Self::DispatchLoopExceeded { depth, limit } => write!(
f,
"dispatch_loop_exceeded: command chain reached depth {depth} \
(limit {limit}); dropping command to break the loop"
),
Self::BufferOverflow { size, limit } => write!(
f,
"buffer_overflow: wire frame of {size} bytes exceeds {limit} byte limit"
),
}
}
}
impl From<Diagnostic> for String {
fn from(d: Diagnostic) -> Self {
d.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn duplicate_id_display() {
let plain = Diagnostic::DuplicateId {
id: "main#form/email".into(),
window_id: None,
};
assert_eq!(plain.to_string(), "duplicate_id: main#form/email");
let scoped = Diagnostic::DuplicateId {
id: "form/email".into(),
window_id: Some("main".into()),
};
assert_eq!(scoped.to_string(), "duplicate_id: form/email (window main)");
}
#[test]
fn kind_matches_variant() {
let d = Diagnostic::EmptyId {
type_name: "container".into(),
};
assert_eq!(d.kind(), DiagnosticKind::EmptyId);
}
#[test]
fn serde_round_trip() {
let d = Diagnostic::UnknownWindow {
window_id: "settings".into(),
subscription_tag: "on_key_press".into(),
};
let json = serde_json::to_value(&d).unwrap();
let back: Diagnostic = serde_json::from_value(json).unwrap();
assert_eq!(d, back);
}
#[test]
fn diagnostic_kind_serializes_to_snake_case() {
// The wire-visible shape of DiagnosticKind is a snake_case
// string matching the serde tag on Diagnostic. Guard the
// strum-generated enum against accidental drift.
let kind = DiagnosticKind::EmitterCoalesceCapExceeded;
let json = serde_json::to_value(kind).unwrap();
assert_eq!(json, serde_json::json!("emitter_coalesce_cap_exceeded"));
let back: DiagnosticKind = serde_json::from_value(json).unwrap();
assert_eq!(back, kind);
}
#[test]
fn unknown_patch_op_display_kind_and_serde() {
let d = Diagnostic::UnknownPatchOp {
op: "frobnicate".into(),
payload: serde_json::json!({
"op": "frobnicate",
"path": [1, 2],
"value": {"answer": 42}
}),
};
assert_eq!(d.kind(), DiagnosticKind::UnknownPatchOp);
assert_eq!(
d.to_string(),
"unknown_patch_op: unrecognized patch operation `frobnicate` with payload \
{\"op\":\"frobnicate\",\"path\":[1,2],\"value\":{\"answer\":42}}; likely a host \
or renderer version skew"
);
let json = serde_json::to_value(&d).unwrap();
assert_eq!(json["kind"], serde_json::json!("unknown_patch_op"));
assert_eq!(
json["payload"],
serde_json::json!({
"op": "frobnicate",
"path": [1, 2],
"value": {"answer": 42}
})
);
let back: Diagnostic = serde_json::from_value(json).unwrap();
assert_eq!(back, d);
let legacy: Diagnostic = serde_json::from_value(serde_json::json!({
"kind": "unknown_patch_op",
"op": "frobnicate"
}))
.unwrap();
assert_eq!(
legacy,
Diagnostic::UnknownPatchOp {
op: "frobnicate".into(),
payload: serde_json::Value::Null,
}
);
}
#[test]
fn tree_depth_exceeded_display() {
let d = Diagnostic::TreeDepthExceeded {
id: "root".into(),
max_depth: 256,
};
assert_eq!(
d.to_string(),
"tree_depth_exceeded: subtree at root exceeds MAX_TREE_DEPTH=256"
);
}
#[test]
fn widget_id_invalid_display_carries_reason_and_detail() {
let d = Diagnostic::WidgetIdInvalid {
reason: "reserved_char".into(),
type_name: "text_input".into(),
id: "form/field".into(),
detail: "'/' is reserved for scoping".into(),
};
assert_eq!(
d.to_string(),
"widget_id_invalid: text_input id=\"form/field\" (reserved_char): \
'/' is reserved for scoping"
);
}
#[test]
fn prop_range_exceeded_display() {
let oob = Diagnostic::PropRangeExceeded {
id: "slider-1".into(),
type_name: "slider".into(),
prop: "value".into(),
raw: "200".into(),
clamped: 100.0,
non_finite: false,
};
assert_eq!(
oob.to_string(),
"prop_range_exceeded: slider slider-1 prop value=200 (out of range), clamped to 100"
);
let non_finite = Diagnostic::PropRangeExceeded {
id: "slider-1".into(),
type_name: "slider".into(),
prop: "value".into(),
raw: "inf".into(),
clamped: 0.0,
non_finite: true,
};
assert!(non_finite.to_string().contains("(non-finite)"));
assert!(non_finite.to_string().contains("inf"));
}
#[test]
fn content_length_exceeded_display() {
let d = Diagnostic::ContentLengthExceeded {
id: "input".into(),
field: "value".into(),
actual: 100_000,
cap: 65_536,
truncated: 65_535,
};
assert_eq!(
d.to_string(),
"content_length_exceeded: input.value = 100000 bytes, cap 65536, truncated to 65535"
);
}
#[test]
fn widget_panic_display() {
let d = Diagnostic::WidgetPanic {
id: "btn".into(),
type_name: "custom_button".into(),
label: "render".into(),
};
assert_eq!(
d.to_string(),
"widget_panic: custom_button btn panicked in render"
);
}
#[test]
fn font_cap_exceeded_display() {
let d = Diagnostic::FontCapExceeded {
max: 256,
requested: 10,
granted: 3,
dropped: 7,
};
assert_eq!(
d.to_string(),
"font_cap_exceeded: 10 requested, 3 granted, 7 dropped (max 256)"
);
}
#[test]
fn a11y_ref_unresolved_switches_phrasing_on_is_member() {
let single = Diagnostic::A11yRefUnresolved {
id: "r1".into(),
key: "labelled_by".into(),
value: "missing".into(),
is_member: false,
};
assert_eq!(
single.to_string(),
"a11y_ref_unresolved: r1 labelled_by=\"missing\" is not a declared widget id"
);
let member = Diagnostic::A11yRefUnresolved {
id: "r1".into(),
key: "radio_group".into(),
value: "missing".into(),
is_member: true,
};
assert_eq!(
member.to_string(),
"a11y_ref_unresolved: r1 radio_group member \"missing\" is not a declared widget id"
);
}
#[test]
fn kind_for_new_variants_is_unique() {
let tde = Diagnostic::TreeDepthExceeded {
id: "x".into(),
max_depth: 256,
};
assert_eq!(tde.kind(), DiagnosticKind::TreeDepthExceeded);
let wid = Diagnostic::WidgetIdInvalid {
reason: "r".into(),
type_name: "t".into(),
id: "i".into(),
detail: "d".into(),
};
assert_eq!(wid.kind(), DiagnosticKind::WidgetIdInvalid);
}
}