use fission::prelude::*;
fission_component! {
pub AttachmentPicker<AppState> {
props { upload_url: String }
}
view(picker, state, cx) {
let browse = cx.bind(PickAttachment, reduce!(on_pick_attachment));
let upload = cx.bind(UploadAttachment(picker.upload_url.clone()), reduce!(on_upload_attachment));
}
=> Column(children: [
if state.picking || state.uploading { Spinner(motion: SpinnerMotion::Default, label: cx.tr("attachments.pending")) }
else {
FileUpload(
label: cx.tr("attachments.choose"),
selected_file: state.pending_attachment.as_ref().map(|file| file.name.clone()),
error_text: state.upload_error.clone(),
on_browse: browse,
)
},
Button(
child: Text(cx.tr("attachments.upload")),
disabled: state.picking || state.uploading || state.upload_attempted
|| state.pending_attachment.is_none() || picker.upload_url.is_empty(),
on_press: upload,
),
if state.uploaded_object_id.is_some() { Text(cx.tr("attachments.uploaded")) },
])
}
#[derive(Debug, Clone, Default)]
pub struct AppState {
pub pending_attachment: Option<PickedFile>,
pub picking: bool,
pub uploading: bool,
pub upload_attempted: bool,
pub upload_error: Option<String>,
pub uploaded_object_id: Option<String>,
}
impl GlobalState for AppState {}
use fission::prelude::*;
#[fission_reducer(PickAttachment)]
fn on_pick_attachment(
state: &mut AppState,
ctx: &mut ReducerContext<AppState>,
) {
if state.picking || state.uploading { return; }
state.picking = true;
state.upload_error = None;
let picked = ctx.effects.bind(AttachmentPicked, reduce!(on_attachment_picked));
let failed = ctx.effects.bind(AttachmentPickFailed, reduce!(on_attachment_pick_failed));
ctx.effects
.capability(
PICK_OPEN_FILES,
PickOpenFilesRequest {
allow_multiple: false,
mime_types: vec!["application/pdf".into(), "image/png".into()],
extensions: vec!["pdf".into(), "png".into()],
// Optional performance hint; stream consumers must accept any
// chunk size because hosts may return smaller chunks.
preferred_chunk_bytes: Some(1024 * 1024),
},
)
.on_ok(picked)
.on_err(failed);
}
#[fission_reducer(AttachmentPicked)]
fn on_attachment_picked(
state: &mut AppState,
ctx: &mut ReducerContext<AppState>,
) {
state.picking = false;
let Some(result) = ctx.input.capability_ok(PICK_OPEN_FILES) else {
state.upload_error = Some("The host returned no picker result".into());
return;
};
let Some(file) = result.files.into_iter().next() else {
// Cancellation keeps the previous selection; it is not an upload error.
return;
};
state.pending_attachment = Some(file);
state.upload_attempted = false;
state.uploaded_object_id = None;
state.upload_error = None;
}
#[fission_reducer(AttachmentPickFailed)]
fn on_attachment_pick_failed(state: &mut AppState, ctx: &mut ReducerContext<AppState>) {
state.picking = false;
state.upload_error = Some(ctx.input.capability_error(PICK_OPEN_FILES)
.map(|error| error.message)
.or_else(|| ctx.input.capability_error_message(PICK_OPEN_FILES).map(str::to_owned))
.unwrap_or_else(|| "The host could not open the file picker".into()));
}
#[derive(Debug)]
pub struct UploadAttachmentJob;
impl JobSpec for UploadAttachmentJob {
type Request = UploadAttachmentRequest;
type Ok = UploadAttachmentResult;
type Err = String;
const NAME: &'static str = "app::upload-attachment";
}
pub const UPLOAD_ATTACHMENT_JOB: JobRef<UploadAttachmentJob> =
JobRef::new(UploadAttachmentJob::NAME);
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UploadAttachmentRequest {
pub upload_url: String,
pub name: String,
pub content_type: Option<String>,
pub byte_len: Option<u64>,
pub stream: DataStreamId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UploadAttachmentResult {
pub object_id: String,
}
#[fission_reducer(UploadAttachment)]
fn on_upload_attachment(
state: &mut AppState,
upload_url: String,
ctx: &mut ReducerContext<AppState>,
) {
if state.picking || state.uploading || state.upload_attempted || upload_url.is_empty() { return; }
let Some(file) = state.pending_attachment.clone() else {
state.upload_error = Some("Choose a file first".into());
return;
};
state.uploading = true;
state.upload_attempted = true;
state.upload_error = None;
let uploaded = ctx.effects.bind(AttachmentUploaded, reduce!(on_attachment_uploaded));
let failed = ctx.effects.bind(AttachmentUploadFailed, reduce!(on_attachment_upload_failed));
ctx.effects
.app(
UPLOAD_ATTACHMENT_JOB,
UploadAttachmentRequest {
upload_url,
name: file.name,
content_type: file.content_type,
byte_len: file.byte_len,
stream: file.stream,
},
)
.on_ok(uploaded)
.on_err(failed);
}
#[fission_reducer(AttachmentUploaded)]
fn on_attachment_uploaded(state: &mut AppState, ctx: &mut ReducerContext<AppState>) {
state.uploading = false;
match ctx.input.job_ok(UPLOAD_ATTACHMENT_JOB) {
Some(receipt) if !receipt.object_id.is_empty() => state.uploaded_object_id = Some(receipt.object_id),
_ => state.upload_error = Some("The server returned no attachment receipt".into()),
}
}
#[fission_reducer(AttachmentUploadFailed)]
fn on_attachment_upload_failed(state: &mut AppState, ctx: &mut ReducerContext<AppState>) {
state.uploading = false;
state.upload_error = Some(ctx.input.job_error_message(UPLOAD_ATTACHMENT_JOB)
.unwrap_or("Upload failed; choose the file again").to_owned());
}
DesktopApp::<AppState, _>::new(App)
.with_async(|asyncs| {
asyncs.register_job(
UPLOAD_ATTACHMENT_JOB,
|request: UploadAttachmentRequest, ctx: JobCtx| async move {
let stream = ctx
.open_data_stream(request.stream)
.map_err(|error| error.to_string())?;
reqwest::Client::new()
.put(request.upload_url)
.header(reqwest::header::CONTENT_TYPE,
request.content_type.as_deref().unwrap_or("application/octet-stream"))
.body(reqwest::Body::wrap_stream(stream))
.send().await.map_err(|error| error.to_string())?
.error_for_status().map_err(|error| error.to_string())?
.json::<UploadAttachmentResult>().await
.map_err(|error| error.to_string())
},
);
})
.run()
// Shape only: the stream boundary is the important part.
let stream = ctx.open_data_stream(command.stream)?;
while let Some(chunk) = stream.next().await {
let bytes = chunk?;
upload_part(bytes).await?;
ctx.emit(UploadProgress { uploaded_bytes }).await?;
}
Target | Default behavior |
|---|---|
macOS, Windows, Linux | Native open-file picker with file contents streamed from disk. |
Web | Built-in browser picker with lazy, bounded streaming from each selected File. |
Android, iOS | Shell/provider-specific. Native pickers should return scoped streams or copied sandbox streams. |
Server, SSR, Static site, Terminal | Usually unsupported unless the host app registers an appropriate provider. |