Fix indentation

main
Ashelyn Dawn 2 years ago
parent 6acc77e52e
commit aa53c75eed

@ -1,7 +1,7 @@
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
use web_sys::KeyboardEvent;
use web_sys::Element; use web_sys::Element;
use web_sys::KeyboardEvent;
use crate::State; use crate::State;
@ -10,85 +10,92 @@ pub enum Key {
Space, Space,
Backspace, Backspace,
Return, Return,
Ctrl(Box<Key>) Ctrl(Box<Key>),
} }
pub fn parse_key_event(event : &KeyboardEvent, ignore_ctrl : bool) -> Option<Key> { pub fn parse_key_event(event: &KeyboardEvent, ignore_ctrl: bool) -> Option<Key> {
if event.ctrl_key() && !ignore_ctrl { if event.ctrl_key() && !ignore_ctrl {
let base = parse_key_event(event, true)?; let base = parse_key_event(event, true)?;
return Some(Key::Ctrl(Box::new(base))) return Some(Key::Ctrl(Box::new(base)));
} }
let key = event.key(); let key = event.key();
// TODO: ^C // TODO: ^C
match key.as_str() { match key.as_str() {
"Space" => Some(Key::Space), "Space" => Some(Key::Space),
"Backspace" => Some(Key::Backspace), "Backspace" => Some(Key::Backspace),
"Enter" => Some(Key::Return), "Enter" => Some(Key::Return),
_ => { _ => {
if key.len() != 1 { if key.len() != 1 {
None None
} else { } else {
event.prevent_default(); event.prevent_default();
Some(Key::Letter(key.chars().next().unwrap())) Some(Key::Letter(key.chars().next().unwrap()))
}
} }
}
} }
} }
pub fn handle_key_event(state : &mut State, key : Key) -> Option<String> { pub fn handle_key_event(state: &mut State, key: Key) -> Option<String> {
match key { match key {
Key::Return => { Key::Return => {
let input = std::mem::replace(&mut state.input, String::new()); let input = std::mem::replace(&mut state.input, String::new());
state.output.push_back(format!("{} {}", state.prompt, input)); state
if state.output.len() > state.max_rows { .output
state.output.pop_front(); .push_back(format!("{} {}", state.prompt, input));
} if state.output.len() > state.max_rows {
state.output.pop_front();
}
return Some(input); return Some(input);
}, }
Key::Backspace => { Key::Backspace => {
if state.input.len() > 0 { if state.input.len() > 0 {
state.input.remove(state.input.len() - 1); state.input.remove(state.input.len() - 1);
}
},
Key::Space => state.input += " ",
Key::Letter(letter) => {
let mut tmp = [0; 4];
state.input += letter.encode_utf8(&mut tmp)
} }
Key::Ctrl(letter) => }
match letter.as_ref() { Key::Space => state.input += " ",
Key::Letter(letter) => { Key::Letter(letter) => {
if *letter == 'c' { let mut tmp = [0; 4];
let mut input = std::mem::replace(&mut state.input, String::new()); state.input += letter.encode_utf8(&mut tmp)
input += "^C"; }
state.output.push_back(format!("{}", input)); Key::Ctrl(letter) => match letter.as_ref() {
if state.output.len() > state.max_rows { Key::Letter(letter) => {
state.output.pop_front(); if *letter == 'c' {
} let mut input = std::mem::replace(&mut state.input, String::new());
} input += "^C";
} state.output.push_back(format!("{}", input));
_ => () if state.output.len() > state.max_rows {
state.output.pop_front();
} }
}
}
_ => (),
},
}; };
return None return None;
} }
#[wasm_bindgen(inline_js = "const ansi_up = new AnsiUp; export function format_html(text) { return ansi_up.ansi_to_html(text).replace(/(https:[^ )]*)/g, '<a href=\"$1\" target=\"_blank\">$1</a>') }")] #[wasm_bindgen(
inline_js = "const ansi_up = new AnsiUp; export function format_html(text) { return ansi_up.ansi_to_html(text).replace(/(https:[^ )]*)/g, '<a href=\"$1\" target=\"_blank\">$1</a>') }"
)]
extern "C" { extern "C" {
fn format_html(text : String) -> String; fn format_html(text: String) -> String;
} }
pub fn print_state(target: &mut Element, state: &State) {
pub fn print_state(target : &mut Element, state : &State) { let mut output = state
let mut output = state.output.iter().map(|s| (*s).clone()).collect::<Vec<String>>().join("\n"); .output
.iter()
.map(|s| (*s).clone())
.collect::<Vec<String>>()
.join("\n");
if state.output.len() > 0 { if state.output.len() > 0 {
output += "\n"; output += "\n";
} }
if state.prompt.len() > 0 { if state.prompt.len() > 0 {
@ -106,7 +113,7 @@ pub fn print_state(target : &mut Element, state : &State) {
target.set_inner_html(formatted.as_str()); target.set_inner_html(formatted.as_str());
} }
pub fn build_prompt(state : &State) -> String { pub fn build_prompt(state: &State) -> String {
let mut prompt = String::new(); let mut prompt = String::new();
let cwd = state.cwd.replace("/home/ashe", "~"); let cwd = state.cwd.replace("/home/ashe", "~");
@ -123,5 +130,5 @@ pub fn build_prompt(state : &State) -> String {
prompt += "\x1b[2;37m"; prompt += "\x1b[2;37m";
prompt += "$"; prompt += "$";
return prompt return prompt;
} }

@ -5,8 +5,8 @@ use js_sys::Promise;
#[wasm_bindgen] #[wasm_bindgen]
extern "C" { extern "C" {
#[wasm_bindgen(js_namespace = console)] #[wasm_bindgen(js_namespace = console)]
pub fn log(s: &str); pub fn log(s: &str);
} }
#[macro_export] #[macro_export]
@ -18,7 +18,7 @@ macro_rules! console_log {
#[wasm_bindgen(inline_js = "export function _wait(ms) { return new Promise(res => setTimeout(res, ms)) }")] #[wasm_bindgen(inline_js = "export function _wait(ms) { return new Promise(res => setTimeout(res, ms)) }")]
extern "C" { extern "C" {
fn _wait(ms: i32) -> Promise; fn _wait(ms: i32) -> Promise;
} }

@ -21,115 +21,115 @@ use web_sys::Element;
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
pub enum Directory { pub enum Directory {
Home, Home,
Projects Projects
} }
pub struct State { pub struct State {
fs_root: fs::DirEntry, fs_root: fs::DirEntry,
cwd: String, cwd: String,
input : String, input : String,
output : VecDeque<String>, output : VecDeque<String>,
prompt: String, prompt: String,
max_rows: usize, max_rows: usize,
} }
impl State { impl State {
pub fn new() -> Self { pub fn new() -> Self {
State { State {
fs_root: fs::setup_fs(), fs_root: fs::setup_fs(),
cwd: "/home/ashe".to_string(), cwd: "/home/ashe".to_string(),
input : String::new(), input : String::new(),
output : VecDeque::new(), output : VecDeque::new(),
prompt: String::new(), prompt: String::new(),
max_rows: 24, max_rows: 24,
}
} }
}
pub fn print(&mut self, line : String) { pub fn print(&mut self, line : String) {
self.output.push_back(line); self.output.push_back(line);
if self.output.len() > self.max_rows { if self.output.len() > self.max_rows {
self.output.pop_front(); self.output.pop_front();
}
} }
}
} }
fn main() { fn main() {
panic::set_hook(Box::new(console_error_panic_hook::hook)); panic::set_hook(Box::new(console_error_panic_hook::hook));
let window = web_sys::window().expect("should have a window in this context"); let window = web_sys::window().expect("should have a window in this context");
let document = window.document().expect("window should have a document"); let document = window.document().expect("window should have a document");
spawn_local(async { spawn_local(async {
init(document).await; init(document).await;
}); });
} }
async fn init(document : Document) { async fn init(document : Document) {
let mut state = State::new(); let mut state = State::new();
let mut render_target = document let mut render_target = document
.get_element_by_id("target") .get_element_by_id("target")
.expect("should have #target on the page"); .expect("should have #target on the page");
print_welcome(&mut render_target, &mut state).await; print_welcome(&mut render_target, &mut state).await;
let closure = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| { let closure = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| {
let key = io::parse_key_event(&event, false); let key = io::parse_key_event(&event, false);
if key.is_none() { if key.is_none() {
return return
} }
let key = key.unwrap(); let key = key.unwrap();
let command = io::handle_key_event(&mut state, key); let command = io::handle_key_event(&mut state, key);
if let Some(command) = command { if let Some(command) = command {
handle_command(command, &mut state); handle_command(command, &mut state);
} }
state.prompt = io::build_prompt(&state); state.prompt = io::build_prompt(&state);
io::print_state(&mut render_target, &state); io::print_state(&mut render_target, &state);
}) as Box<dyn FnMut(_)>); }) as Box<dyn FnMut(_)>);
document.add_event_listener_with_callback("keydown", closure.as_ref().unchecked_ref()).unwrap(); document.add_event_listener_with_callback("keydown", closure.as_ref().unchecked_ref()).unwrap();
closure.forget(); closure.forget();
} }
pub async fn print_welcome(render_target : &mut Element, state : &mut State) { pub async fn print_welcome(render_target : &mut Element, state : &mut State) {
let intro = include_str!("../res/welcome.txt"); let intro = include_str!("../res/welcome.txt");
let mut lines = intro.split("\n"); let mut lines = intro.split("\n");
let first_line = lines.next().unwrap(); let first_line = lines.next().unwrap();
state.input = String::from_str(first_line).unwrap(); state.input = String::from_str(first_line).unwrap();
io::print_state(render_target, state); io::print_state(render_target, state);
js::wait(3000i32).await.unwrap(); js::wait(3000i32).await.unwrap();
state.output.push_back(String::from_str(first_line).unwrap()); state.output.push_back(String::from_str(first_line).unwrap());
state.input = String::new(); state.input = String::new();
io::print_state(render_target, state); io::print_state(render_target, state);
js::wait(1000i32).await.unwrap(); js::wait(1000i32).await.unwrap();
for line in lines { for line in lines {
js::wait(30i32).await.unwrap(); js::wait(30i32).await.unwrap();
state.output.push_back(String::from_str(line).unwrap()); state.output.push_back(String::from_str(line).unwrap());
if state.output.len() > state.max_rows { if state.output.len() > state.max_rows {
state.output.pop_front(); state.output.pop_front();
}
io::print_state(render_target, state);
} }
io::print_state(render_target, state);
}
js::wait(100i32).await.unwrap(); js::wait(100i32).await.unwrap();
state.prompt = io::build_prompt(&state); state.prompt = io::build_prompt(&state);
io::print_state(render_target, state); io::print_state(render_target, state);
} }
Loading…
Cancel
Save