@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
105 lines (103 loc) • 3.1 kB
JavaScript
import { uploadServerFn } from "./upload-fn.js";
import { useCallback, useEffect, useRef, useState } from "react";
//#region src/core/use-file-upload.ts
/**
* The state machine behind useFileUpload, decoupled from React so it can be
* tested directly with a plain dispatch function.
*/
function createFileUploadStore(uploadFn, dispatch) {
let nextId = 0;
return {
upload(file) {
const id = String(++nextId);
const controller = new AbortController();
const cancel = () => {
controller.abort();
dispatch((prev) => prev.filter((item) => item.id !== id));
};
const onProgress = (progress) => {
dispatch((prev) => prev.map((item) => item.id === id && item.status === "uploading" ? {
...item,
progress
} : item));
};
dispatch((prev) => [...prev, {
status: "uploading",
id,
filename: file.name,
progress: 0,
cancel
}]);
uploadFn(file, {
onProgress,
signal: controller.signal
}).then((attachment) => {
dispatch((prev) => prev.map((item) => item.id === id ? {
...attachment,
status: "done"
} : item));
}).catch((error) => {
if (controller.signal.aborted) return;
dispatch((prev) => prev.map((item) => item.id === id ? {
status: "error",
id,
filename: file.name,
error: error instanceof Error ? error : /* @__PURE__ */ new Error("Upload failed")
} : item));
});
},
remove(id) {
dispatch((prev) => prev.filter((item) => item.id !== id));
}
};
}
function xhrUpload(action, file, { onProgress, signal }) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const fd = new FormData();
fd.append("file", file);
fd.append("action", JSON.stringify(action));
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) onProgress(Math.round(e.loaded / e.total * 100));
};
signal.addEventListener("abort", () => {
xhr.abort();
reject(new DOMException("Upload cancelled", "AbortError"));
});
xhr.onload = () => {
if (xhr.status < 200 || xhr.status >= 300) {
reject(/* @__PURE__ */ new Error(`File upload failed: ${xhr.status}`));
return;
}
try {
resolve(JSON.parse(xhr.responseText));
} catch {
reject(/* @__PURE__ */ new Error("File upload: unexpected response format"));
}
};
xhr.onerror = () => reject(/* @__PURE__ */ new Error("File upload failed: network error"));
xhr.open("POST", uploadServerFn.url);
xhr.send(fd);
});
}
function useFileUpload(action, options) {
const [files, dispatch] = useState(() => (options?.initialAttachments ?? []).map((a) => ({
...a,
status: "done"
})));
const actionRef = useRef(action);
useEffect(() => {
actionRef.current = action;
});
const store = useRef(createFileUploadStore((file, opts) => xhrUpload(actionRef.current, file, opts), dispatch));
const upload = useCallback((file) => store.current.upload(file), []);
const remove = useCallback((id) => store.current.remove(id), []);
return {
files,
isUploading: files.some((f) => f.status === "uploading"),
upload,
remove
};
}
//#endregion
export { useFileUpload };