Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       130       140       150       160       170       180       190       200       210       220       2301mod document;2mod preview;34use std::path::PathBuf;56use eframe::egui::{self, KeyboardShortcut, Modifiers};78use crate::document::{read_document, write_document};910const SHORTCUT_OPEN: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, egui::Key::O);11const SHORTCUT_SAVE: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, egui::Key::S);12const SHORTCUT_NEW: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, egui::Key::N);1314fn main() -> eframe::Result {15    let options = eframe::NativeOptions {16        viewport: egui::ViewportBuilder::default()17            .with_inner_size([1180.0, 760.0])18            .with_min_inner_size([760.0, 480.0]),19        ..Default::default()20    };2122    eframe::run_native(23        "Markdown Editor",24        options,25        Box::new(|_creation_context| Ok(Box::<MarkdownApp>::default())),26    )27}2829struct MarkdownApp {30    text: String,31    saved_text: String,32    path: Option<PathBuf>,33    status: String,34    preview_visible: bool,35}3637impl Default for MarkdownApp {38    fn default() -> Self {39        let text = "# Welcome\n\nWrite Markdown on the left and see a live preview here.\n\n- **Bold** and *italic* text\n- Lists and `inline code`\n\n```rust\nfn main() {\n    println!(\"Hello, Markdown!\");\n}\n```\n".to_owned();40        Self {41            saved_text: text.clone(),42            text,43            path: None,44            status: "Ready".to_owned(),45            preview_visible: true,46        }47    }48}4950impl MarkdownApp {51    fn is_dirty(&self) -> bool {52        self.text != self.saved_text53    }5455    fn open_dialog(&mut self) {56        if let Some(path) = rfd::FileDialog::new()57            .add_filter("Markdown", &["md", "markdown", "mdown"])58            .pick_file()59        {60            self.open_path(path);61        }62    }6364    fn open_path(&mut self, path: PathBuf) {65        match read_document(&path) {66            Ok(contents) => {67                self.text.clone_from(&contents);68                self.saved_text = contents;69                self.status = format!("Opened {}", path.display());70                self.path = Some(path);71            }72            Err(error) => self.status = format!("Could not open file: {error}"),73        }74    }7576    fn save(&mut self) {77        if let Some(path) = self.path.clone() {78            self.save_path(path);79        } else {80            self.save_as();81        }82    }8384    fn save_as(&mut self) {85        if let Some(path) = rfd::FileDialog::new()86            .add_filter("Markdown", &["md", "markdown"])87            .set_file_name("untitled.md")88            .save_file()89        {90            self.save_path(path);91        }92    }9394    fn save_path(&mut self, path: PathBuf) {95        match write_document(&path, &self.text) {96            Ok(()) => {97                self.saved_text.clone_from(&self.text);98                self.status = format!("Saved {}", path.display());99                self.path = Some(path);100            }101            Err(error) => self.status = format!("Could not save file: {error}"),102        }103    }104105    fn new_document(&mut self) {106        self.text.clear();107        self.saved_text.clear();108        self.path = None;109        "New document".clone_into(&mut self.status);110    }111112    fn handle_shortcuts(&mut self, ctx: &egui::Context) {113        if ctx.input_mut(|input| input.consume_shortcut(&SHORTCUT_NEW)) {114            self.new_document();115        }116        if ctx.input_mut(|input| input.consume_shortcut(&SHORTCUT_OPEN)) {117            self.open_dialog();118        }119        if ctx.input_mut(|input| input.consume_shortcut(&SHORTCUT_SAVE)) {120            self.save();121        }122    }123}124125impl eframe::App for MarkdownApp {126    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {127        let ctx = ui.ctx().clone();128        self.handle_shortcuts(&ctx);129130        ui.vertical(|ui| {131            ui.horizontal(|ui| {132                if ui.button("New").on_hover_text("Ctrl/⌘+N").clicked() {133                    self.new_document();134                }135                if ui.button("Open…").on_hover_text("Ctrl/⌘+O").clicked() {136                    self.open_dialog();137                }138                if ui.button("Save").on_hover_text("Ctrl/⌘+S").clicked() {139                    self.save();140                }141                if ui.button("Save as…").clicked() {142                    self.save_as();143                }144                ui.separator();145                ui.toggle_value(&mut self.preview_visible, "Preview");146                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {147                    let words = self.text.split_whitespace().count();148                    ui.label(format!(149                        "{} words · {} characters",150                        words,151                        self.text.chars().count()152                    ));153                });154            });155            ui.separator();156157            ui.columns(if self.preview_visible { 2 } else { 1 }, |columns| {158                columns[0].vertical(|ui| {159                    ui.heading("Editor");160                    ui.separator();161                    egui::ScrollArea::both()162                        .auto_shrink([false, false])163                        .show(ui, |ui| {164                            let editor = egui::TextEdit::multiline(&mut self.text)165                                .font(egui::TextStyle::Monospace)166                                .desired_width(f32::INFINITY)167                                .desired_rows(20)168                                .lock_focus(true);169                            ui.add(editor);170                        });171                });172                if self.preview_visible {173                    columns[1].vertical(|ui| {174                        ui.heading("Preview");175                        ui.separator();176                        egui::ScrollArea::vertical().show(ui, |ui| {177                            preview::render(ui, &self.text);178                        });179                    });180                }181            });182183            ui.separator();184            ui.horizontal(|ui| {185                ui.label(if self.is_dirty() {186                    "● Unsaved changes"187                } else {188                    "Saved"189                });190                ui.separator();191                ui.label(192                    self.path193                        .as_deref()194                        .map_or_else(|| "Untitled".to_owned(), |path| path.display().to_string()),195                );196                ui.separator();197                ui.label(&self.status);198            });199        });200201        if let Some(path) = &self.path {202            let marker = if self.is_dirty() { " •" } else { "" };203            ctx.send_viewport_cmd(egui::ViewportCommand::Title(format!(204                "{}{} — Markdown Editor",205                path.file_name()206                    .and_then(|name| name.to_str())207                    .unwrap_or("Untitled"),208                marker209            )));210        } else {211            let marker = if self.is_dirty() { " •" } else { "" };212            ctx.send_viewport_cmd(egui::ViewportCommand::Title(format!(213                "Untitled{marker} — Markdown Editor"214            )));215        }216    }217}