tela-engine 0.1.0

Runtime engine for Tela — React Native for terminals. QuickJS bridge, native APIs, and ratatui renderer.
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
use anyhow::{Context, Result, anyhow};
use crossterm::{
    event::{DisableMouseCapture, EnableMouseCapture, Event, EventStream, KeyCode, KeyEventKind, KeyModifiers},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use futures_util::StreamExt;
use ratatui::{backend::CrosstermBackend, Terminal};
use rquickjs::{AsyncContext, AsyncRuntime};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;

use crate::elements::Element;
use crate::native::{
    register_clipboard, register_console, register_env, register_fetch, register_filesystem,
    register_storage, register_timers, register_websocket, TimerHandles, WsSenders,
};

const H_AND_FRAGMENT: &str = r#"
globalThis.h = function h(tag, props, ...children) {
    var flatChildren = children
        .flat(Infinity)
        .filter(function(c) { return c != null && c !== false && c !== true; })
        .map(function(c) {
            return (typeof c === 'string' || typeof c === 'number')
                ? { tag: '__text__', props: { content: String(c) }, children: [] }
                : c;
        });
    if (typeof tag === 'function') {
        return tag(Object.assign({}, props, { children: flatChildren }));
    }
    return { tag: tag, props: props || {}, children: flatChildren };
};

globalThis.Fragment = function Fragment(props) {
    return { tag: '__fragment__', props: {}, children: props.children || [] };
};

globalThis.__tela_state__ = undefined;
globalThis.__tela_dispatch_queue__ = [];
globalThis.__tela_quit__ = false;

globalThis.Tela = {
    dispatch: function(action) {
        globalThis.__tela_dispatch_queue__.push(action);
    },
    quit: function() {
        globalThis.__tela_quit__ = true;
    },
    columns: 0,
    rows: 0,
};
"#;

const TELA_RUNTIME: &str = r#"
(function() {
    var userReduce = globalThis.reduce;
    var bindings = globalThis.keybindings;

    if (!bindings || !userReduce) return;

    globalThis.reduce = function(state, action) {
        if (action.type !== "__tela_key__") {
            return userReduce(state, action);
        }

        var mode = (state && state.mode) || "normal";
        var modeBindings = bindings[mode] || {};

        var keyName = action.key;
        if (action.ctrl) keyName = "Ctrl+" + keyName;
        if (action.alt) keyName = "Alt+" + keyName;
        if (action.shift && action.key.length > 1) keyName = "Shift+" + keyName;

        var actionName = modeBindings[keyName] || modeBindings[action.key];

        // Check for multi-key sequence match
        if (!actionName) {
            globalThis.__tela_key_buffer__ = globalThis.__tela_key_buffer__ || [];
            globalThis.__tela_key_buffer__.push(action.key);
            var seq = globalThis.__tela_key_buffer__.join(" ");

            // Check exact match
            if (modeBindings[seq]) {
                clearTimeout(globalThis.__tela_key_timer__);
                globalThis.__tela_key_buffer__ = [];
                actionName = modeBindings[seq];
            } else {
                // Check if any binding starts with this prefix
                var hasPrefix = Object.keys(modeBindings).some(function(k) {
                    return k.indexOf(seq + " ") === 0;
                });
                if (hasPrefix) {
                    clearTimeout(globalThis.__tela_key_timer__);
                    globalThis.__tela_key_timer__ = setTimeout(function() {
                        globalThis.__tela_key_buffer__ = [];
                    }, 500);
                    return state;
                }
                // No match and no prefix — reset and fall through
                globalThis.__tela_key_buffer__ = [];
            }
        } else {
            // Single key matched — clear any pending sequence
            globalThis.__tela_key_buffer__ = [];
            clearTimeout(globalThis.__tela_key_timer__);
        }

        if (actionName) {
            if (actionName === "quit") {
                Tela.quit();
                return state;
            }
            return userReduce(state, { type: actionName });
        }

        if (mode === "insert") {
            if (action.ctrl && action.key === "j") {
                return userReduce(state, { type: "input_newline" });
            }
            if (!action.ctrl && !action.alt && action.key.length === 1) {
                return userReduce(state, { type: "input_char", char: action.key });
            }
            switch (action.key) {
                case "Backspace": return userReduce(state, { type: "input_backspace" });
                case "Enter": return userReduce(state, { type: "input_submit" });
                case "Escape": return userReduce(state, { type: "enter_normal" });
            }
        }

        return state;
    };
})();
"#;

pub struct Engine {
    rt: AsyncRuntime,
    ctx: AsyncContext,
    _action_tx: mpsc::UnboundedSender<serde_json::Value>,
    action_rx: tokio::sync::Mutex<mpsc::UnboundedReceiver<serde_json::Value>>,
    _timer_handles: TimerHandles,
    _ws_senders: WsSenders,
}

impl Engine {
    pub async fn new() -> Result<Self> {
        let all_perms: Vec<String> = ["network", "storage", "clipboard", "env"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        Self::new_with_manifest("default", &all_perms).await
    }

    pub async fn new_with_manifest(app_name: &str, permissions: &[String]) -> Result<Self> {
        let rt = AsyncRuntime::new().context("failed to create QuickJS runtime")?;
        let ctx = AsyncContext::full(&rt)
            .await
            .context("failed to create QuickJS context")?;

        let (action_tx, action_rx) = mpsc::unbounded_channel();
        let timer_handles: TimerHandles = Arc::new(Mutex::new(HashMap::new()));
        let ws_senders: WsSenders = Arc::new(Mutex::new(HashMap::new()));

        {
            let tx = action_tx.clone();
            let th = timer_handles.clone();
            let ws = ws_senders.clone();
            let rt_handle = tokio::runtime::Handle::current();
            let app_name = app_name.to_string();
            let perms: Vec<String> = permissions.to_vec();
            ctx.with(move |ctx| -> Result<()> {
                register_console(&ctx)?;
                ctx.eval::<(), _>(H_AND_FRAGMENT)
                    .map_err(|e| anyhow!("failed to register h/Fragment: {e}"))?;
                register_timers(&ctx, tx.clone(), th, rt_handle.clone())?;
                if perms.iter().any(|p| p == "network") {
                    register_fetch(&ctx, tx.clone(), rt_handle.clone())?;
                    register_websocket(&ctx, tx, ws, rt_handle)?;
                }
                if perms.iter().any(|p| p == "storage") {
                    register_storage(&ctx, &app_name)?;
                }
                if perms.iter().any(|p| p == "env") {
                    register_env(&ctx)?;
                }
                if perms.iter().any(|p| p == "clipboard") {
                    register_clipboard(&ctx)?;
                }
                register_filesystem(&ctx, &perms)?;
                Ok(())
            })
            .await?;
        }

        Ok(Engine {
            rt,
            ctx,
            _action_tx: action_tx,
            action_rx: tokio::sync::Mutex::new(action_rx),
            _timer_handles: timer_handles,
            _ws_senders: ws_senders,
        })
    }

    pub async fn load_bundle(&self, source: &str) -> Result<()> {
        let source = source.to_string();
        self.ctx
            .with(move |ctx| -> Result<()> {
                ctx.eval::<(), _>(source.as_str())
                    .map_err(|e| anyhow!("failed to evaluate bundle: {e}"))?;

                ctx.eval::<(), _>(
                    r#"
                    if (typeof initialState !== 'undefined') {
                        globalThis.__tela_state__ = (typeof initialState === 'function')
                            ? initialState()
                            : JSON.parse(JSON.stringify(initialState));
                    }
                    "#,
                )
                .map_err(|e| anyhow!("failed to capture initialState: {e}"))?;

                ctx.eval::<(), _>(TELA_RUNTIME)
                    .map_err(|e| anyhow!("failed to load tela runtime: {e}"))?;

                Ok(())
            })
            .await?;
        Ok(())
    }

    pub async fn get_initial_state_json(&self) -> Result<serde_json::Value> {
        self.ctx
            .with(|ctx| -> Result<serde_json::Value> {
                let val: rquickjs::Value =
                    ctx.eval("globalThis.__tela_state__")
                        .map_err(|e| anyhow!("failed to get state: {e}"))?;
                js_value_to_json(&ctx, val)
            })
            .await
    }

    async fn reduce_and_process(&self, action: serde_json::Value) -> Result<bool> {
        let action_json = serde_json::to_string(&action)?;
        self.ctx
            .with(move |ctx| -> Result<bool> {
                // Set action directly via JSON.parse in a separate eval
                // Double-encode: serde_json::to_string(&action_json) wraps the JSON string
                // in quotes with proper escaping, so it's a valid JS string literal.
                let set_action = format!(
                    "globalThis.__tela_pending_action__ = JSON.parse({});",
                    serde_json::to_string(&action_json).unwrap_or_else(|_| "\"{}\"".to_string())
                );
                ctx.eval::<(), _>(set_action.as_str())
                    .map_err(|e| anyhow!("failed to set action: {e}"))?;

                ctx.eval::<bool, _>(r#"
                    (function() {
                        var action = globalThis.__tela_pending_action__;
                        if (typeof reduce === 'function') {
                            globalThis.__tela_state__ = reduce(globalThis.__tela_state__, action);
                        }
                        for (var i = 0; i < 100; i++) {
                            var q = globalThis.__tela_dispatch_queue__;
                            if (!q || q.length === 0) break;
                            globalThis.__tela_dispatch_queue__ = [];
                            for (var j = 0; j < q.length; j++) {
                                if (typeof reduce === 'function') {
                                    globalThis.__tela_state__ = reduce(globalThis.__tela_state__, q[j]);
                                }
                            }
                        }
                        return globalThis.__tela_quit__ === true;
                    })();
                "#)
                .map_err(|e| anyhow!("reduce_and_process failed: {e}"))
            })
            .await
    }

    pub async fn reduce(&self, action: serde_json::Value) -> Result<()> {
        let action_json = serde_json::to_string(&action)?;
        self.ctx
            .with(move |ctx| -> Result<()> {
                let set_action = format!(
                    "globalThis.__tela_pending_action__ = JSON.parse({});",
                    serde_json::to_string(&action_json).unwrap_or_else(|_| "\"{}\"".to_string())
                );
                ctx.eval::<(), _>(set_action.as_str())
                    .map_err(|e| anyhow!("failed to set action: {e}"))?;

                ctx.eval::<(), _>(r#"
                    (function() {
                        var action = globalThis.__tela_pending_action__;
                        if (typeof reduce === 'function') {
                            globalThis.__tela_state__ = reduce(globalThis.__tela_state__, action);
                        }
                    })();
                "#)
                .map_err(|e| anyhow!("reduce failed: {e}"))?;
                Ok(())
            })
            .await?;
        Ok(())
    }

    pub async fn view(&self) -> Result<Element> {
        self.ctx
            .with(|ctx| -> Result<Element> {
                let result: rquickjs::Value = ctx
                    .eval(
                        r#"
                        (function() {
                            globalThis.__tela_dispatch_queue__ = [];
                            var dispatch = function(action) {
                                globalThis.__tela_dispatch_queue__.push(action);
                            };
                            if (typeof view === 'function') {
                                return view(globalThis.__tela_state__, dispatch);
                            }
                            return { tag: 'text', props: { content: 'no view() exported' }, children: [] };
                        })()
                        "#,
                    )
                    .map_err(|e| anyhow!("view() failed: {e}"))?;

                let json_val = js_value_to_json(&ctx, result)?;
                serde_json::from_value(json_val).context("failed to parse element tree")
            })
            .await
    }

    pub async fn drain_dispatch_queue(&self) -> Result<Vec<serde_json::Value>> {
        self.ctx
            .with(|ctx| -> Result<Vec<serde_json::Value>> {
                let val: rquickjs::Value = ctx
                    .eval(
                        r#"
                        (function() {
                            var q = globalThis.__tela_dispatch_queue__ || [];
                            globalThis.__tela_dispatch_queue__ = [];
                            return q;
                        })()
                        "#,
                    )
                    .map_err(|e| anyhow!("failed to drain dispatch queue: {e}"))?;
                let json_val = js_value_to_json(&ctx, val)?;
                serde_json::from_value(json_val).context("dispatch queue is not an array")
            })
            .await
    }

    pub async fn execute_pending_jobs(&self) {
        for _ in 0..100 {
            match tokio::time::timeout(
                std::time::Duration::from_millis(1),
                self.rt.execute_pending_job(),
            )
            .await
            {
                Ok(Ok(true)) => continue,
                _ => break,
            }
        }
    }

    async fn fire_timer(&self, id: u64) -> Result<()> {
        let id = id as f64;
        self.ctx
            .with(move |ctx| -> Result<()> {
                let func: rquickjs::Function = ctx
                    .globals()
                    .get("__tela_fire_timer__")
                    .map_err(|e| anyhow!("__tela_fire_timer__ not found: {e}"))?;
                func.call::<_, ()>((id,))
                    .map_err(|e| anyhow!("fire_timer failed: {e}"))?;
                Ok(())
            })
            .await
    }

    async fn fire_ws_event(&self, id: u64, event: &str, data: &str) -> Result<()> {
        let id = id as f64;
        let event = event.to_string();
        let data = data.to_string();
        self.ctx
            .with(move |ctx| -> Result<()> {
                let func: rquickjs::Function = ctx
                    .globals()
                    .get("__tela_ws_event__")
                    .map_err(|e| anyhow!("__tela_ws_event__ not found: {e}"))?;
                func.call::<_, ()>((id, event, data))
                    .map_err(|e| anyhow!("fire_ws_event failed: {e}"))?;
                Ok(())
            })
            .await
    }

    async fn resolve_fetch(&self, id: u64, result_json: &str) -> Result<()> {
        let id = id as f64;
        let result_json = result_json.to_string();
        self.ctx
            .with(move |ctx| -> Result<()> {
                let func: rquickjs::Function = ctx
                    .globals()
                    .get("__tela_resolve_fetch__")
                    .map_err(|e| anyhow!("__tela_resolve_fetch__ not found: {e}"))?;
                func.call::<_, ()>((id, result_json))
                    .map_err(|e| anyhow!("resolve_fetch failed: {e}"))?;
                Ok(())
            })
            .await
    }

    async fn check_quit(&self) -> bool {
        self.ctx
            .with(|ctx| -> bool {
                ctx.eval::<bool, _>("globalThis.__tela_quit__ === true")
                    .unwrap_or(false)
            })
            .await
    }

    async fn update_terminal_size(&self) {
        if let Ok((cols, rows)) = crossterm::terminal::size() {
            let cols = cols as u32;
            let rows = rows as u32;
            self.ctx
                .with(move |ctx| {
                    let _ = ctx.eval::<(), _>(format!(
                        "globalThis.Tela.columns={cols};globalThis.Tela.rows={rows};"
                    ));
                })
                .await;
        }
    }

    async fn handle_internal_action(&self, action: serde_json::Value) -> Result<()> {
        match action.get("type").and_then(|v| v.as_str()) {
            Some("__tela_timer__") => {
                let id = action.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
                self.fire_timer(id).await?;
            }
            Some("__tela_ws__") => {
                let id = action.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
                let event = action.get("event").and_then(|v| v.as_str()).unwrap_or("");
                let data = action.get("data").and_then(|v| v.as_str()).unwrap_or("");
                self.fire_ws_event(id, event, data).await?;
            }
            Some("__tela_fetch__") => {
                let id = action.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
                let result = action.get("result").and_then(|v| v.as_str()).unwrap_or("{}");
                self.resolve_fetch(id, result).await?;
                self.execute_pending_jobs().await;
            }
            _ => {
                self.reduce(action).await?;
            }
        }

        let dispatched = self.drain_dispatch_queue().await?;
        for a in dispatched {
            self.reduce(a).await?;
        }
        self.execute_pending_jobs().await;

        Ok(())
    }

    async fn process_event(&self, event: Event) -> Result<bool> {
        match event {
            Event::Key(key) if key.kind == KeyEventKind::Press => {
                if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c')
                {
                    return Ok(true); // quit
                }
                let key_name = match key.code {
                    KeyCode::Char(' ') => Some(" ".to_string()),
                    KeyCode::Char(c) => Some(c.to_string()),
                    KeyCode::Enter => Some("Enter".to_string()),
                    KeyCode::Esc => Some("Escape".to_string()),
                    KeyCode::Backspace => Some("Backspace".to_string()),
                    KeyCode::Tab => Some("Tab".to_string()),
                    KeyCode::Up => Some("Up".to_string()),
                    KeyCode::Down => Some("Down".to_string()),
                    KeyCode::Left => Some("Left".to_string()),
                    KeyCode::Right => Some("Right".to_string()),
                    KeyCode::Home => Some("Home".to_string()),
                    KeyCode::End => Some("End".to_string()),
                    KeyCode::PageUp => Some("PageUp".to_string()),
                    KeyCode::PageDown => Some("PageDown".to_string()),
                    KeyCode::Insert => Some("Insert".to_string()),
                    KeyCode::Delete => Some("Delete".to_string()),
                    KeyCode::F(n) => Some(format!("F{n}")),
                    _ => None,
                };
                
                if let Some(name) = key_name {
                    return self
                        .reduce_and_process(serde_json::json!({
                            "type": "__tela_key__",
                            "key": name,
                            "ctrl": key.modifiers.contains(KeyModifiers::CONTROL),
                            "alt": key.modifiers.contains(KeyModifiers::ALT),
                            "shift": key.modifiers.contains(KeyModifiers::SHIFT),
                        }))
                        .await;
                }
            }
            Event::Mouse(mouse) => {
                let (event_name, button) = match mouse.kind {
                    crossterm::event::MouseEventKind::Down(btn) => {
                        let b = match btn {
                            crossterm::event::MouseButton::Left => "left",
                            crossterm::event::MouseButton::Right => "right",
                            crossterm::event::MouseButton::Middle => "middle",
                        };
                        ("click", b)
                    }
                    crossterm::event::MouseEventKind::ScrollUp => ("scroll", "up"),
                    crossterm::event::MouseEventKind::ScrollDown => ("scroll", "down"),
                    _ => return Ok(false),
                };
                return self
                    .reduce_and_process(serde_json::json!({
                        "type": "__tela_mouse__",
                        "event": event_name,
                        "column": mouse.column,
                        "row": mouse.row,
                        "button": button,
                    }))
                    .await;
            }
            Event::Resize(w, h) => {
                self.update_terminal_size().await;
                return self
                    .reduce_and_process(serde_json::json!({
                        "type": "__tela_resize__",
                        "columns": w,
                        "rows": h,
                    }))
                    .await;
            }
            _ => {}
        }
        Ok(false)
    }

    pub async fn run(&self) -> Result<()> {
        enable_raw_mode().context("failed to enable raw mode")?;
        let mut stdout = std::io::stdout();
        execute!(stdout, EnterAlternateScreen, EnableMouseCapture)
            .context("failed to enter alternate screen")?;
        let _guard = TerminalGuard;

        let backend = CrosstermBackend::new(stdout);
        let mut terminal = Terminal::new(backend).context("failed to create terminal")?;

        let mut action_rx = self.action_rx.lock().await;
        let mut event_stream = EventStream::new();

        self.update_terminal_size().await;

        let tree = self.view().await?;
        terminal.draw(|frame| {
            crate::renderer::render_element(frame, frame.area(), &tree);
        })?;

        loop {
            let mut should_quit = false;

            tokio::select! {
                event = event_stream.next() => {
                    match event {
                        Some(Ok(evt)) => {
                            should_quit = self.process_event(evt).await?;
                        }
                        None => break,
                        _ => {}
                    }
                }
                action = action_rx.recv() => {
                    if let Some(action) = action {
                        self.handle_internal_action(action).await?;
                        should_quit = self.check_quit().await;
                    }
                }
            }

            if !should_quit {
                loop {
                    tokio::select! {
                        biased;
                        event = event_stream.next() => {
                            match event {
                                Some(Ok(evt)) => {
                                    should_quit = self.process_event(evt).await?;
                                    if should_quit { break; }
                                    continue;
                                }
                                None => { should_quit = true; break; }
                                _ => { continue; }
                            }
                        }
                        action = action_rx.recv() => {
                            if let Some(action) = action {
                                self.handle_internal_action(action).await?;
                                should_quit = self.check_quit().await;
                                if should_quit { break; }
                                continue;
                            }
                        }
                        _ = futures_util::future::ready(()) => { break; }
                    }
                }
            }

            if should_quit {
                break;
            }

            let tree = self.view().await?;
            terminal.draw(|frame| {
                crate::renderer::render_element(frame, frame.area(), &tree);
            })?;
        }

        Ok(())
    }
}

fn js_value_to_json<'js>(
    ctx: &rquickjs::Ctx<'js>,
    val: rquickjs::Value<'js>,
) -> Result<serde_json::Value> {
    if val.is_undefined() || val.is_null() {
        return Ok(serde_json::Value::Null);
    }
    let json_str = ctx
        .json_stringify(val)
        .map_err(|e| anyhow!("JSON.stringify failed: {e}"))?
        .ok_or_else(|| anyhow!("JSON.stringify returned undefined"))?;
    let s = json_str
        .to_string()
        .map_err(|e| anyhow!("string conversion failed: {e}"))?;
    serde_json::from_str(&s).context("failed to parse JSON from JS")
}

struct TerminalGuard;

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        let _ = disable_raw_mode();
        let _ = execute!(
            std::io::stdout(),
            LeaveAlternateScreen,
            DisableMouseCapture
        );
    }
}