lemon 0.2.0-alpha.14

A reactive UI toolkit for Rust
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
//! Opt-in verbose tracing for debugging Lemon's reactive pipeline.
//!
//! # Enabling
//!
//! Set an environment variable before launching your app:
//!
//! ```bash
//! LEMON_DEBUG=1 cargo run -p components
//! # or filter categories:
//! LEMON_DEBUG=runtime,patches,input,layout cargo run -p components
//! ```
//!
//! `LEMON_TRACE=1` is an alias for `LEMON_DEBUG=1` (all categories).
//!
//! # Categories
//!
//! | Category   | What gets logged                                              |
//! |------------|---------------------------------------------------------------|
//! | `runtime`  | Effect flush, component slots, render/diff of virtual trees  |
//! | `patches`  | Each patch applied to the retained tree                       |
//! | `layout`   | Layout pass entry/exit                                        |
//! | `paint`    | Paint pass stats                                              |
//! | `input`    | Clicks, keyboard dispatch, hit targets                         |
//! | `signal`   | Signal `set` / `update` (very noisy)                          |
//! | `retained` | Retained-tree mount and structural changes                    |
//!
//! Use `1`, `true`, `yes`, or `all` to enable every category.
//!
//! # Programmatic API
//!
//! ```
//! lemon::debug::enable_all();
//! lemon::debug::set_categories(&["runtime", "patches"]);
//! ```

use std::cell::Cell;
use std::fmt::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::OnceLock;

use crate::diff::{NodePath, Patch};
use crate::element::Element;

/// Trace category switch.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Category {
    Runtime,
    Patches,
    Layout,
    Paint,
    Input,
    Signal,
    Retained,
}

impl Category {
    const ALL: &'static [Category] = &[
        Category::Runtime,
        Category::Patches,
        Category::Layout,
        Category::Paint,
        Category::Input,
        Category::Signal,
        Category::Retained,
    ];

    fn name(self) -> &'static str {
        match self {
            Category::Runtime => "runtime",
            Category::Patches => "patches",
            Category::Layout => "layout",
            Category::Paint => "paint",
            Category::Input => "input",
            Category::Signal => "signal",
            Category::Retained => "retained",
        }
    }

    fn parse(name: &str) -> Option<Category> {
        match name.trim().to_ascii_lowercase().as_str() {
            "runtime" => Some(Category::Runtime),
            "patches" | "patch" => Some(Category::Patches),
            "layout" => Some(Category::Layout),
            "paint" => Some(Category::Paint),
            "input" => Some(Category::Input),
            "signal" | "signals" => Some(Category::Signal),
            "retained" => Some(Category::Retained),
            _ => None,
        }
    }
}

struct DebugConfig {
    enabled: bool,
    categories: u32,
}

impl DebugConfig {
    const fn disabled() -> Self {
        Self {
            enabled: false,
            categories: 0,
        }
    }

    fn enable_all(&mut self) {
        self.enabled = true;
        self.categories = u32::MAX;
    }

    fn set_categories(&mut self, names: &[&str]) {
        self.enabled = true;
        self.categories = 0;
        for name in names {
            let normalized = name.trim();
            if matches!(normalized, "1" | "true" | "yes" | "on" | "all" | "*") {
                self.enable_all();
                return;
            }
            if let Some(cat) = Category::parse(normalized) {
                self.categories |= category_bit(cat);
            } else if !normalized.is_empty() {
                eprintln!("[lemon:debug] unknown category {normalized:?} (ignored)");
            }
        }
    }

    fn enabled(&self, cat: Category) -> bool {
        self.enabled && (self.categories & category_bit(cat)) != 0
    }
}

fn category_bit(cat: Category) -> u32 {
    1 << (cat as u32)
}

static CONFIG: OnceLock<DebugConfig> = OnceLock::new();
static FRAME: AtomicU64 = AtomicU64::new(0);

