logic.rs 2.08 KB
use mogwai::prelude::*;
use web_sys::{HtmlInputElement, ImageBitmap, HtmlCanvasElement, CanvasRenderingContext2d};

use super::upload::Upload;

pub(super) async fn upload_preview_logic( mut rx_canvas :broadcast::Receiver<Dom>
                                        , upload :Upload ) {
    while let Some(dom) = rx_canvas.next().await {
        match dom.inner_read() {
            Either::Left(c) => {
                let canvas = c.to_owned().dyn_into::<HtmlCanvasElement>().unwrap();
                let context = canvas
                            . get_context("2d").unwrap().unwrap()
                            . dyn_into::<CanvasRenderingContext2d>().unwrap();
                context
                    . draw_image_with_image_bitmap_and_dw_and_dh(
                          &upload.bitmap()
                        , 0.0, 0.0
                        , canvas.width() as f64, canvas.height() as f64 )
                    . unwrap();
            },
            _ => (),
        }
    }
}

pub(super) async fn upload_logic( mut rx_logic: broadcast::Receiver<DomEvent>
                                , tx_previews: mpmc::Sender<ListPatch<ViewBuilder<Dom>>>
                                ) {
    let mut uploads: ListPatchModel<Upload> = ListPatchModel::new();

    mogwai::spawn(uploads.stream().for_each(move |patch| {
        let patch = patch.map(|u| u.into());
        let tx_previews = tx_previews.clone();
        async move {
            tx_previews.send(patch).await.unwrap();
        }
    }));

    while let Some(msg) = rx_logic.next().await {
        match msg.clone_inner() {
            Either::Left(val) => {
                let filelist = val.dyn_into::<Event>().unwrap()
                             . target().unwrap()
                             . dyn_into::<HtmlInputElement>().unwrap()
                             . files().unwrap();

                for index in 0..filelist.length() {
                    let file = filelist.item(index).unwrap();
                    uploads.list_patch_push(Upload::new(file).await);
                }
            },
            _ => (),
        }
    }
}