state.rs 2.09 KB
use mogwai::prelude::*;
use wasm_bindgen::JsValue;

pub(super) struct MarkdownState {
               editor:       HtmlElement,
               display:      HtmlElement,
    pub(super) show_edit:    bool,
    pub(super) show_patches: bool,
}

impl MarkdownState {
    pub(super) fn new(dom: Dom) -> Result<Self, JsValue> {
        let (editor, display) = match dom.inner_read() {
            Either::Left(dom_js) => {
                let node = &dom_js.to_owned().dyn_into::<Node>()?;
                ( node . first_child().unwrap()
                       . first_child().unwrap()
                       . dyn_into::<HtmlElement>()?
                , node . child_nodes().get(1).unwrap()
                       . child_nodes().get(1).unwrap()
                       . dyn_into::<HtmlElement>()? )
            },
            _ => Err(JsValue::UNDEFINED)?,
        };
        let show_edit = false;
        let show_patches = false;

        Ok(Self { editor, display, show_edit, show_patches })
    }

    pub(super) fn get_md(&self) -> String {
        self.editor.inner_text()
    }

    pub(super) fn set_md(&self, md :Option<&str>) {
        self.editor.set_text_content(md)
    }

    pub(super) fn update(&self) {
        use pulldown_cmark::{Parser, Options, html};

        let mut html_out = String::new();
        let md = self.get_md();
        let parser = Parser::new_ext(&md, Options::all());

        html::push_html(&mut html_out, parser);
        self.display.set_inner_html(&html_out)
    }

    pub(super) fn toggle_show_edit(&mut self) {
        self.show_edit = ! self.show_edit;
    }

    #[allow(dead_code)]
    pub(super) fn set_show_edit(&mut self) {
        self.show_edit = true;
    }

    #[allow(dead_code)]
    pub(super) fn reset_show_edit(&mut self) {
        self.show_edit = false;
    }

    pub(super) fn toggle_show_patches(&mut self) {
        self.show_patches = ! self.show_patches;
    }

    #[allow(dead_code)]
    pub(super) fn set_show_patches(&mut self) {
        self.show_patches = true;
    }

    pub(super) fn reset_show_patches(&mut self) {
        self.show_patches = false;
    }
}