fn config() -> &'static DebugConfig {
    CONFIG.get_or_init(|| {
        if let Ok(value) = std::env::var("LEMON_DEBUG") {
            let mut cfg = DebugConfig::disabled();
            parse_env_value(&mut cfg, &value);
            log_startup(&cfg, "LEMON_DEBUG", &value);
            return cfg;
        }
        if let Ok(value) = std::env::var("LEMON_TRACE") {
            let mut cfg = DebugConfig::disabled();
            parse_env_value(&mut cfg, &value);
            log_startup(&cfg, "LEMON_TRACE", &value);
            return cfg;
        }
        DebugConfig::disabled()
    })
}

fn parse_env_value(cfg: &mut DebugConfig, value: &str) {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return;
    }
    if matches!(trimmed, "1" | "true" | "yes" | "on" | "all" | "*") {
        cfg.enable_all();
        return;
    }
    let parts: Vec<&str> = trimmed
        .split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .collect();
    cfg.set_categories(&parts);
}

fn log_startup(cfg: &DebugConfig, var: &str, raw: &str) {
    if !cfg.enabled {
        eprintln!("[lemon:debug] {var}={raw:?} (no categories enabled)");
        return;
    }
    let mut names = Vec::new();
    for cat in Category::ALL {
        if cfg.enabled(*cat) {
            names.push(cat.name());
        }
    }
    eprintln!(
        "[lemon:debug] enabled via {var}={raw:?} categories=[{}]",
        names.join(", ")
    );
}

/// Re-read is not supported; call before `run` if using env vars.
pub fn configure_from_env() {
    let _ = config();
}

/// Enable every trace category (overrides env until [`disable`]).
pub fn enable_all() {
    PROGRAMMATIC.with(|p| {
        p.enabled.set(true);
        p.categories.set(u32::MAX);
    });
    eprintln!("[lemon:debug] enable_all()");
}

/// Disable all tracing.
pub fn disable() {
    PROGRAMMATIC.with(|p| {
        p.enabled.set(false);
        p.categories.set(0);
    });
    eprintln!("[lemon:debug] disable()");
}

/// Enable only the listed categories (`"runtime"`, `"patches"`, …).
pub fn set_categories(names: &[&str]) {
    PROGRAMMATIC.with(|p| {
        p.enabled.set(true);
        p.categories.set(0);
        for name in names {
            if matches!(*name, "1" | "true" | "yes" | "on" | "all" | "*") {
                p.categories.set(u32::MAX);
                break;
            }
            if let Some(cat) = Category::parse(name) {
                p.categories.set(p.categories.get() | category_bit(cat));
            }
        }
    });
    eprintln!("[lemon:debug] set_categories({names:?})");
}

struct ProgrammaticFlags {
    enabled: Cell<bool>,
    categories: Cell<u32>,
}

impl ProgrammaticFlags {
    const fn new() -> Self {
        Self {
            enabled: Cell::new(false),
            categories: Cell::new(0),
        }
    }
}

thread_local! {
    static PROGRAMMATIC: ProgrammaticFlags = const { ProgrammaticFlags::new() };
}

/// Returns whether tracing is enabled for `cat`.
pub fn enabled(cat: Category) -> bool {
    let programmatic = PROGRAMMATIC.with(|p| {
        if p.enabled.get() {
            Some((p.categories.get() & category_bit(cat)) != 0)
        } else {
            None
        }
    });
    if let Some(on) = programmatic {
        return on;
    }
    config().enabled(cat)
}

/// Log a formatted line when `cat` is enabled.
#[inline]
pub fn trace(cat: Category, message: impl AsRef<str>) {
    if enabled(cat) {
        eprintln!("[lemon:{}] {}", cat.name(), message.as_ref());
    }
}

/// Log with `format!` args when `cat` is enabled.
#[macro_export]
macro_rules! lemon_trace {
    ($cat:ident, $($tt:tt)*) => {
        $crate::debug::trace(
            $crate::debug::Category::$cat,
            format!($($tt)*),
        )
    };
}

