node-app-build 0.1.0

Mini app developer CLI: scaffold, validate, package node-app-* Debian packages
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
//! Split-pane TUI for `node-app dev`.
//!
//! # Channel architecture
//!
//! ```text
//! ┌─ producers ──────────────────────────────────────────────────┐
//! │  orchestrator  ──────────────────────────────────────┐       │
//! │  daemon reader threads  ─────────────────────────────┤       │
//! │  ui-server reader threads  ──────────────────────────┤       │
//! │  build capture threads  ─────────────────────────────┤       │
//! └──────────────────────────────────────────────────────▼───────┘
//!                                                SyncSender<TuiEvent>
//!//!                                               TUI render thread
//!                                            (drains rx, draws frame)
//! ```
//!
//! Back-pressure (keyboard → orchestrator) uses `Arc<AtomicBool>` flags so
//! the orchestrator can poll cheaply inside the debounce loop.

pub mod render;
pub mod state;

use std::io;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc};
use std::time::{Duration, Instant};

use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers},
    execute,
    terminal::{self, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};

pub use state::{LogSource, ServiceStatus};

const TICK: Duration = Duration::from_millis(30);

// ── Public types ─────────────────────────────────────────────────────────────

#[derive(Debug)]
pub struct LogEntry {
    pub source: LogSource,
    pub line: String,
}

/// All events flowing from producers into the TUI render thread.
#[derive(Debug)]
pub enum TuiEvent {
    Log(LogEntry),
    Status {
        source: LogSource,
        status: ServiceStatus,
        detail: Option<String>,
    },
}

pub type LogTx = mpsc::SyncSender<TuiEvent>;
pub type LogRx = mpsc::Receiver<TuiEvent>;

/// Signals written by the TUI keyboard handler and read by the orchestrator,
/// plus one signal written by the orchestrator and read by the TUI.
#[derive(Clone)]
pub struct DevSignals {
    pub restart_requested: Arc<AtomicBool>,
    pub build_now_requested: Arc<AtomicBool>,
    /// Set by TUI on q / Ctrl+C — tells orchestrator to start shutting down.
    pub quit_requested: Arc<AtomicBool>,
    /// Set by orchestrator once host_impl.shutdown() fully completes — tells
    /// the TUI it is safe to restore the terminal and exit.
    pub shutdown_complete: Arc<AtomicBool>,
}

