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"> <script lang="ts">
import { profile } from '$lib/auth.js' 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 { 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 { Button, Modal } from 'mono-svelte'
import { createEventDispatcher } from '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 open: boolean
export let image: FileList | null = null export let image: FileList | null = null
export let output: string | undefined = undefined export let preview: boolean = true
let loading = false 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() { async function upload() {
if (!$profile?.jwt || image == null) return if (!$profile?.jwt || image == null) return
loading = true progress = 0
try { try {
const uploaded = await uploadImage( const uploaded = (
image[0], await Promise.all(
$profile.instance, Array.from(image).map((i) =>
$profile.jwt 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') if (!uploaded) throw new Error('Image upload returned undefined')
dispatcher('upload', uploaded) dispatcher('upload', uploaded)
output = uploaded progress = 1
loading = false
open = false open = false
} catch (err) { } catch (err) {
toast({ toast({
content: err as any, content: errorMessage(err),
type: 'error', type: 'error',
}) })
} }
loading = false progress = 1
} }
</script> </script>
<Modal bind:open> <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}> <form class="flex flex-col gap-4" on:submit|preventDefault={upload}>
<ImageInput accept="image/jpeg,image/png,image/webp" bind:files={image} /> <label
<Button {loading} disabled={loading} submit color="primary" size="lg"> 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 Upload
</Button> </Button>
</form> </form>
@@ -219,8 +219,9 @@
{#await import('$lib/components/lemmy/modal/ImageUploadModal.svelte') then { default: UploadModal }} {#await import('$lib/components/lemmy/modal/ImageUploadModal.svelte') then { default: UploadModal }}
<UploadModal <UploadModal
bind:open={uploadingImage} bind:open={uploadingImage}
multiple={false}
on:upload={(e) => { on:upload={(e) => {
if (e.detail) data.url = e.detail if (e.detail) data.url = e.detail[0]
uploadingImage = false uploadingImage = false
}} }}
/> />
@@ -16,6 +16,7 @@
ListBullet, ListBullet,
Photo, Photo,
} from 'svelte-hero-icons' } from 'svelte-hero-icons'
import ImageUploadModal from '../lemmy/modal/ImageUploadModal.svelte'
export let images: boolean = true export let images: boolean = true
export let value: string = '' export let value: string = ''
@@ -62,40 +63,7 @@
} }
let uploadingImage = false let uploadingImage = false
let loading = false
let image: any 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 export let previewing = false
@@ -114,49 +82,15 @@
</script> </script>
{#if uploadingImage && images} {#if uploadingImage && images}
<Modal bind:open={uploadingImage}> <ImageUploadModal
<span slot="title">Upload image</span> bind:open={uploadingImage}
<form class="flex flex-col gap-4" on:submit|preventDefault={upload}> bind:image
<div class="flex flex-col gap-1"> on:upload={(e) => {
<label e.detail.forEach((i) => {
class="flex flex-col items-center px-8 py-4 mx-auto w-full rounded-lg wrapSelection(`![](${i})\n\n`, '')
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>
{/if} {/if}
<div> <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", "nsfw": "NSFW",
"generateTitle": "Generate Title", "generateTitle": "Generate Title",
"uploadImage": "Upload Image", "uploadImage": "Upload Image",
"selectFile": "Select a file",
"altText": "Alt Text" "altText": "Alt Text"
}, },
"profile": { "profile": {
+12 -6
View File
@@ -82,7 +82,7 @@
class="flex flex-col gap-4 bg-white dark:bg-black border border-slate-300 dark:border-zinc-800 p-4 w-full h-32 rounded-xl" class="flex flex-col gap-4 bg-white dark:bg-black border border-slate-300 dark:border-zinc-800 p-4 w-full h-32 rounded-xl"
> >
{#if formData.icon} {#if formData.icon}
<img src={formData.icon} class="rounded-md mx-auto h-full" /> <img src={formData.icon} alt="" class="rounded-md mx-auto h-full" />
{:else} {:else}
<Icon <Icon
src={DocumentPlus} src={DocumentPlus}
@@ -94,8 +94,11 @@
{#if uploading.icon} {#if uploading.icon}
<ImageUploadModal <ImageUploadModal
bind:open={uploading.icon} bind:open={uploading.icon}
bind:output={formData.icon} multiple={false}
on:upload={() => (uploading.icon = false)} on:upload={(uploaded) => {
uploading.icon = false
formData.icon = uploaded.detail[0]
}}
/> />
{/if} {/if}
</div> </div>
@@ -107,7 +110,7 @@
class="flex flex-col gap-4 bg-white dark:bg-black border border-slate-300 dark:border-zinc-800 p-4 w-full h-32 rounded-xl" class="flex flex-col gap-4 bg-white dark:bg-black border border-slate-300 dark:border-zinc-800 p-4 w-full h-32 rounded-xl"
> >
{#if formData.banner} {#if formData.banner}
<img src={formData.banner} class="rounded-md mx-auto h-full" /> <img src={formData.banner} alt="" class="rounded-md mx-auto h-full" />
{:else} {:else}
<Icon <Icon
src={DocumentPlus} src={DocumentPlus}
@@ -119,8 +122,11 @@
{#if uploading.banner} {#if uploading.banner}
<ImageUploadModal <ImageUploadModal
bind:open={uploading.banner} bind:open={uploading.banner}
bind:output={formData.banner} multiple={false}
on:upload={() => (uploading.banner = false)} on:upload={(uploaded) => {
uploading.banner = false
formData.banner = uploaded.detail[0]
}}
/> />
{/if} {/if}
</div> </div>