/// Bump the per-frame counter (used in log prefixes during `update_frame`).
pub fn next_frame() -> u64 {
    FRAME.fetch_add(1, Ordering::Relaxed) + 1
}

pub fn frame_tag() -> String {
    format!("f{}", FRAME.load(Ordering::Relaxed))
}

/// Format a [`NodePath`] as `[0,1,2]`.
pub fn format_path(path: &NodePath) -> String {
    if path.0.is_empty() {
        return "[]".to_string();
    }
    let mut out = String::from("[");
    for (i, seg) in path.0.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        let _ = write!(out, "{seg}");
    }
    out.push(']');
    out
}

/// Short element kind label for logs.
pub fn element_kind(element: &Element) -> &'static str {
    match element {
        Element::View(_) => "View",
        Element::Row(_) => "Row",
        Element::Column(_) => "Column",
        Element::Text(_) => "Text",
        Element::Button(_) => "Button",
        Element::Image(_) => "Image",
        Element::Component(_) => "Component",
        Element::Fragment(_) => "Fragment",
        Element::None => "None",
    }
}

/// One-line patch description.
pub fn format_patch(patch: &Patch) -> String {
    match patch {
        Patch::UpdateComponent { node, component } => format!(
            "UpdateComponent path={} key={:?} identity={}",
            format_path(node),
            component.key(),
            component.identity()
        ),
        Patch::MountComponent { node, component } => format!(
            "MountComponent path={} key={:?} identity={}",
            format_path(node),
            component.key(),
            component.identity()
        ),
        Patch::UnmountComponent { node } => {
            format!("UnmountComponent path={}", format_path(node))
        }
        Patch::UpdateStyle { node, .. } => {
            format!("UpdateStyle path={}", format_path(node))
        }
        Patch::UpdatePaint { node, .. } => {
            format!("UpdatePaint path={}", format_path(node))
        }
        Patch::UpdateText { node, content } => {
            format!("UpdateText path={} content={content:?}", format_path(node))
        }
        Patch::UpdateTextStyle { node, .. } => {
            format!("UpdateTextStyle path={}", format_path(node))
        }
        Patch::UpdateWidgetChrome { node, .. } => {
            format!("UpdateWidgetChrome path={}", format_path(node))
        }
        Patch::ReplaceNode { node, new_element } => format!(
            "ReplaceNode path={} new={}",
            format_path(node),
            element_kind(new_element)
        ),
        Patch::InsertChild {
            parent,
            index,
            element,
        } => format!(
            "InsertChild parent={} index={index} child={}",
            format_path(parent),
            element_kind(element)
        ),
        Patch::RemoveChild { parent, index } => {
            format!("RemoveChild parent={} index={index}", format_path(parent))
        }
        Patch::MoveChild { parent, from, to } => format!(
            "MoveChild parent={} from={from} to={to}",
            format_path(parent)
        ),
    }
}

/// Log a batch of patches (patches category).
pub fn trace_patches(context: &str, patches: &[Patch]) {
    if !enabled(Category::Patches) && !enabled(Category::Runtime) {
        return;
    }
    if patches.is_empty() {
        trace(Category::Patches, format!("{context}: (no patches)"));
        return;
    }
    trace(
        Category::Patches,
        format!("{context}: {} patch(es)", patches.len()),
    );
    for (i, patch) in patches.iter().enumerate() {
        trace(
            Category::Patches,
            format!("  [{i}] {}", format_patch(patch)),
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn category_parse_and_format_patch() {
        assert_eq!(Category::parse("runtime"), Some(Category::Runtime));
        assert_eq!(Category::parse("PATCHES"), Some(Category::Patches));
        assert!(Category::parse("unknown").is_none());

        let patch = Patch::UpdateText {
            node: NodePath(vec![5, 0]),
            content: "1".to_string(),
        };
        let text = format_patch(&patch);
        assert!(text.contains("UpdateText"));
        assert!(text.contains("[5,0]"));
        assert!(text.contains("\"1\""));
    }
}