upload.rs 2.05 KB
use mogwai::{prelude::*, utils::window};
use web_sys::{File, ImageBitmap};
use wasm_bindgen::prelude::*;

use super::{view::upload_preview_view, logic::{upload_preview_logic, UploadLogic}};

#[derive(Clone, Debug)]
pub(crate) struct Upload {
    pub(super) id       :usize,
               file     :File,
               bitmap   :ImageBitmap,
    pub(super) tx_logic :broadcast::Sender<UploadLogic>,
}

impl Upload {
    pub(super) async fn new( id       :usize
                           , file     :File
                           , tx_logic :broadcast::Sender<UploadLogic>
                           ) -> Upload {
        let bitmap = window()
                   . create_image_bitmap_with_blob(&file.clone().into())
                   . unwrap();
        let bitmap = JsFuture::from(bitmap)
                   . await.unwrap()
                   . dyn_into::<ImageBitmap>().unwrap();

        Self { id, file, bitmap, tx_logic }
    }

    pub(crate) fn mime_type(&self) -> String {
        self.file.type_()
    }

    pub(crate) fn data(&self) -> &JsValue {
        &self.file
    }

    pub(crate) fn size(&self) -> usize {
        self.file.size() as usize
    }

    pub(super) fn bitmap(&self) -> ImageBitmap {
        self.to_owned().bitmap
    }
}

impl From<Upload> for Component<Dom> {
    fn from(upload: Upload) -> Self {
        let (tx_canvas, rx_canvas) = broadcast::bounded(1);
        let (tx_click, rx_click) = broadcast::bounded(1);

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

        Component::from(view).with_logic(logic)
    }
}

impl From<Upload> for ViewBuilder<Dom> {
    fn from(upload: Upload) -> Self {
        let component :Component<Dom> = upload.into();
        component.into()
    }
}