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

use crate::component::upload::view::upload_preview_view;

async fn upload_preview_logic( mut rx_canvas :broadcast::Receiver<Dom>
                             , bitmap :ImageBitmap ) {
    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( &bitmap
                                                                    , 0.0, 0.0
                                                                    , 100.0, 100.0 )
                        . unwrap();
            },
            _ => (),
        }
    }
}

pub(super) async fn upload_logic( mut rx_logic: broadcast::Receiver<DomEvent>
                                , tx_previews: mpmc::Sender<ListPatch<ViewBuilder<Dom>>>
                                ) {
    while let Some(msg) = rx_logic.next().await {
        match msg.clone_inner() {
            Either::Left(val) => {
                let event = val.dyn_into::<Event>().unwrap();
                let target = event.target().unwrap();
                let element = target.dyn_into::<HtmlInputElement>().unwrap();
                let filelist = element.files().unwrap();

                let mut previews = vec![];
                for index in 0..filelist.length() {
                    let (tx_canvas, rx_canvas) = broadcast::bounded(1);
                    let file = filelist.item(index).unwrap();
                    let bitmap =
                        JsFuture::from( window().unwrap()
                                      . create_image_bitmap_with_blob(&file.clone().into()).unwrap());
                    let bitmap = bitmap
                               . await.unwrap()
                               . dyn_into::<ImageBitmap>().unwrap();

                    let view = upload_preview_view( tx_canvas
                                                  , file.name()
                                                  , file.size()
                                                  , file.type_()
                                                  , file.last_modified() );
                    let logic = upload_preview_logic(rx_canvas, bitmap);

                    previews.push(Component::from(view).with_logic(logic).into());
                }
                let previews = ListPatch::splice(.., previews.into_iter());
                tx_previews.send(previews).await.unwrap();
            },
            _ => (),
        }
    }
}