lib.rs 7.74 KB
mod data;

use artshop_common::types::MarkdownJson;
use data::icons::*;
use js_sys::JsString;
use log::Level;
use mogwai::prelude::*;
use web_sys::{RequestInit, RequestMode, Request, Response, MouseEvent};
use std::panic;
use wasm_bindgen::prelude::*;

#[derive(Clone)]
enum AppLogic {
    Update,
    Toggle,
    Store,
}

fn md_to_html(source: &str) -> String {
    use pulldown_cmark::{Parser, Options, html};

    let parser = Parser::new_ext(source, Options::all());
    let mut html_output = String::new();
    html::push_html(&mut html_output, parser);

    html_output
}

async fn md_from_db(patch :Option<i32>) -> MarkdownJson {
    let window = web_sys::window().unwrap();
    let mut opts = RequestInit::new();
    opts.method("GET").mode(RequestMode::Cors);

    let api_uri = match patch {
        Some(i) => format!("/api/v0/markdowns/md-example?patch={}", i),
        None    => String::from("/api/v0/markdowns/md-example"),
    };

    let request = Request::new_with_str_and_init(&api_uri, &opts).unwrap();
    request.headers().set("Accept", "application/json").unwrap();

    let response = JsFuture::from(window.fetch_with_request(&request))
                 . await.unwrap()
                 . dyn_into::<Response>().unwrap();
    let data = String::from( JsFuture::from(response.text().unwrap())
                           . await.unwrap()
                           . dyn_into::<JsString>().unwrap()
                           );
    let data :MarkdownJson = serde_json::from_str(data.as_str()).unwrap();

    data
}

async fn md_to_db(md :&MarkdownJson) {
    let encoded = serde_json::to_string(&md).unwrap();

    let window = web_sys::window().unwrap();
    let mut opts = RequestInit::new();
    opts . method("PUT")
         . mode(RequestMode::Cors)
         . body(Some(&encoded.into()));

    let url_str = format!("/api/v0/markdowns/{}", md.name);
    let request = Request::new_with_str_and_init(url_str.as_str(), &opts)
                . unwrap();
    request.headers().set("Content-Type", "application/json").unwrap();

    let _response = JsFuture::from(window.fetch_with_request(&request))
                  . await.unwrap()
                  . dyn_into::<Response>().unwrap();

    /* do something with the response here.... */
}

async fn editor_logic( mut rx_logic: broadcast::Receiver<AppLogic>
                     , tx_view: broadcast::Sender<String>
                     , mut rx_dom: broadcast::Receiver<Dom> )
{
    let dom = rx_dom.next().await.unwrap();
    let mut show_edit = false;
    let mut md = md_from_db(Some(2)).await;

    let container = match dom.inner_read() {
            Either::Left(dom_js) =>
                Some( ( dom_js
                      . to_owned()
                      . dyn_into::<Node>().unwrap()
                      . first_child().unwrap()
                      . first_child().unwrap()
                      . dyn_into::<HtmlElement>().unwrap()
                      , dom_js
                      . to_owned()
                      . dyn_into::<Node>().unwrap()
                      . child_nodes().get(1).unwrap()
                      . child_nodes().get(1).unwrap()
                      . dyn_into::<HtmlElement>().unwrap() )),
            _ => None,
    };

    let cont_ref = container.as_ref();

    let get_md = move || {
        match cont_ref {
            Some((md_cont, _)) => md_cont.inner_text(),
            None => String::from(""),
        }
    };

    let set_md = move |md :&str| {
        match cont_ref {
            Some((md_cont, _)) => md_cont.set_text_content(Some(md)),
            None => (),
        }
    };

    let update = move || {
        match cont_ref {
            Some((md_cont, view_cont)) =>
                view_cont.set_inner_html(
                    md_to_html(md_cont.inner_text().as_str()).as_str() ),
            None => (),
        }
    };

    set_md(md.content.as_str());
    update();

    /* play with katex ==== */
    let opts = katex::Opts::builder()
             . output_type(katex::opts::OutputType::Mathml)
             . build().unwrap();
    let formula1 = katex::render_with_opts("E = mc^2", &opts).unwrap();
    let formula2 = katex::render_with_opts("e^{i*\\pi} +1 = 0", &opts).unwrap();

    if let Either::Left(dom_js) = dom.inner_read() {
        dom_js . to_owned()
            . dyn_into::<Node>().unwrap()
            . child_nodes().get(1).unwrap()
            . child_nodes().get(2).unwrap()
            . dyn_into::<HtmlElement>().unwrap()
            . set_inner_html(formula1.as_str())
    };

    if let Either::Left(dom_js) = dom.inner_read() {
        dom_js . to_owned()
            . dyn_into::<Node>().unwrap()
            . child_nodes().get(1).unwrap()
            . child_nodes().get(3).unwrap()
            . dyn_into::<HtmlElement>().unwrap()
            . set_inner_html(formula2.as_str())
    };
    /* =========== */

    while let Some(msg) = rx_logic.next().await {
        match msg {
            AppLogic::Store => {
                md.content = get_md();
                md_to_db(&md).await;
            },
            AppLogic::Update => update(),
            AppLogic::Toggle => {
                show_edit = ! show_edit;
                match show_edit {
                    true => tx_view . broadcast(String::from("block"))
                                    . await.unwrap(),
                    false => tx_view . broadcast(String::from("none"))
                                     . await.unwrap(),
                };
            },
        }
    }
}

fn editor_view( tx_logic: broadcast::Sender<AppLogic>
              , rx_view: broadcast::Receiver<String>
              , tx_dom: broadcast::Sender<Dom>
              ) -> ViewBuilder<Dom>
{
    let ns = "http://www.w3.org/2000/svg";

    let input_filter = tx_logic
                     . sink()
                     . contra_map(|_| AppLogic::Update);
    let store_filter = tx_logic
                     . sink()
                     . contra_filter_map(|e :DomEvent| {
                         if let Either::Left(e) = e.clone_inner() {
                             let e = e.dyn_into::<MouseEvent>().unwrap();
                             match e.alt_key() {
                                 true => Some(AppLogic::Store),
                                 false => None
                             }
                         } else {
                             None
                         }
                     });
    let toggle_filter = tx_logic
                      . sink()
                      . contra_map(|_| AppLogic::Toggle);

    builder! {
        <div class="input"
             style:width="33%"
             on:input=input_filter
             capture:view=tx_dom.sink()>
            <div contenteditable="true"
                 style:cursor="text"
                 style:display=("none", rx_view)>
                <pre on:click=store_filter></pre>
            </div>
            <div>
                <div>
                    <button>{select_icon()}</button>
                    <button>{save_icon()}</button>
                    <button>{discard_icon()}</button>
                    <button on:click=toggle_filter>{edit_icon()}</button>
                </div>
                <div></div>
                <div></div>
                <div></div>
            </div>
        </div>
    }
}

#[wasm_bindgen(start)]
pub async fn main() -> Result<(), JsValue> {
    panic::set_hook(Box::new(console_error_panic_hook::hook));
    console_log::init_with_level(Level::Trace).unwrap();

    let (tx_dom, rx_dom) = broadcast::bounded(1);
    let (tx_logic, rx_logic) = broadcast::bounded(1);
    let (tx_view, rx_view) = broadcast::bounded(1);
    let comp = Component::from( editor_view(tx_logic, rx_view, tx_dom) )
             . with_logic( editor_logic(rx_logic, tx_view, rx_dom) );

    let page = Component::from(builder! {{comp}});
    page.build()?.run()
}