feat: improve file upload and diplay stuff
This commit is contained in:
@@ -4,17 +4,59 @@ const props = defineProps<{
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
status?: 'pending' | 'uploaded';
|
||||
status?: 'uploading' | 'uploaded' | 'error';
|
||||
url: string;
|
||||
progress?: number;
|
||||
}
|
||||
}>();
|
||||
|
||||
const isImage = computed(() => props.file.mimeType.startsWith('image/'));
|
||||
const isVideo = computed(() => props.file.mimeType.startsWith('video/'));
|
||||
const isAudio = computed(() => props.file.mimeType.startsWith('audio/'));
|
||||
const isPdf = computed(() => props.file.mimeType === 'application/pdf');
|
||||
|
||||
const fileIcon = computed(() => {
|
||||
if (isImage.value) return 'i-mynaui-image';
|
||||
if (isVideo.value) return 'i-mynaui-video';
|
||||
if (isAudio.value) return 'i-mynaui-music';
|
||||
if (isPdf.value) return 'i-tabler-file-type-pdf';
|
||||
if (props.file.mimeType.includes('text')) return 'i-mynaui-file-text';
|
||||
if (props.file.mimeType.includes('zip') || props.file.mimeType.includes('archive')) return 'i-mynaui-archive';
|
||||
return 'i-mynaui-file';
|
||||
});
|
||||
|
||||
const fileExtension = computed(() => {
|
||||
const parts = props.file.name.split('.');
|
||||
return parts.length > 1 ? parts.pop()?.toUpperCase() : 'FILE';
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<img v-if="props.file.mimeType.startsWith('image/')" :src="props.file.url"
|
||||
class="rounded-lg h-full w-full max-h-36 max-w-64 object-cover" />
|
||||
<video v-else-if="props.file.mimeType.startsWith('video/')" controls :src="props.file.url"
|
||||
class="rounded-lg h-full w-full max-h-36 max-w-64 aspect-ratio-video object-cover" />
|
||||
<audio v-else-if="props.file.mimeType.startsWith('audio/')" :src="props.file.url"
|
||||
class="rounded-lg h-full w-full max-h-36 max-w-64 object-cover" />
|
||||
</template>
|
||||
<div class="relative h-full w-fit">
|
||||
<img v-if="isImage" :src="props.file.url" class="rounded-lg h-full w-full max-h-36 max-w-64 object-cover" />
|
||||
<video v-else-if="isVideo" controls :src="props.file.url"
|
||||
class="rounded-lg h-full w-full max-h-36 max-w-64 object-cover" />
|
||||
<audio v-else-if="isAudio" controls :src="props.file.url" class="rounded-lg h-full w-full max-h-36 max-w-64" />
|
||||
|
||||
<div v-else class="flex items-center gap-2 p-2 rounded-lg bg-[var(--color-hover)] min-w-40 max-w-48">
|
||||
<span :class="[fileIcon, 'text-6 text-[var(--color-accent)]']"></span>
|
||||
<div class="flex-1 min-w-0">
|
||||
<p class="text-sm truncate">{{ props.file.name }}</p>
|
||||
<p class="text-xs text-[var(--text-tertiary)]">{{ fileExtension }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="file.status === 'uploading'"
|
||||
class="absolute inset-0 bg-black/50 rounded-lg flex items-center justify-center">
|
||||
<div class="text-center">
|
||||
<span class="i-svg-spinners-90-ring-with-bg text-6 text-white block mb-1"></span>
|
||||
<span class="text-xs text-white">{{ file.progress || 0 }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button @click="$emit('delete')"
|
||||
class="absolute top-0 right-0 translate-x-1/2 -translate-y-1/2 flex items-center justify-center w-4 h-4 rounded-full bg-[var(--bg-base)] border border-[var(--color-border)] text-xs text-[#ff3b3b]">
|
||||
<span class="i-mynaui-x text-3"></span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -6,7 +6,7 @@ const props = defineProps<{
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
status: 'pending' | 'uploaded';
|
||||
status: 'uploading' | 'uploaded' | 'error';
|
||||
url: string;
|
||||
}
|
||||
}>();
|
||||
|
||||
@@ -13,8 +13,9 @@ const files = ref<{
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
status: 'pending' | 'uploaded';
|
||||
status: 'uploading' | 'uploaded' | 'error';
|
||||
url: string;
|
||||
progress: number;
|
||||
}[]>([]);
|
||||
const inputValue = defineModel<BaseMessage>({ required: false, default: { content: '', fileIds: [] } });
|
||||
const textAreaValue = ref('');
|
||||
@@ -189,7 +190,7 @@ onUnmounted(() => {
|
||||
<div :class="['w-full flex max-h-full', $attrs.class]">
|
||||
<div class="relative w-full flex flex-shrink-1 flex-col gap-3 p-2 rounded-2xl border transition-border ease-in-out duration-300 bg-[var(--bg-container)]
|
||||
border-[var(--color-border)] focus-within:border-[var(--color-border-active)]">
|
||||
<div v-if="files.length > 0" class="flex-1 flex gap-2 max-w-full max-h-24 pt-2 px-2">
|
||||
<div v-if="files.length > 0" class="flex-1 flex gap-2 pt-2 px-2 pb-1 overflow-x-auto flex-wrap">
|
||||
<!-- TODO: show attachment previews -->
|
||||
<AttachmentPreview v-for="file in files" @delete="files = files.filter((f) => f.id !== file.id)"
|
||||
:key="file.id" :file="file" />
|
||||
@@ -207,9 +208,7 @@ onUnmounted(() => {
|
||||
<!-- TODO: since we dont want to model selector dropdown to potentially overflow, it has max-width: 100%, so, we need to maake the trigger large enough to fit the entire width of the dropdown -->
|
||||
<div class="flex flex-1 gap-1">
|
||||
<ModelSelector v-if="providers !== undefined" v-model="selectedModel" :providers="providers" />
|
||||
<FileSelector
|
||||
v-if="selectedModel && [...selectedModel.attributes.inputModalities].filter(p => p !== 'text').length > 0"
|
||||
v-model="files" />
|
||||
<FileSelector :selected-model="selectedModel" v-model="files" />
|
||||
</div>
|
||||
<button aria-label="Send message" @click="handleSubmit"
|
||||
:disabled="(!inputValue.content.trim() && files.length === 0) && !loading" :class="[
|
||||
|
||||
+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