impl DevSignals {
    fn new() -> Self {
        Self {
            restart_requested: Arc::new(AtomicBool::new(false)),
            build_now_requested: Arc::new(AtomicBool::new(false)),
            quit_requested: Arc::new(AtomicBool::new(false)),
            shutdown_complete: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Returns true and clears the flag if a restart was requested.
    pub fn take_restart(&self) -> bool {
        self.restart_requested.swap(false, Ordering::SeqCst)
    }

    /// Returns true and clears the flag if an immediate build was requested.
    pub fn take_build_now(&self) -> bool {
        self.build_now_requested.swap(false, Ordering::SeqCst)
    }

    pub fn should_quit(&self) -> bool {
        self.quit_requested.load(Ordering::SeqCst)
    }

    /// Called by the orchestrator after shutdown is complete.
    pub fn mark_shutdown_complete(&self) {
        self.shutdown_complete.store(true, Ordering::SeqCst);
    }
}

// ── Setup ────────────────────────────────────────────────────────────────────

/// Create channels + signals. Returns `(producer tx, consumer rx, signals)`.
pub fn setup() -> (LogTx, LogRx, DevSignals) {
    let (tx, rx) = mpsc::sync_channel(512);
    (tx, rx, DevSignals::new())
}

/// Returns true when stdout is a real TTY (i.e. TUI should be enabled).
pub fn is_tty() -> bool {
    use std::io::IsTerminal;
    std::io::stdout().is_terminal()
}

// ── Helpers for producers ────────────────────────────────────────────────────

/// Send a System-level log line, or fall back to `eprintln!` when no sink.
pub fn sys_log(tx: Option<&LogTx>, line: impl Into<String>) {
    match tx {
        Some(t) => {
            let _ = t.send(TuiEvent::Log(LogEntry {
                source: LogSource::System,
                line: line.into(),
            }));
        }
        None => eprintln!("{}", line.into()),
    }
}

/// Send a service-status update.
pub fn update_status(
    tx: Option<&LogTx>,
    source: LogSource,
    status: ServiceStatus,
    detail: Option<String>,
) {
    if let Some(t) = tx {
        let _ = t.send(TuiEvent::Status {
            source,
            status,
            detail,
        });
    }
}

// ── TUI render loop ──────────────────────────────────────────────────────────

/// Run the TUI. Blocks until the user presses `q` / `Ctrl+C`.
/// Call from a dedicated thread; the main thread continues running the
/// orchestrator while this thread owns the terminal.
pub fn run(rx: LogRx, mut app: state::AppState, signals: DevSignals) -> io::Result<()> {
    terminal::enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let result = render_loop(&mut terminal, rx, &mut app, &signals);

    // Disable mouse tracking before leaving the alternate screen.
    // Reversing this order causes mouse events buffered between LeaveAlternateScreen
    // and DisableMouseCapture to be printed as raw escape sequences in the shell.
    execute!(
        terminal.backend_mut(),
        DisableMouseCapture,
        LeaveAlternateScreen,
    )?;
    terminal::disable_raw_mode()?;
    terminal.show_cursor()?;
    result
}

fn render_loop<B: ratatui::backend::Backend>(
    terminal: &mut Terminal<B>,
    rx: LogRx,
    app: &mut state::AppState,
    signals: &DevSignals,
) -> io::Result<()> {
    use state::ShutdownPhase;
    let mut last_tick = Instant::now();
    loop {
        // Drain all pending events (non-blocking).
        loop {
            match rx.try_recv() {
                Ok(TuiEvent::Log(entry)) => app.push_log(entry),
                Ok(TuiEvent::Status {
                    source,
                    status,
                    detail,
                }) => app.update_service(source, status, detail),
                Err(_) => break,
            }
        }

        // Once the orchestrator signals shutdown is done, exit the render loop.
        if signals.shutdown_complete.load(Ordering::SeqCst) {
            app.shutdown_phase = ShutdownPhase::Done;
            terminal.draw(|f| render::draw(f, app))?;
            return Ok(());
        }

        terminal.draw(|f| render::draw(f, app))?;

        // While shutting down, skip keyboard processing — just keep rendering
        // progress until the orchestrator sets shutdown_complete.
        if app.shutdown_phase == ShutdownPhase::ShuttingDown {
            if last_tick.elapsed() >= TICK {
                last_tick = Instant::now();
            }
            continue;
        }

        // Poll keyboard/mouse for the remaining tick budget.
        let remaining = TICK.saturating_sub(last_tick.elapsed());
        if event::poll(remaining)? {
            match event::read()? {
                Event::Key(key) => {
                    if key.code == KeyCode::Char('c')
                        && key.modifiers.contains(KeyModifiers::CONTROL)
                    {
                        begin_shutdown(app, signals);
                    } else if app.search_input_active {
                        handle_search_input(key, app);
                    } else {
                        handle_normal(key, app, signals);
                    }
                }
                Event::Mouse(mouse_event) => {
                    handle_mouse(mouse_event, app);
                }
                _ => {}
            }
        }

        // Clear expired copy flash.
        if app
            .copy_flash
            .is_some_and(|t| t.elapsed() > std::time::Duration::from_secs(2))
        {
            app.copy_flash = None;
        }

        if last_tick.elapsed() >= TICK {
            last_tick = Instant::now();
        }
    }
}

/// Switch the TUI to shutdown display mode and signal the orchestrator.
fn begin_shutdown(app: &mut state::AppState, signals: &DevSignals) {
    use state::ShutdownPhase;
    if app.shutdown_phase != ShutdownPhase::Running {
        return;
    }
    app.shutdown_phase = ShutdownPhase::ShuttingDown;
    // Switch to System pane so shutdown log messages are immediately visible.
    app.active_pane = LogSource::System;
    app.scroll_bottom();
    app.clear_search();
    signals.quit_requested.store(true, Ordering::SeqCst);
}

/// Key handling while the search box is open.
fn handle_search_input(key: event::KeyEvent, app: &mut state::AppState) {
    let shift = key.modifiers.contains(KeyModifiers::SHIFT);
    match key.code {
        KeyCode::Enter | KeyCode::Esc => app.exit_search_input(),
        KeyCode::Backspace => app.search_backspace(),
        KeyCode::Up => {
            if shift { app.page_up() } else { app.scroll_up() }
        }
        KeyCode::Down => {
            if shift { app.page_down() } else { app.scroll_down() }
        }
        KeyCode::Char(c) => app.search_push(c),
        _ => {}
    }
}

/// Key handling in normal (non-search-input) mode.
fn handle_normal(key: event::KeyEvent, app: &mut state::AppState, signals: &DevSignals) {
    let shift = key.modifiers.contains(KeyModifiers::SHIFT);
    match key.code {
        KeyCode::Char('q') => begin_shutdown(app, signals),
        KeyCode::Char('/') => app.enter_search(),
        KeyCode::Esc => app.clear_search(),
        // Orchestrator signals.
        KeyCode::Char('r') => {
            signals.restart_requested.store(true, Ordering::SeqCst);
        }
        KeyCode::Char('b') => {
            signals.build_now_requested.store(true, Ordering::SeqCst);
        }
        // Pane navigation.
        KeyCode::Tab => app.cycle_pane(1),
        KeyCode::BackTab => app.cycle_pane(-1),
        KeyCode::Char('1') => app.active_pane = LogSource::System,
        KeyCode::Char('2') => app.active_pane = LogSource::Daemon,
        KeyCode::Char('3') => app.active_pane = LogSource::UiServer,
        KeyCode::Char('4') => app.active_pane = LogSource::Build,
        KeyCode::Char('5') => app.active_pane = LogSource::App,
        // Scrolling — Shift+↑/↓ pages, plain ↑/↓ lines.
        KeyCode::Up => {
            if shift { app.page_up() } else { app.scroll_up() }
        }
        KeyCode::Down => {
            if shift { app.page_down() } else { app.scroll_down() }
        }
        KeyCode::Char('g') => app.scroll_top(),
        KeyCode::Char('G') => app.scroll_bottom(),
        KeyCode::Char('c') => app.clear_active_pane(),
        _ => {}
    }
}

/// Copy text to the system clipboard.
/// Returns `true` if the clipboard command succeeded.
fn copy_to_clipboard(text: &str) -> bool {
    use std::io::Write as _;
    #[cfg(target_os = "macos")]
    {
        if let Ok(mut child) = std::process::Command::new("pbcopy")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
        {
            if let Some(mut stdin) = child.stdin.take() {
                let _ = stdin.write_all(text.as_bytes());
            }
            return child.wait().map(|s| s.success()).unwrap_or(false);
        }
        false
    }
    #[cfg(target_os = "linux")]
    {
        for (cmd, args) in [
            ("wl-copy", vec![] as Vec<&str>),
            ("xclip", vec!["-selection", "clipboard"]),
        ] {
            if let Ok(mut child) = std::process::Command::new(cmd)
                .args(&args)
                .stdin(std::process::Stdio::piped())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()
            {
                if let Some(mut stdin) = child.stdin.take() {
                    let _ = stdin.write_all(text.as_bytes());
                }
                if child.wait().map(|s| s.success()).unwrap_or(false) {
                    return true;
                }
            }
        }
        false
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        let _ = text;
        false
    }
}

/// Handle a mouse event, updating app state accordingly.
fn handle_mouse(mouse: crossterm::event::MouseEvent, app: &mut state::AppState) {
    use crossterm::event::{MouseButton, MouseEventKind};
    use state::Selection;

    let col = mouse.column;
    let row = mouse.row;
    let layout = app.layout;

    // ── Mouse wheel: scroll anywhere in the right panel ────────────────────────
    let in_log_panel = col >= layout.tab_bar.x;
    match mouse.kind {
        MouseEventKind::ScrollUp if in_log_panel => {
            app.scroll_up();
            return;
        }
        MouseEventKind::ScrollDown if in_log_panel => {
            app.scroll_down();
            return;
        }
        _ => {}
    }

    // ── Click on tab bar ───────────────────────────────────────────────────────
    if row == layout.tab_bar.y
        && col >= layout.tab_bar.x
        && col < layout.tab_bar.x + layout.tab_bar.width
    {
        let sources = LogSource::all();
        for i in 0..sources.len() {
            let x_start = layout.tab_edges[i];
            let x_end = if i + 1 < sources.len() {
                layout.tab_edges[i + 1]
            } else {
                u16::MAX
            };
            if col >= x_start && col < x_end {
                if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) {
                    app.active_pane = sources[i];
                    app.auto_scroll = true;
                    app.clear_search();
                    app.selection = None;
                }
                return;
            }
        }
        return;
    }

    // ── Click in service list ──────────────────────────────────────────────────
    let sl = layout.service_list;
    if col >= sl.x && col < sl.x + sl.width && row >= sl.y && row < sl.y + sl.height {
        if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) && row > sl.y {
            // sl.y is the title row; items start at sl.y + 1, each 3 rows tall.
            let row_in_items = (row - sl.y - 1) as usize;
            let idx = row_in_items / 3;
            let sources = LogSource::all();
            if idx < sources.len() {
                app.active_pane = sources[idx];
                app.auto_scroll = true;
                app.clear_search();
                app.selection = None;
            }
        }
        return;
    }

