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

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

#[derive(Clone, Debug)]
pub(super) struct Upload {
    file   :File,
    bitmap :ImageBitmap,
}

impl Upload {
    pub(super) async fn new(file :File) -> 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 { file, bitmap }
    }

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

    pub(super) fn data(&self) -> ReadableStream {
        self.file.stream()
    }

    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 view = upload_preview_view( tx_canvas
                                      , upload.file.name()
                                      , upload.file.size()
                                      , upload.file.type_()
                                      , upload.file.last_modified() );
        let logic = upload_preview_logic(rx_canvas, 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()
    }
}