feat: allow uploading multiple images in image upload modal

This commit is contained in:
Xylight committed 2024-08-05 10:55:38 -07:00
1 parent 8fb1777bbb
commit 4e65bc1113
6 files changed
+123 -100

No files matched your search

@@ -1,51 +1,117 @@
<script lang="ts">
import { profile } from '$lib/auth.js'
import ProgressBar from '$lib/components/ui/ProgressBar.svelte'
import { errorMessage } from '$lib/lemmy/error'
import { t } from '$lib/translations'
import { uploadImage } from '$lib/util.js'
import { ImageInput, toast } from 'mono-svelte'
import { ImageInput, Spinner, toast } from 'mono-svelte'
import { Button, Modal } from 'mono-svelte'
import { createEventDispatcher } from 'svelte'
import { DocumentPlus, Icon } from 'svelte-hero-icons'
import { expoOut } from 'svelte/easing'
import { slide } from 'svelte/transition'
export let open: boolean
export let image: FileList | null = null
export let output: string | undefined = undefined
let loading = false
export let preview: boolean = true
export let multiple: boolean = true
let progress = 1
const dispatcher = createEventDispatcher<{ upload: string }>()
$: previewURLs =
preview && image ? Array.from(image).map(URL.createObjectURL) : undefined
const dispatcher = createEventDispatcher<{ upload: string[] }>()
async function upload() {
if (!$profile?.jwt || image == null) return
loading = true
progress = 0
try {
const uploaded = await uploadImage(
image[0],
$profile.instance,
$profile.jwt
)
const uploaded = (
await Promise.all(
Array.from(image).map((i) =>
uploadImage(i, $profile.instance, $profile.jwt!)
.then((uploaded) => {
progress += 1 / (image?.length ?? 0)
return uploaded
})
.catch((err) => {
toast({ content: errorMessage(err), type: 'error' })
return 'Failed to upload'
})
)
)
).filter((i) => i != undefined)
if (!uploaded) throw new Error('Image upload returned undefined')
dispatcher('upload', uploaded)
output = uploaded
loading = false
progress = 1
open = false
} catch (err) {
toast({
content: err as any,
content: errorMessage(err),
type: 'error',
})
}
loading = false
progress = 1
}
</script>
<Modal bind:open>
<span slot="title">Upload image</span>
<div slot="title" class="flex items-center gap-2">Upload image</div>
{#if progress != 1}
<div transition:slide={{ duration: 500, easing: expoOut }} class="w-full">
<ProgressBar {progress} />
</div>
{/if}
<form class="flex flex-col gap-4" on:submit|preventDefault={upload}>
<ImageInput accept="image/jpeg,image/png,image/webp" bind:files={image} />
<Button {loading} disabled={loading} submit color="primary" size="lg">
<label
for="image-input"
class="p-4 border-2 border-dashed rounded-xl cursor-pointer transition-colors
border-slate-300 dark:border-zinc-700 hover:border-primary-900 dark:hover:border-primary-100"
>
{#if previewURLs}
<div
class="grid gap-x-2 gap-y-px max-h-64 overflow-auto
{multiple ? 'grid-cols-3 grid-rows-2' : 'grid-cols-1 grid-rows-1'}"
>
{#each previewURLs as file}
<!-- svelte-ignore a11y-missing-attribute -->
<img
src={file}
on:load={() => URL.revokeObjectURL(file)}
alt={file}
class="w-full rounded-md h-full object-cover transition-all
border border-slate-200 dark:border-zinc-800 ring-1
ring-slate-50 dark:ring-zinc-950 bg-white dark:bg-zinc-950"
/>
{/each}
</div>
{:else}
<div class="flex flex-col justify-center w-full items-center gap-2">
<Icon src={DocumentPlus} size="32" />
<span>{$t('form.post.selectFile')}</span>
</div>
{/if}
<input
{multiple}
type="file"
accept="image/*"
class="hidden"
id="image-input"
bind:files={image}
/>
</label>
<Button
loading={progress != 1}
disabled={progress != 1 || image == null}
submit
color="primary"
size="lg"
>
Upload
</Button>
</form>
@@ -219,8 +219,9 @@
{#await import('$lib/components/lemmy/modal/ImageUploadModal.svelte') then { default: UploadModal }}
<UploadModal
bind:open={uploadingImage}
multiple={false}
on:upload={(e) => {
if (e.detail) data.url = e.detail
if (e.detail) data.url = e.detail[0]
uploadingImage = false
}}
/>
@@ -16,6 +16,7 @@
ListBullet,
Photo,
} from 'svelte-hero-icons'
import ImageUploadModal from '../lemmy/modal/ImageUploadModal.svelte'
export let images: boolean = true
export let value: string = ''
@@ -62,40 +63,7 @@
}
let uploadingImage = false
let loading = false
let image: any
$: previewURL = image?.length
? URL.createObjectURL(image[0])
: image
? URL.createObjectURL(image)
: ''
async function upload() {
if (!$profile?.jwt || !image) return
loading = true
try {
const uploaded = await uploadImage(
image instanceof FileList ? image[0] : image,
$profile.instance,
$profile.jwt
)
if (!uploaded) throw new Error('Image upload returned undefined')
wrapSelection(`![](${uploaded})`, '')
uploadingImage = false
} catch (err) {
toast({
content: err as any,
type: 'error',
})
}
loading = false
}
export let previewing = false
@@ -114,49 +82,15 @@
</script>
{#if uploadingImage && images}
<Modal bind:open={uploadingImage}>
<span slot="title">Upload image</span>
<form class="flex flex-col gap-4" on:submit|preventDefault={upload}>
<div class="flex flex-col gap-1">
<label
class="flex flex-col items-center px-8 py-4 mx-auto w-full rounded-lg
border border-slate-300 dark:border-zinc-700 bg-white dark:bg-black
cursor-pointer min-h-36 transition-colors
"
on:drop|preventDefault={(event) =>
(image = event.dataTransfer?.files?.[0])}
on:dragover|preventDefault={(event) => {
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'copy'
}
}}
>
{#if image}
<!-- svelte-ignore a11y-missing-attribute -->
<img
src={previewURL}
on:load={() => {
if (previewURL) URL.revokeObjectURL(previewURL)
}}
class="w-full max-w-sm h-full rounded-lg"
/>
{:else}
<Icon src={DocumentPlus} class="opacity-50" size="36" />
<p class="text-sm opacity-50">Attach a file</p>
{/if}
<input
type="file"
bind:files={image}
accept="image/*"
class="hidden"
/>
</label>
</div>
<Button {loading} disabled={loading} submit color="primary" size="lg">
Upload
</Button>
</form>
</Modal>
<ImageUploadModal
bind:open={uploadingImage}
bind:image
on:upload={(e) => {
e.detail.forEach((i) => {
wrapSelection(`![](${i})\n\n`, '')
})
}}
/>
{/if}
<div>
+15
View File
@@ -0,0 +1,15 @@
<script lang="ts">
import { expoOut } from 'svelte/easing'
import { tweened } from 'svelte/motion'
export let progress: number = 0
let tween = tweened(progress, { easing: expoOut })
$: tween.set(progress)
</script>
<div
class="bg-primary-900 dark:bg-primary-100 h-1 rounded-full"
style="width: {$tween * 100}%;"
/>
+1
View File
@@ -135,6 +135,7 @@
"nsfw": "NSFW",
"generateTitle": "Generate Title",
"uploadImage": "Upload Image",
"selectFile": "Select a file",
"altText": "Alt Text"
},
"profile": {