    // ── Drag selection in log scroll area ─────────────────────────────────────
    let ls = layout.log_scroll;
    if col < ls.x || col >= ls.x + ls.width || row < ls.y || row >= ls.y + ls.height {
        return;
    }
    // Only support selection when no filter is active.
    if !app.search_query.is_empty() {
        return;
    }

    let row_in_area = (row - ls.y) as usize;
    let total = app.log_lines(app.active_pane).len();
    let line_idx = app.log_scroll_start + row_in_area;
    if line_idx >= total {
        return;
    }

    match mouse.kind {
        MouseEventKind::Down(MouseButton::Left) => {
            app.selection = Some(Selection { anchor: line_idx, head: line_idx });
            app.auto_scroll = false;
            if app.scroll_pos == 0 {
                app.scroll_pos = app.log_scroll_start;
            }
        }
        MouseEventKind::Drag(MouseButton::Left) => {
            if let Some(sel) = app.selection.as_mut() {
                sel.head = line_idx;
            }
        }
        MouseEventKind::Up(MouseButton::Left) => {
            if let Some(sel) = app.selection {
                // Copy on release (even single-line selections).
                let text = app.get_selected_text();
                if !text.is_empty() && copy_to_clipboard(&text) {
                    app.copy_flash = Some(std::time::Instant::now());
                }
                // Keep the selection visible so the user sees what was copied.
                let _ = sel;
            }
        }
        _ => {}
    }
}