├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── inline │ ├── Cargo.toml │ ├── package-lock.json │ ├── package.json │ ├── src │ │ ├── lib.rs │ │ └── main.rs │ └── www │ │ ├── .gitignore │ │ ├── index.js │ │ ├── package-lock.json │ │ ├── package.json │ │ ├── static │ │ └── index.html │ │ └── webpack.config.js └── simple │ ├── Cargo.toml │ ├── package-lock.json │ ├── package.json │ ├── src │ ├── lib.rs │ └── main.rs │ └── www │ ├── .gitignore │ ├── index.js │ ├── package-lock.json │ ├── package.json │ ├── static │ └── index.html │ └── webpack.config.js ├── rust-toolchain.toml ├── rustfmt.toml └── src ├── backend.rs ├── event.rs ├── js_terminal.rs └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | node_modules 4 | .vscode -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ratatui-xterm-js" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [workspace] 7 | members = [".", "./examples/*"] 8 | 9 | [lib] 10 | crate-type = ["cdylib", "rlib"] 11 | 12 | [dependencies] 13 | ratatui = "0.29" 14 | tokio = { version = "1.32.0", default-features = false, features = ["sync"] } 15 | crossterm = "0.28.1" 16 | terminput-crossterm = "0.1" 17 | futures = "0.3.28" 18 | terminput = "0.4.2" 19 | 20 | [target.'cfg(target_arch = "wasm32")'.dependencies] 21 | js-sys = "0.3.64" 22 | wasm-bindgen = "0.2.87" 23 | web-sys = "0.3.64" 24 | xterm-js-rs = { git = "https://github.com/aschey/xterm-js-rs", rev = "d97c6ab43c012068514413261024e782ea866fae", features = [ 25 | "xterm-addon-fit", 26 | ] } 27 | 28 | [features] 29 | scrolling-regions = ["ratatui/scrolling-regions"] 30 | 31 | [patch.crates-io] 32 | crossterm = { git = "https://github.com/aschey/crossterm", rev = "3b6db3586eda31a803a67af7bdb1d0937cf26485" } 33 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Austin Schey 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ratatui-xterm-js 2 | 3 | This is a demo/POC of a ratatui backend based on crossterm that can run on both web and native environments with minimal implementation differences. It requires a [fork of crossterm](https://github.com/aschey/crossterm/tree/wasm) that has certain features disabled or stubbed out when building for wasm. I hope to get these changes merged upstream. 4 | 5 | On the web, it runs on [xtermjs](http://xtermjs.org/) using [xterm-js-rs](https://github.com/segeljakt/xterm-js-rs). We can't spawn threads in the browser so we make use of crossterm's async input streams when running natively and [wasm-bindgen-futures](https://crates.io/crates/wasm-bindgen-futures) on the web. 6 | 7 | To run the demos (requires [wasm-pack](https://github.com/rustwasm/wasm-pack)): 8 | 9 | ```bash 10 | cd ./examples/simple 11 | npm install 12 | cd www 13 | npm install 14 | # run wasm build 15 | npm run start 16 | # or run native build 17 | cargo run 18 | ``` 19 | 20 | ```bash 21 | cd ./examples/inline 22 | npm install 23 | cd www 24 | npm install 25 | # run wasm build 26 | npm run start 27 | # or run native build 28 | cargo run 29 | ``` 30 | -------------------------------------------------------------------------------- /examples/inline/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "inline" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | crate-type = ["cdylib", "rlib"] 8 | 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies] 13 | ratatui = "0.29" 14 | ratatui-xterm-js = { path = "../.." } 15 | rand = "0.8.5" 16 | crossterm = { version = "0.28", features = ["event-stream"] } 17 | futures = "0.3.28" 18 | 19 | [target.'cfg(not(target_arch = "wasm32"))'.dependencies] 20 | tokio = { version = "1.32.0", default-features = false, features = [ 21 | "sync", 22 | "macros", 23 | "rt", 24 | "time", 25 | ] } 26 | 27 | [target.'cfg(target_arch = "wasm32")'.dependencies] 28 | # `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size 29 | # compared to the default allocator's ~10K. It is slower than the default 30 | # allocator, however. 31 | # 32 | # Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now. 33 | wee_alloc = { version = "0.4.5", optional = true } 34 | web-sys = { version = "0.3.64", features = ["console", "Window", "Document"] } 35 | wasm-bindgen-futures = "0.4.37" 36 | wasm-bindgen = "0.2.87" 37 | js-sys = "0.3.64" 38 | # The `console_error_panic_hook` crate provides better debugging of panics by 39 | # logging them with `console.error`. This is great for development, but requires 40 | # all the `std::fmt` and `std::panicking` infrastructure, so isn't great for 41 | # code size when deploying. 42 | console_error_panic_hook = { version = "0.1.7" } 43 | tokio = { version = "1.32.0", default-features = false, features = [ 44 | "sync", 45 | "macros", 46 | ] } 47 | getrandom = { version = "0.2.10", features = ["js"] } 48 | 49 | [dev-dependencies] 50 | wasm-bindgen-test = "0.3.12" 51 | -------------------------------------------------------------------------------- /examples/inline/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "inline", 3 | "lockfileVersion": 3, 4 | "requires": true, 5 | "packages": { 6 | "": { 7 | "dependencies": { 8 | "@xterm/addon-fit": "^0.10.0", 9 | "@xterm/xterm": "^5.5.0" 10 | } 11 | }, 12 | "node_modules/@xterm/addon-fit": { 13 | "version": "0.10.0", 14 | "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.10.0.tgz", 15 | "integrity": "sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==", 16 | "license": "MIT", 17 | "peerDependencies": { 18 | "@xterm/xterm": "^5.0.0" 19 | } 20 | }, 21 | "node_modules/@xterm/xterm": { 22 | "version": "5.5.0", 23 | "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz", 24 | "integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==", 25 | "license": "MIT" 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /examples/inline/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "@xterm/addon-fit": "^0.10.0", 4 | "@xterm/xterm": "^5.5.0" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /examples/inline/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::collections::{BTreeMap, VecDeque}; 2 | use std::error::Error; 3 | use std::io; 4 | #[cfg(not(target_arch = "wasm32"))] 5 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; 6 | 7 | #[cfg(not(target_arch = "wasm32"))] 8 | use crossterm::event::EventStream; 9 | use futures::stream::StreamExt; 10 | use rand::distributions::Uniform; 11 | use rand::prelude::Distribution; 12 | use ratatui::Viewport; 13 | use ratatui::prelude::*; 14 | use ratatui::widgets::*; 15 | #[cfg(target_arch = "wasm32")] 16 | use ratatui_xterm_js::EventStream; 17 | #[cfg(target_arch = "wasm32")] 18 | use ratatui_xterm_js::xterm::Theme; 19 | #[cfg(target_arch = "wasm32")] 20 | use ratatui_xterm_js::{TerminalHandle, XtermJsBackend, init_terminal, xterm::TerminalOptions}; 21 | #[cfg(not(target_arch = "wasm32"))] 22 | use tokio::spawn; 23 | use tokio::sync::mpsc; 24 | #[cfg(target_arch = "wasm32")] 25 | use wasm_bindgen::{JsCast, JsError, prelude::wasm_bindgen}; 26 | #[cfg(target_arch = "wasm32")] 27 | use wasm_bindgen_futures::JsFuture; 28 | #[cfg(target_arch = "wasm32")] 29 | use wasm_bindgen_futures::spawn_local as spawn; 30 | #[cfg(all(feature = "wee_alloc", target_arch = "wasm32"))] 31 | #[global_allocator] 32 | static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 33 | 34 | const NUM_DOWNLOADS: usize = 10; 35 | 36 | type DownloadId = usize; 37 | type WorkerId = usize; 38 | 39 | enum Event { 40 | Input(crossterm::event::KeyEvent), 41 | Tick, 42 | Resize, 43 | DownloadUpdate(WorkerId, DownloadId, f64), 44 | DownloadDone(WorkerId, DownloadId), 45 | } 46 | 47 | struct Downloads { 48 | pending: VecDeque, 49 | in_progress: BTreeMap, 50 | } 51 | 52 | impl Downloads { 53 | fn next(&mut self, worker_id: WorkerId) -> Option { 54 | match self.pending.pop_front() { 55 | Some(d) => { 56 | self.in_progress.insert( 57 | worker_id, 58 | DownloadInProgress { 59 | id: d.id, 60 | started_at: now(), 61 | progress: 0.0, 62 | }, 63 | ); 64 | Some(d) 65 | } 66 | None => None, 67 | } 68 | } 69 | } 70 | 71 | struct DownloadInProgress { 72 | id: DownloadId, 73 | started_at: f64, 74 | progress: f64, 75 | } 76 | 77 | struct Download { 78 | id: DownloadId, 79 | size: usize, 80 | } 81 | 82 | struct Worker { 83 | id: WorkerId, 84 | tx: mpsc::Sender, 85 | } 86 | 87 | #[cfg(target_arch = "wasm32")] 88 | #[wasm_bindgen(start)] 89 | pub async fn main() -> Result<(), JsError> { 90 | console_error_panic_hook::set_once(); 91 | let elem = web_sys::window() 92 | .unwrap() 93 | .document() 94 | .unwrap() 95 | .get_element_by_id("terminal") 96 | .unwrap(); 97 | 98 | init_terminal( 99 | TerminalOptions::new() 100 | .with_rows(50) 101 | .with_cursor_blink(true) 102 | .with_cursor_width(10) 103 | .with_font_size(20) 104 | .with_draw_bold_text_in_bright_colors(true) 105 | .with_right_click_selects_word(true) 106 | .with_theme( 107 | Theme::new() 108 | .with_foreground("#98FB98") 109 | .with_background("#000000"), 110 | ), 111 | elem.dyn_into().map_err(|e| JsError::new(&e.node_name()))?, 112 | ); 113 | let handle = TerminalHandle::default(); 114 | 115 | run(handle, XtermJsBackend::new) 116 | .await 117 | .map_err(|e| JsError::new(&e.to_string()))?; 118 | Ok(()) 119 | } 120 | 121 | pub async fn run(out: W, create_backend: F) -> Result<(), Box> 122 | where 123 | W: io::Write, 124 | B: Backend, 125 | F: FnOnce(W) -> B, 126 | { 127 | crossterm::terminal::enable_raw_mode()?; 128 | 129 | let backend = create_backend(out); 130 | let mut terminal = Terminal::with_options( 131 | backend, 132 | ratatui::TerminalOptions { 133 | viewport: Viewport::Inline(8), 134 | }, 135 | ) 136 | .unwrap(); 137 | 138 | let (tx, rx) = mpsc::channel(32); 139 | input_handling(tx.clone()); 140 | let mut workers = workers(tx); 141 | let mut downloads = downloads(); 142 | 143 | for w in &mut workers { 144 | let d = downloads.next(w.id).unwrap(); 145 | w.tx.send(d).await.ok(); 146 | } 147 | 148 | run_app(&mut terminal, workers, downloads, rx) 149 | .await 150 | .unwrap(); 151 | 152 | crossterm::terminal::disable_raw_mode()?; 153 | terminal.clear().unwrap(); 154 | 155 | Ok(()) 156 | } 157 | 158 | fn input_handling(tx: mpsc::Sender) { 159 | spawn(async move { 160 | let mut events = EventStream::default(); 161 | loop { 162 | tokio::select! { 163 | _ = sleep(200) => { 164 | tx.send(Event::Tick).await.ok(); 165 | } 166 | event = events.next() => { 167 | if let Some(Ok(event)) = event { 168 | match event { 169 | crossterm::event::Event::Key(key) => { 170 | tx.send(Event::Input(key)).await.ok(); 171 | } 172 | crossterm::event::Event::Resize(_, _) => { 173 | tx.send(Event::Resize).await.ok(); 174 | } 175 | _ => {} 176 | } 177 | } 178 | 179 | } 180 | } 181 | } 182 | }); 183 | } 184 | 185 | #[cfg(target_arch = "wasm32")] 186 | async fn sleep(ms: i32) { 187 | let fut: JsFuture = js_sys::Promise::new(&mut |resolve, _| { 188 | web_sys::window() 189 | .unwrap() 190 | .set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms) 191 | .unwrap(); 192 | }) 193 | .into(); 194 | fut.await.unwrap(); 195 | } 196 | 197 | #[cfg(not(target_arch = "wasm32"))] 198 | async fn sleep(ms: i32) { 199 | tokio::time::sleep(Duration::from_millis(ms as u64)).await 200 | } 201 | 202 | #[cfg(target_arch = "wasm32")] 203 | fn now() -> f64 { 204 | js_sys::Date::now() 205 | } 206 | 207 | #[cfg(not(target_arch = "wasm32"))] 208 | fn now() -> f64 { 209 | SystemTime::now() 210 | .duration_since(UNIX_EPOCH) 211 | .unwrap() 212 | .as_millis() as f64 213 | } 214 | 215 | fn workers(tx: mpsc::Sender) -> Vec { 216 | (0..4) 217 | .map(|id| { 218 | let (worker_tx, mut worker_rx) = mpsc::channel::(32); 219 | let tx = tx.clone(); 220 | spawn(async move { 221 | while let Some(download) = worker_rx.recv().await { 222 | let mut remaining = download.size; 223 | while remaining > 0 { 224 | let wait = (remaining as u64).min(10); 225 | sleep((wait * 10) as i32).await; 226 | 227 | remaining = remaining.saturating_sub(10); 228 | let progress = (download.size - remaining) * 100 / download.size; 229 | tx.send(Event::DownloadUpdate(id, download.id, progress as f64)) 230 | .await 231 | .ok(); 232 | } 233 | tx.send(Event::DownloadDone(id, download.id)).await.ok(); 234 | } 235 | }); 236 | Worker { id, tx: worker_tx } 237 | }) 238 | .collect() 239 | } 240 | 241 | fn downloads() -> Downloads { 242 | let distribution = Uniform::new(0, 1000); 243 | let mut rng = rand::thread_rng(); 244 | let pending = (0..NUM_DOWNLOADS) 245 | .map(|id| { 246 | let size = distribution.sample(&mut rng); 247 | Download { id, size } 248 | }) 249 | .collect(); 250 | Downloads { 251 | pending, 252 | in_progress: BTreeMap::new(), 253 | } 254 | } 255 | 256 | async fn run_app( 257 | terminal: &mut Terminal, 258 | workers: Vec, 259 | mut downloads: Downloads, 260 | mut rx: mpsc::Receiver, 261 | ) -> Result<(), Box> { 262 | let mut redraw = true; 263 | loop { 264 | if redraw { 265 | terminal.draw(|f| ui(f, &downloads))?; 266 | } 267 | redraw = true; 268 | 269 | match rx.recv().await.unwrap() { 270 | Event::Input(event) => { 271 | if event.code == crossterm::event::KeyCode::Char('q') { 272 | break; 273 | } 274 | } 275 | Event::Resize => { 276 | terminal.autoresize()?; 277 | } 278 | Event::Tick => {} 279 | Event::DownloadUpdate(worker_id, _download_id, progress) => { 280 | let download = downloads.in_progress.get_mut(&worker_id).unwrap(); 281 | download.progress = progress; 282 | redraw = false 283 | } 284 | Event::DownloadDone(worker_id, download_id) => { 285 | let download = downloads.in_progress.remove(&worker_id).unwrap(); 286 | terminal.insert_before(1, |buf| { 287 | Paragraph::new(Line::from(vec![ 288 | Span::from("Finished "), 289 | Span::styled( 290 | format!("download {download_id}"), 291 | Style::default().add_modifier(Modifier::BOLD), 292 | ), 293 | Span::from(format!(" in {}ms", now() - download.started_at)), 294 | ])) 295 | .render(buf.area, buf); 296 | })?; 297 | match downloads.next(worker_id) { 298 | Some(d) => { 299 | workers[worker_id].tx.send(d).await.ok(); 300 | } 301 | None => { 302 | if downloads.in_progress.is_empty() { 303 | terminal.insert_before(1, |buf| { 304 | Paragraph::new("Done !").render(buf.area, buf); 305 | })?; 306 | break; 307 | } 308 | } 309 | }; 310 | } 311 | }; 312 | } 313 | Ok(()) 314 | } 315 | 316 | fn ui(f: &mut Frame, downloads: &Downloads) { 317 | let size = f.area(); 318 | 319 | let block = Block::default() 320 | .title(block::Title::from("Progress")) 321 | .title_alignment(Alignment::Center); 322 | f.render_widget(block, size); 323 | 324 | let chunks = Layout::default() 325 | .constraints(vec![Constraint::Length(2), Constraint::Length(4)]) 326 | .margin(1) 327 | .split(size); 328 | 329 | // total progress 330 | let done = NUM_DOWNLOADS - downloads.pending.len() - downloads.in_progress.len(); 331 | let progress = LineGauge::default() 332 | .filled_style(Style::default().fg(Color::Blue)) 333 | .label(format!("{done}/{NUM_DOWNLOADS}")) 334 | .ratio(done as f64 / NUM_DOWNLOADS as f64); 335 | f.render_widget(progress, chunks[0]); 336 | 337 | let chunks = Layout::default() 338 | .direction(Direction::Horizontal) 339 | .constraints(vec![Constraint::Percentage(20), Constraint::Percentage(80)]) 340 | .split(chunks[1]); 341 | 342 | // in progress downloads 343 | let items: Vec = downloads 344 | .in_progress 345 | .values() 346 | .map(|download| { 347 | ListItem::new(Line::from(vec![ 348 | Span::raw(symbols::DOT), 349 | Span::styled( 350 | format!(" download {:>2}", download.id), 351 | Style::default() 352 | .fg(Color::LightGreen) 353 | .add_modifier(Modifier::BOLD), 354 | ), 355 | Span::raw(format!(" ({}ms)", now() - download.started_at)), 356 | ])) 357 | }) 358 | .collect(); 359 | let list = List::new(items); 360 | f.render_widget(list, chunks[0]); 361 | 362 | for (i, (_, download)) in downloads.in_progress.iter().enumerate() { 363 | let gauge = Gauge::default() 364 | .gauge_style(Style::default().fg(Color::Yellow)) 365 | .ratio(download.progress / 100.0); 366 | if chunks[1].top().saturating_add(i as u16) > size.bottom() { 367 | continue; 368 | } 369 | f.render_widget( 370 | gauge, 371 | Rect { 372 | x: chunks[1].left(), 373 | y: chunks[1].top().saturating_add(i as u16), 374 | width: chunks[1].width, 375 | height: 1, 376 | }, 377 | ); 378 | } 379 | } 380 | -------------------------------------------------------------------------------- /examples/inline/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::io; 3 | 4 | #[tokio::main(flavor = "current_thread")] 5 | async fn main() -> Result<(), Box> { 6 | let stdout = io::stdout(); 7 | inline::run(stdout, ratatui::backend::CrosstermBackend::new).await 8 | } 9 | -------------------------------------------------------------------------------- /examples/inline/www/.gitignore: -------------------------------------------------------------------------------- 1 | pkg/* -------------------------------------------------------------------------------- /examples/inline/www/index.js: -------------------------------------------------------------------------------- 1 | import "@xterm/xterm/css/xterm.css"; 2 | import "@xterm/xterm/lib/xterm.js"; 3 | 4 | import("../pkg/index.js").catch(console.error); 5 | -------------------------------------------------------------------------------- /examples/inline/www/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "You ", 3 | "name": "rust-webpack-template", 4 | "version": "0.1.0", 5 | "scripts": { 6 | "build": "rimraf dist pkg && webpack", 7 | "start": "rimraf dist pkg && webpack-dev-server", 8 | "test": "cargo test && wasm-pack test --headless" 9 | }, 10 | "devDependencies": { 11 | "@wasm-tool/wasm-pack-plugin": "^1.1.0", 12 | "copy-webpack-plugin": "^13.0.0", 13 | "css-loader": "^7.1.2", 14 | "file-loader": "^6.2.0", 15 | "rimraf": "^3.0.0", 16 | "style-loader": "^4.0.0", 17 | "webpack": "^5.99.8", 18 | "webpack-cli": "^6.0.1", 19 | "webpack-dev-server": "^5.2.1" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /examples/inline/www/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Hello wasm-pack! 6 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /examples/inline/www/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("node:path"); 2 | const CopyWebpackPlugin = require("copy-webpack-plugin"); 3 | const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin"); 4 | 5 | const dist = path.resolve(__dirname, "dist"); 6 | 7 | module.exports = { 8 | mode: "production", 9 | entry: { 10 | index: "./index.js", 11 | }, 12 | output: { 13 | path: dist, 14 | filename: "[name].js", 15 | }, 16 | devServer: { 17 | static: { 18 | directory: dist, 19 | }, 20 | }, 21 | performance: { 22 | hints: "warning", 23 | maxAssetSize: 500 * 1024, 24 | maxEntrypointSize: 500 * 1024, 25 | assetFilter: (assetFilename) => { 26 | return !/\.wasm$/.test(assetFilename); 27 | }, 28 | }, 29 | plugins: [ 30 | new CopyWebpackPlugin({ 31 | patterns: ["static/index.html"], 32 | }), 33 | 34 | new WasmPackPlugin({ 35 | crateDirectory: path.resolve(__dirname, ".."), 36 | }), 37 | ], 38 | module: { 39 | rules: [ 40 | { 41 | test: /\.css$/i, 42 | use: ["style-loader", "css-loader"], 43 | }, 44 | { 45 | test: /\.wasm$/, 46 | type: "webassembly/async", 47 | }, 48 | ], 49 | }, 50 | experiments: { 51 | asyncWebAssembly: true, 52 | }, 53 | }; 54 | -------------------------------------------------------------------------------- /examples/simple/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "simple" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | crate-type = ["cdylib", "rlib"] 8 | 9 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 10 | 11 | [dependencies] 12 | ratatui = "0.29" 13 | ratatui-xterm-js = { path = "../.." } 14 | crossterm = { version = "0.28.1", features = ["event-stream"] } 15 | futures = "0.3.28" 16 | 17 | [target.'cfg(not(target_arch = "wasm32"))'.dependencies] 18 | tokio = { version = "1.32.0", default-features = false, features = [ 19 | "sync", 20 | "macros", 21 | "rt", 22 | "time", 23 | ] } 24 | 25 | [target.'cfg(target_arch = "wasm32")'.dependencies] 26 | # `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size 27 | # compared to the default allocator's ~10K. It is slower than the default 28 | # allocator, however. 29 | # 30 | # Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now. 31 | wee_alloc = { version = "0.4.5", optional = true } 32 | web-sys = { version = "0.3.64", features = ["console", "Window", "Document"] } 33 | wasm-bindgen-futures = "0.4.37" 34 | wasm-bindgen = "0.2.87" 35 | js-sys = "0.3.64" 36 | # The `console_error_panic_hook` crate provides better debugging of panics by 37 | # logging them with `console.error`. This is great for development, but requires 38 | # all the `std::fmt` and `std::panicking` infrastructure, so isn't great for 39 | # code size when deploying. 40 | console_error_panic_hook = { version = "0.1.7" } 41 | tokio = { version = "1.32.0", default-features = false, features = [ 42 | "sync", 43 | "macros", 44 | ] } 45 | 46 | [dev-dependencies] 47 | wasm-bindgen-test = "0.3.12" 48 | -------------------------------------------------------------------------------- /examples/simple/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "simple", 3 | "lockfileVersion": 3, 4 | "requires": true, 5 | "packages": { 6 | "": { 7 | "dependencies": { 8 | "@xterm/addon-fit": "^0.10.0", 9 | "@xterm/xterm": "^5.5.0" 10 | } 11 | }, 12 | "node_modules/@xterm/addon-fit": { 13 | "version": "0.10.0", 14 | "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.10.0.tgz", 15 | "integrity": "sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==", 16 | "license": "MIT", 17 | "peerDependencies": { 18 | "@xterm/xterm": "^5.0.0" 19 | } 20 | }, 21 | "node_modules/@xterm/xterm": { 22 | "version": "5.5.0", 23 | "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz", 24 | "integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==", 25 | "license": "MIT" 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /examples/simple/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "@xterm/addon-fit": "^0.10.0", 4 | "@xterm/xterm": "^5.5.0" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /examples/simple/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::io; 3 | 4 | #[cfg(not(target_arch = "wasm32"))] 5 | use crossterm::event::EventStream; 6 | use crossterm::event::{DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind}; 7 | use crossterm::execute; 8 | use crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen}; 9 | use futures::StreamExt; 10 | use ratatui::prelude::*; 11 | use ratatui::widgets::*; 12 | #[cfg(target_arch = "wasm32")] 13 | use ratatui_xterm_js::EventStream; 14 | #[cfg(target_arch = "wasm32")] 15 | use ratatui_xterm_js::xterm::Theme; 16 | #[cfg(target_arch = "wasm32")] 17 | use ratatui_xterm_js::{TerminalHandle, XtermJsBackend, init_terminal}; 18 | #[cfg(target_arch = "wasm32")] 19 | use wasm_bindgen::{JsCast, JsValue, prelude::wasm_bindgen}; 20 | 21 | #[cfg(all(feature = "wee_alloc", target_arch = "wasm32"))] 22 | #[global_allocator] 23 | static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 24 | 25 | struct App<'a> { 26 | pub titles: Vec<&'a str>, 27 | pub index: usize, 28 | } 29 | 30 | impl<'a> App<'a> { 31 | fn new() -> App<'a> { 32 | App { 33 | titles: vec!["Tab0", "Tab1", "Tab2", "Tab3"], 34 | index: 0, 35 | } 36 | } 37 | 38 | pub fn next(&mut self) { 39 | self.index = (self.index + 1) % self.titles.len(); 40 | } 41 | 42 | pub fn previous(&mut self) { 43 | if self.index > 0 { 44 | self.index -= 1; 45 | } else { 46 | self.index = self.titles.len() - 1; 47 | } 48 | } 49 | } 50 | 51 | #[cfg(target_arch = "wasm32")] 52 | #[wasm_bindgen(start)] 53 | pub async fn main() -> Result<(), JsValue> { 54 | console_error_panic_hook::set_once(); 55 | let elem = web_sys::window() 56 | .unwrap() 57 | .document() 58 | .unwrap() 59 | .get_element_by_id("terminal") 60 | .unwrap(); 61 | 62 | init_terminal( 63 | ratatui_xterm_js::xterm::TerminalOptions::new() 64 | .with_rows(50) 65 | .with_cursor_blink(true) 66 | .with_cursor_width(10) 67 | .with_font_size(20) 68 | .with_draw_bold_text_in_bright_colors(true) 69 | .with_right_click_selects_word(true) 70 | .with_theme( 71 | Theme::new() 72 | .with_foreground("#98FB98") 73 | .with_background("#000000"), 74 | ), 75 | elem.dyn_into()?, 76 | ); 77 | 78 | let handle = TerminalHandle::default(); 79 | run(handle, XtermJsBackend::new).await.unwrap(); 80 | Ok(()) 81 | } 82 | 83 | pub async fn run(mut out: W, create_backend: F) -> Result<(), Box> 84 | where 85 | W: io::Write, 86 | B: Backend + io::Write, 87 | F: FnOnce(W) -> B, 88 | { 89 | crossterm::terminal::enable_raw_mode().unwrap(); 90 | 91 | execute!(out, EnterAlternateScreen, EnableMouseCapture).unwrap(); 92 | let backend = create_backend(out); 93 | let mut terminal = Terminal::new(backend).unwrap(); 94 | 95 | let app = App::new(); 96 | 97 | run_app(&mut terminal, app).await.unwrap(); 98 | crossterm::terminal::disable_raw_mode().unwrap(); 99 | execute!( 100 | terminal.backend_mut(), 101 | LeaveAlternateScreen, 102 | DisableMouseCapture 103 | ) 104 | .unwrap(); 105 | terminal.show_cursor().unwrap(); 106 | Ok(()) 107 | } 108 | 109 | async fn run_app(terminal: &mut Terminal, mut app: App<'_>) -> io::Result<()> { 110 | let mut events = EventStream::default(); 111 | loop { 112 | terminal.draw(|f| ui(f, &app))?; 113 | if let Some(Ok(event)) = events.next().await { 114 | if let Event::Key(key) = event { 115 | if key.kind == KeyEventKind::Press { 116 | match key.code { 117 | KeyCode::Char('q') => return Ok(()), 118 | KeyCode::Right => app.next(), 119 | KeyCode::Left => app.previous(), 120 | _ => {} 121 | } 122 | } 123 | } 124 | } else { 125 | return Ok(()); 126 | } 127 | } 128 | } 129 | 130 | fn ui(f: &mut Frame, app: &App) { 131 | let size = f.area(); 132 | let chunks = Layout::default() 133 | .direction(Direction::Vertical) 134 | .constraints([Constraint::Length(3), Constraint::Min(0)].as_ref()) 135 | .split(size); 136 | 137 | let block = Block::default(); 138 | f.render_widget(block, size); 139 | let titles = app.titles.iter().map(|t| { 140 | let (first, rest) = t.split_at(1); 141 | Line::from(vec![first.yellow(), rest.green()]) 142 | }); 143 | let tabs = Tabs::new(titles) 144 | .block(Block::default().borders(Borders::ALL).title("Tabs")) 145 | .select(app.index) 146 | .style(Style::default().fg(Color::Cyan)) 147 | .highlight_style( 148 | Style::default() 149 | .add_modifier(Modifier::BOLD) 150 | .bg(Color::Black), 151 | ); 152 | f.render_widget(tabs, chunks[0]); 153 | let inner = match app.index { 154 | 0 => Block::default().title("Inner 0").borders(Borders::ALL), 155 | 1 => Block::default().title("Inner 1").borders(Borders::ALL), 156 | 2 => Block::default().title("Inner 2").borders(Borders::ALL), 157 | 3 => Block::default().title("Inner 3").borders(Borders::ALL), 158 | _ => unreachable!(), 159 | }; 160 | f.render_widget(inner, chunks[1]); 161 | } 162 | -------------------------------------------------------------------------------- /examples/simple/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::io; 3 | 4 | #[tokio::main(flavor = "current_thread")] 5 | async fn main() -> Result<(), Box> { 6 | let stdout = io::stdout(); 7 | simple::run(stdout, ratatui::backend::CrosstermBackend::new).await 8 | } 9 | -------------------------------------------------------------------------------- /examples/simple/www/.gitignore: -------------------------------------------------------------------------------- 1 | pkg/* -------------------------------------------------------------------------------- /examples/simple/www/index.js: -------------------------------------------------------------------------------- 1 | import "@xterm/xterm/css/xterm.css"; 2 | import "@xterm/xterm/lib/xterm.js"; 3 | 4 | import("../pkg/index.js").catch(console.error); 5 | -------------------------------------------------------------------------------- /examples/simple/www/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "You ", 3 | "name": "rust-webpack-template", 4 | "version": "0.1.0", 5 | "scripts": { 6 | "build": "rimraf dist pkg && webpack", 7 | "start": "rimraf dist pkg && webpack-dev-server", 8 | "test": "cargo test && wasm-pack test --headless" 9 | }, 10 | "devDependencies": { 11 | "@wasm-tool/wasm-pack-plugin": "^1.1.0", 12 | "copy-webpack-plugin": "^13.0.0", 13 | "css-loader": "^7.1.2", 14 | "file-loader": "^6.2.0", 15 | "rimraf": "^3.0.0", 16 | "style-loader": "^4.0.0", 17 | "webpack": "^5.99.8", 18 | "webpack-cli": "^6.0.1", 19 | "webpack-dev-server": "^5.2.1" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /examples/simple/www/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Hello wasm-pack! 6 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /examples/simple/www/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("node:path"); 2 | const CopyWebpackPlugin = require("copy-webpack-plugin"); 3 | const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin"); 4 | 5 | const dist = path.resolve(__dirname, "dist"); 6 | 7 | module.exports = { 8 | mode: "production", 9 | entry: { 10 | index: "./index.js", 11 | }, 12 | output: { 13 | path: dist, 14 | filename: "[name].js", 15 | }, 16 | devServer: { 17 | static: { 18 | directory: dist, 19 | }, 20 | }, 21 | performance: { 22 | hints: "warning", 23 | maxAssetSize: 500 * 1024, 24 | maxEntrypointSize: 500 * 1024, 25 | assetFilter: (assetFilename) => { 26 | return !/\.wasm$/.test(assetFilename); 27 | }, 28 | }, 29 | plugins: [ 30 | new CopyWebpackPlugin({ 31 | patterns: ["static/index.html"], 32 | }), 33 | 34 | new WasmPackPlugin({ 35 | crateDirectory: path.resolve(__dirname, ".."), 36 | }), 37 | ], 38 | module: { 39 | rules: [ 40 | { 41 | test: /\.css$/i, 42 | use: ["style-loader", "css-loader"], 43 | }, 44 | { 45 | test: /\.wasm$/, 46 | type: "webassembly/async", 47 | }, 48 | ], 49 | }, 50 | experiments: { 51 | asyncWebAssembly: true, 52 | }, 53 | }; 54 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.85.0" 3 | components = ["rustfmt", "clippy"] 4 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # configuration for https://rust-lang.github.io/rustfmt/ 2 | newline_style = "Unix" 3 | use_field_init_shorthand = true 4 | unstable_features = true 5 | style_edition = "2024" 6 | comment_width = 100 7 | error_on_line_overflow = true 8 | error_on_unformatted = false 9 | format_code_in_doc_comments = true 10 | format_macro_bodies = true 11 | format_macro_matchers = true 12 | format_strings = true 13 | imports_granularity = "Module" 14 | group_imports = "StdExternalCrate" 15 | normalize_doc_attributes = true 16 | wrap_comments = true 17 | -------------------------------------------------------------------------------- /src/backend.rs: -------------------------------------------------------------------------------- 1 | //! This module provides the `CrosstermBackend` implementation for the `Backend` trait. 2 | //! It uses the `crossterm` crate to interact with the terminal. 3 | //! 4 | //! 5 | //! [`Backend`]: trait.Backend.html 6 | //! [`CrosstermBackend`]: struct.CrosstermBackend.html 7 | 8 | use std::io::{self, Write}; 9 | 10 | use ratatui::backend::{Backend, ClearType, WindowSize}; 11 | use ratatui::buffer::Cell; 12 | use ratatui::layout::{Position, Size}; 13 | 14 | use crate::js_terminal::{TerminalHandle, cursor_position}; 15 | use crate::window_size; 16 | 17 | /// A backend implementation using the `crossterm` crate. 18 | /// 19 | /// The `CrosstermBackend` struct is a wrapper around a type implementing `Write`, which 20 | /// is used to send commands to the terminal. It provides methods for drawing content, 21 | /// manipulating the cursor, and clearing the terminal screen. 22 | /// 23 | /// # Example 24 | /// 25 | /// ```rust 26 | /// use ratatui::backend::{Backend, CrosstermBackend}; 27 | /// 28 | /// # fn main() -> Result<(), Box> { 29 | /// let buffer = std::io::stdout(); 30 | /// let mut backend = CrosstermBackend::new(buffer); 31 | /// backend.clear()?; 32 | /// # Ok(()) 33 | /// # } 34 | /// ``` 35 | #[derive(Default)] 36 | pub struct XtermJsBackend { 37 | inner: ratatui::backend::CrosstermBackend, 38 | } 39 | 40 | impl XtermJsBackend { 41 | /// Creates a new `CrosstermBackend` with the given buffer. 42 | pub fn new(handle: TerminalHandle) -> Self { 43 | Self { 44 | inner: ratatui::backend::CrosstermBackend::new(handle), 45 | } 46 | } 47 | } 48 | 49 | impl Write for XtermJsBackend { 50 | /// Writes a buffer of bytes to the underlying buffer. 51 | fn write(&mut self, buf: &[u8]) -> io::Result { 52 | self.inner.write(buf) 53 | } 54 | 55 | /// Flushes the underlying buffer. 56 | fn flush(&mut self) -> io::Result<()> { 57 | io::Write::flush(&mut self.inner) 58 | } 59 | } 60 | 61 | impl Backend for XtermJsBackend { 62 | fn draw<'a, I>(&mut self, content: I) -> io::Result<()> 63 | where 64 | I: Iterator, 65 | { 66 | self.inner.draw(content) 67 | } 68 | 69 | fn hide_cursor(&mut self) -> io::Result<()> { 70 | self.inner.hide_cursor() 71 | } 72 | 73 | fn show_cursor(&mut self) -> io::Result<()> { 74 | self.inner.show_cursor() 75 | } 76 | 77 | fn get_cursor_position(&mut self) -> io::Result { 78 | let (x, y) = cursor_position()?; 79 | Ok(Position::new(x, y)) 80 | } 81 | 82 | fn set_cursor_position>(&mut self, position: P) -> io::Result<()> { 83 | self.inner.set_cursor_position(position) 84 | } 85 | 86 | fn clear(&mut self) -> io::Result<()> { 87 | self.inner.clear() 88 | } 89 | 90 | fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> { 91 | self.inner.clear_region(clear_type) 92 | } 93 | 94 | fn append_lines(&mut self, n: u16) -> io::Result<()> { 95 | self.inner.append_lines(n) 96 | } 97 | 98 | fn size(&self) -> io::Result { 99 | let (width, height) = crate::js_terminal::size()?; 100 | Ok(Size::new(width, height)) 101 | } 102 | 103 | fn flush(&mut self) -> io::Result<()> { 104 | io::Write::flush(&mut self.inner) 105 | } 106 | 107 | #[cfg(feature = "scrolling-regions")] 108 | fn scroll_region_up(&mut self, region: std::ops::Range, amount: u16) -> io::Result<()> { 109 | self.inner.scroll_region_up(region, amount) 110 | } 111 | 112 | #[cfg(feature = "scrolling-regions")] 113 | fn scroll_region_down(&mut self, region: std::ops::Range, amount: u16) -> io::Result<()> { 114 | self.inner.scroll_region_down(region, amount) 115 | } 116 | 117 | fn window_size(&mut self) -> io::Result { 118 | let crossterm::terminal::WindowSize { 119 | columns, 120 | rows, 121 | width, 122 | height, 123 | } = window_size()?; 124 | Ok(WindowSize { 125 | columns_rows: Size { 126 | width: columns, 127 | height: rows, 128 | }, 129 | pixels: Size { width, height }, 130 | }) 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/event.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::task::{Poll, ready}; 3 | 4 | use futures::Stream; 5 | use terminput::Event; 6 | use terminput_crossterm::to_crossterm; 7 | 8 | use crate::poll_next_event; 9 | 10 | #[derive(Default)] 11 | pub struct EventStream {} 12 | 13 | impl EventStream { 14 | pub fn new() -> Self { 15 | Self {} 16 | } 17 | } 18 | 19 | impl Stream for EventStream { 20 | type Item = io::Result; 21 | 22 | fn poll_next( 23 | self: std::pin::Pin<&mut Self>, 24 | cx: &mut std::task::Context<'_>, 25 | ) -> std::task::Poll> { 26 | loop { 27 | if let Some(event) = ready!(poll_next_event(cx)) { 28 | match Event::parse_from(event.as_bytes()) { 29 | Ok(Some(e)) => { 30 | if let Ok(e) = to_crossterm(e) { 31 | return Poll::Ready(Some(Ok(e))); 32 | } 33 | } 34 | Err(e) => { 35 | return Poll::Ready(Some(Err(e))); 36 | } 37 | _ => { 38 | continue; 39 | } 40 | } 41 | } else { 42 | return Poll::Pending; 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/js_terminal.rs: -------------------------------------------------------------------------------- 1 | use std::cell::{OnceCell, RefCell}; 2 | use std::io; 3 | use std::sync::{Mutex, OnceLock}; 4 | use std::task::{Context, Poll}; 5 | 6 | use crossterm::terminal::WindowSize; 7 | use futures::StreamExt; 8 | use futures::channel::mpsc; 9 | use wasm_bindgen::JsCast; 10 | use wasm_bindgen::prelude::Closure; 11 | use web_sys::HtmlElement; 12 | use xterm_js_rs::addons::fit::FitAddon; 13 | 14 | thread_local! { 15 | static TERMINAL: OnceCell = const { OnceCell::new() }; 16 | } 17 | 18 | static DATA_CHANNEL: OnceLock>> = OnceLock::new(); 19 | 20 | pub(crate) fn with_terminal(f: F) -> T 21 | where 22 | F: FnOnce(&xterm_js_rs::Terminal) -> T, 23 | { 24 | TERMINAL.with(|t| f(t.get().unwrap())) 25 | } 26 | 27 | pub fn init_terminal(options: &xterm_js_rs::TerminalOptions, parent: HtmlElement) { 28 | TERMINAL.with(|t| { 29 | let (mut tx, rx) = mpsc::channel(32); 30 | let mut tx_ = tx.clone(); 31 | let terminal = xterm_js_rs::Terminal::new(options); 32 | 33 | let callback = Closure::wrap(Box::new(move |e: xterm_js_rs::Event| { 34 | tx_.try_send(e.as_string().unwrap()).ok(); 35 | }) as Box); 36 | terminal.on_data(callback.as_ref().unchecked_ref()); 37 | callback.forget(); 38 | 39 | let callback = Closure::wrap(Box::new(move |e: xterm_js_rs::Event| { 40 | tx.try_send(e.as_string().unwrap()).ok(); 41 | }) as Box); 42 | terminal.on_binary(callback.as_ref().unchecked_ref()); 43 | callback.forget(); 44 | 45 | DATA_CHANNEL.set(Mutex::new(rx)).unwrap(); 46 | 47 | let addon = FitAddon::new(); 48 | terminal.load_addon(addon.clone().dyn_into::().unwrap().into()); 49 | addon.fit(); 50 | 51 | terminal.open(parent); 52 | terminal.focus(); 53 | if t.set(terminal).is_err() { 54 | panic!(); 55 | } 56 | }); 57 | } 58 | 59 | pub(crate) fn poll_next_event(cx: &mut Context<'_>) -> Poll> { 60 | DATA_CHANNEL 61 | .get() 62 | .unwrap() 63 | .lock() 64 | .unwrap() 65 | .poll_next_unpin(cx) 66 | } 67 | 68 | pub fn window_size() -> io::Result { 69 | Ok(with_terminal(|t| WindowSize { 70 | rows: t.get_rows() as u16, 71 | columns: t.get_cols() as u16, 72 | width: t.get_element().client_width() as u16, 73 | height: t.get_element().client_height() as u16, 74 | })) 75 | } 76 | 77 | pub(crate) fn size() -> io::Result<(u16, u16)> { 78 | window_size().map(|s| (s.columns, s.rows)) 79 | } 80 | 81 | pub fn cursor_position() -> io::Result<(u16, u16)> { 82 | Ok(with_terminal(|t| { 83 | let active = t.get_buffer().get_active(); 84 | (active.get_cursor_x() as u16, active.get_cursor_y() as u16) 85 | })) 86 | } 87 | 88 | #[derive(Default)] 89 | pub struct TerminalHandle { 90 | buffer: RefCell>, 91 | } 92 | 93 | impl io::Write for TerminalHandle { 94 | fn write(&mut self, buf: &[u8]) -> io::Result { 95 | self.buffer.borrow_mut().write(buf) 96 | } 97 | 98 | fn flush(&mut self) -> io::Result<()> { 99 | let s = String::from_utf8(self.buffer.replace(Vec::new())) 100 | .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; 101 | with_terminal(|t| t.write(&s)); 102 | Ok(()) 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_arch = "wasm32")] 2 | pub use backend::XtermJsBackend; 3 | #[cfg(target_arch = "wasm32")] 4 | pub use event::EventStream; 5 | #[cfg(target_arch = "wasm32")] 6 | pub use js_terminal::*; 7 | #[cfg(target_arch = "wasm32")] 8 | pub use xterm_js_rs as xterm; 9 | 10 | #[cfg(target_arch = "wasm32")] 11 | mod backend; 12 | #[cfg(target_arch = "wasm32")] 13 | mod event; 14 | #[cfg(target_arch = "wasm32")] 15 | mod js_terminal; 16 | --------------------------------------------------------------------------------