feat: improve file upload and diplay stuff
This commit is contained in:
+145
-45
@@ -2,13 +2,20 @@
|
||||
import { nanoid } from 'nanoid';
|
||||
import { assert } from '~~/utils/assert';
|
||||
|
||||
const inputRef = ref<HTMLInputElement | null>(null);
|
||||
const props = defineProps<{
|
||||
selectedModel?: ModelWithProvider | null;
|
||||
}>();
|
||||
|
||||
const imageInputRef = ref<HTMLInputElement | null>(null);
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null);
|
||||
|
||||
const files = defineModel<{
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
status: 'pending' | 'uploaded';
|
||||
status: 'uploading' | 'uploaded' | 'error';
|
||||
url: string;
|
||||
progress: number;
|
||||
}[]>({ required: false, default: [] });
|
||||
const rawFiles = ref<{
|
||||
name: string;
|
||||
@@ -17,83 +24,169 @@ const rawFiles = ref<{
|
||||
}[]>([]);
|
||||
|
||||
const triplit = useTriplitClient();
|
||||
|
||||
const activeUploads = ref<Map<string, XMLHttpRequest>>(new Map());
|
||||
|
||||
const uploadWithProgress = (file: File, url: string, id: string) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
activeUploads.value.set(id, xhr);
|
||||
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) {
|
||||
const progress = Math.round((e.loaded / e.total) * 100);
|
||||
files.value = files.value.map(f => {
|
||||
if (f.id === id) {
|
||||
return { ...f, progress };
|
||||
}
|
||||
return f;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onload = () => {
|
||||
activeUploads.value.delete(id);
|
||||
resolve(xhr);
|
||||
};
|
||||
|
||||
xhr.onerror = () => {
|
||||
activeUploads.value.delete(id);
|
||||
reject(xhr);
|
||||
};
|
||||
|
||||
xhr.onabort = () => {
|
||||
activeUploads.value.delete(id);
|
||||
reject(new Error('Upload aborted'));
|
||||
};
|
||||
|
||||
xhr.open('PUT', url);
|
||||
xhr.send(file);
|
||||
});
|
||||
};
|
||||
|
||||
watch(rawFiles, async (newFiles, oldFiles) => {
|
||||
const { user } = useAuth();
|
||||
assert(user.value !== null);
|
||||
|
||||
const diff = newFiles.filter(f => !oldFiles.find(o => o.name === f.name));
|
||||
const diff = newFiles.filter(f =>
|
||||
!oldFiles.find(o => o.name === f.name) &&
|
||||
!files.value.find(existing => existing.name === f.name)
|
||||
);
|
||||
|
||||
if (diff.length === 0) return;
|
||||
|
||||
for (const file of diff) {
|
||||
const id = nanoid();
|
||||
files.value.push({
|
||||
id: nanoid(),
|
||||
id,
|
||||
name: file.name,
|
||||
mimeType: file.type,
|
||||
status: 'pending',
|
||||
status: 'uploading',
|
||||
url: URL.createObjectURL(file.file),
|
||||
progress: 0
|
||||
});
|
||||
}
|
||||
|
||||
await Promise.all(diff.map(async file => {
|
||||
const { url: uploadUrl, assetUrl } = await $fetch('/api/upload/presigned', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
file: {
|
||||
name: file.name,
|
||||
mimeType: file.type,
|
||||
try {
|
||||
const { url: uploadUrl, assetUrl } = await $fetch('/api/upload/presigned', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
file: {
|
||||
name: file.name,
|
||||
mimeType: file.type,
|
||||
}
|
||||
}),
|
||||
}) as { url: string; assetUrl: string };
|
||||
|
||||
await uploadWithProgress(file.file, uploadUrl, files.value.find(f => f.name === file.name)!.id);
|
||||
|
||||
await triplit.insert('files', {
|
||||
id: files.value.find(f => f.name === file.name)!.id,
|
||||
userId: user.value!.id,
|
||||
name: file.name,
|
||||
mimeType: file.type || 'application/octet-stream',
|
||||
url: assetUrl,
|
||||
});
|
||||
|
||||
files.value = files.value.map(f => {
|
||||
if (f.name === file.name) {
|
||||
return {
|
||||
...f,
|
||||
status: 'uploaded',
|
||||
progress: 100
|
||||
};
|
||||
}
|
||||
}),
|
||||
}) as { url: string; assetUrl: string };
|
||||
|
||||
const uploadResponse = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body: file.file,
|
||||
});
|
||||
|
||||
assert(uploadResponse.ok, 'Failed to upload file');
|
||||
|
||||
await triplit.insert('files', {
|
||||
id: files.value.find(f => f.name === file.name)!.id,
|
||||
userId: user.value!.id,
|
||||
name: file.name,
|
||||
mimeType: file.type,
|
||||
url: assetUrl,
|
||||
})
|
||||
files.value = files.value.map(f => {
|
||||
if (f.name === file.name) {
|
||||
return {
|
||||
...f,
|
||||
status: 'uploaded',
|
||||
};
|
||||
}
|
||||
return f;
|
||||
});
|
||||
return f;
|
||||
});
|
||||
} catch (error) {
|
||||
files.value = files.value.map(f => {
|
||||
if (f.name === file.name) {
|
||||
return {
|
||||
...f,
|
||||
status: 'error'
|
||||
};
|
||||
}
|
||||
return f;
|
||||
});
|
||||
}
|
||||
}));
|
||||
})
|
||||
|
||||
const handleFileChange = (e: Event) => {
|
||||
watch(files, async (newFiles, oldFiles) => {
|
||||
if (!oldFiles) return;
|
||||
|
||||
const newIds = new Set(newFiles.map(f => f.id));
|
||||
const removed = oldFiles.filter(f => !newIds.has(f.id));
|
||||
|
||||
rawFiles.value = rawFiles.value.filter(f => removed.find(r => r.name === f.name));
|
||||
|
||||
for (const removedFile of removed) {
|
||||
const xhr = activeUploads.value.get(removedFile.id);
|
||||
if (xhr) {
|
||||
xhr.abort();
|
||||
activeUploads.value.delete(removedFile.id);
|
||||
}
|
||||
|
||||
if (removedFile.url.startsWith('blob:')) {
|
||||
// we knpw that if the url starts with blob: it was the first time we uploaded it
|
||||
// so we can just delete it
|
||||
await triplit.delete('files', removedFile.id);
|
||||
|
||||
URL.revokeObjectURL(removedFile.url);
|
||||
}
|
||||
}
|
||||
}, { deep: true });
|
||||
|
||||
const handleFileChange = (e: Event, inputRef: Ref<HTMLInputElement | null>) => {
|
||||
const inputFiles = (e.target! as HTMLInputElement).files;
|
||||
if (inputFiles === null) return;
|
||||
|
||||
rawFiles.value = [...inputFiles].map(file => ({
|
||||
const newFiles = [...inputFiles].map(file => ({
|
||||
name: file.name,
|
||||
type: file.type,
|
||||
file: file,
|
||||
}));
|
||||
rawFiles.value = [...rawFiles.value, ...newFiles];
|
||||
|
||||
(e.target! as HTMLInputElement).value = '';
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
inputRef.value?.addEventListener('change', handleFileChange);
|
||||
imageInputRef.value?.addEventListener('change', (e) => handleFileChange(e, imageInputRef));
|
||||
fileInputRef.value?.addEventListener('change', (e) => handleFileChange(e, fileInputRef));
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
inputRef.value?.removeEventListener('change', handleFileChange);
|
||||
imageInputRef.value?.removeEventListener('change', (e) => handleFileChange(e, imageInputRef));
|
||||
fileInputRef.value?.removeEventListener('change', (e) => handleFileChange(e, fileInputRef));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input ref="inputRef" type="file" multiple class="hidden" />
|
||||
<Dropdown placement="top">
|
||||
<input ref="imageInputRef" type="file" multiple accept="image/*" class="hidden" />
|
||||
<input ref="fileInputRef" type="file" multiple class="hidden" />
|
||||
<Dropdown dropdownClass="text-sm" placement="top">
|
||||
<template #default="{ toggle, setRef }">
|
||||
<button :ref="setRef" @click="toggle"
|
||||
class="flex items-center justify-center h-8.5 w-8.5 hover:bg-[var(--color-hover)] rounded-lg transition-colors duration-200 ease-[cubic-bezier(0.5,_1,_0.89,_1)]">
|
||||
@@ -102,8 +195,15 @@ onUnmounted(() => {
|
||||
</template>
|
||||
|
||||
<template #dropdown="{ close }">
|
||||
<button @click="inputRef?.click(); close()"
|
||||
class="text-left px-3 py-1.5 items-center gap-1 hover:bg-[var(--color-hover)] rounded-lg transition-colors duration-150">
|
||||
<button
|
||||
:disabled="selectedModel ? [...selectedModel.attributes.inputModalities].filter(p => p !== 'text').length === 0 : true"
|
||||
@click="imageInputRef?.click(); close()"
|
||||
class="text-left px-3 py-1.5 items-center gap-2 enabled:hover:bg-[var(--color-hover)] rounded-lg transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-50">
|
||||
<span class="text-4.5 i-tabler-photo-plus"></span>
|
||||
<span>Upload image</span>
|
||||
</button>
|
||||
<button @click="fileInputRef?.click(); close()"
|
||||
class="text-left px-3 py-1.5 items-center gap-2 hover:bg-[var(--color-hover)] rounded-lg transition-colors duration-150">
|
||||
<span class="text-4.5 i-mynaui-file-plus"></span>
|
||||
<span>Upload file</span>
|
||||
</button>
|
||||
|
||||
Reference in New Issue
Block a user