Add an image by upload or url from one dialog (#388)

Co-authored-by: Coracle-Bot <npub1klq6260@nostr.local>
This commit is contained in:
Coracle-Bot 2026-09-01 23:55:01 +00:00 committed by hodlbod
parent 7db286ed2d
commit 97d4222d35
7 changed files with 184 additions and 43 deletions

View file

@ -0,0 +1,107 @@
<script lang="ts">
import LinkRound from "@assets/icons/link-round.svg?dataurl"
import UploadMinimalistic from "@assets/icons/upload-minimalistic.svg?dataurl"
import AltArrowLeft from "@assets/icons/alt-arrow-left.svg?dataurl"
import {preventDefault} from "@lib/html"
import Icon from "@lib/components/Icon.svelte"
import Field from "@lib/components/Field.svelte"
import Button from "@lib/components/Button.svelte"
import Modal from "@lib/components/Modal.svelte"
import ModalBody from "@lib/components/ModalBody.svelte"
import ModalHeader from "@lib/components/ModalHeader.svelte"
import ModalTitle from "@lib/components/ModalTitle.svelte"
import ModalSubtitle from "@lib/components/ModalSubtitle.svelte"
import ModalFooter from "@lib/components/ModalFooter.svelte"
import {popModal} from "@app/modal"
type Props = {
onSelect: (image: File | string) => void
initialValue?: string
}
const {onSelect, initialValue = ""}: Props = $props()
const isValidUrl = (value: string) => {
try {
return ["http:", "https:"].includes(new URL(value).protocol)
} catch (e) {
return false
}
}
const select = (image: File | string) => {
onSelect(image)
popModal()
}
const onFileChange = (event: Event) => {
const selected = (event.target as HTMLInputElement).files?.[0]
if (selected?.type.startsWith("image/")) {
select(selected)
}
}
let value = $state(initialValue)
let failedUrl = $state("")
const url = $derived(value.trim())
const isValid = $derived(isValidUrl(url))
const failed = $derived(Boolean(url) && failedUrl === url)
</script>
<Modal tag="form" onsubmit={preventDefault(() => select(url))}>
<ModalBody>
<ModalHeader>
<ModalTitle>Add an image</ModalTitle>
<ModalSubtitle>Upload a file, or link to an image hosted somewhere else.</ModalSubtitle>
</ModalHeader>
<label class="button button-primary cursor-pointer">
<Icon icon={UploadMinimalistic} />
Upload a file
<input type="file" accept="image/*" class="hidden" onchange={onFileChange} />
</label>
<div class="flex items-center gap-3 text-sm opacity-50">
<span class="h-px grow bg-line"></span>
or
<span class="h-px grow bg-line"></span>
</div>
<Field>
{#snippet label()}
<p>Image URL</p>
{/snippet}
{#snippet input()}
<label class="input flex w-full items-center gap-2">
<Icon icon={LinkRound} />
<input bind:value class="grow" type="url" placeholder="https://" />
</label>
{/snippet}
{#snippet info()}
{#if url && !isValid}
<span class="text-error">Please enter a valid http or https link.</span>
{:else if failed}
<span class="text-error">That link could not be loaded as an image.</span>
{:else}
<span>The image will be linked from where it's hosted rather than re-uploaded.</span>
{/if}
{/snippet}
</Field>
{#if isValid && !failed}
<div class="flex justify-center">
<img
src={url}
alt="Preview"
class="max-h-48 rounded-2xl object-contain"
onerror={() => (failedUrl = url)} />
</div>
{/if}
</ModalBody>
<ModalFooter>
<Button class="button button-link" onclick={popModal}>
<Icon icon={AltArrowLeft} />
Go back
</Button>
<Button type="submit" class="button button-primary" disabled={!isValid}>Use this image</Button>
</ModalFooter>
</Modal>

View file

@ -14,7 +14,7 @@
import {rooms} from "@app/core"
import {joinRoom} from "@app/access"
import {pushToast} from "@app/toast"
import {compressFileForUpload, uploadFileOrFallback} from "@app/uploads"
import {resolveImageInput} from "@app/uploads"
import {deriveHasLivekit} from "@app/relays"
import {RoomType} from "@app/rooms"
@ -28,6 +28,8 @@
const {url, header, footer, onsubmit, initialValues = {h: randomId()}}: Props = $props()
const compressOptions = {maxWidth: 128, maxHeight: 128}
const values = $state(initialValues)
const relayHasLivekit = deriveHasLivekit(url)
@ -43,16 +45,7 @@
room.livekit = roomType === RoomType.Voice
if (imageFile) {
const compressedFile = await compressFileForUpload(imageFile, {
maxWidth: 128,
maxHeight: 128,
})
const result = await uploadFileOrFallback(compressedFile)
room.picture = result.url
}
room.picture = await resolveImageInput(imageFile, imagePreview, compressOptions)
const createCommand = await $rooms.createRoom(url, room)
const createMessage = await createCommand.publish().waitForError()

View file

@ -18,7 +18,7 @@
import IconInput from "@lib/components/IconInput.svelte"
import {pushToast} from "@app/toast"
import {clearModals} from "@app/modal"
import {compressFileForUpload, uploadFileOrFallback} from "@app/uploads"
import {resolveImageInput} from "@app/uploads"
import {relayManagement, relays} from "@app/core"
type Props = {
@ -30,6 +30,8 @@
const values = $state({...initialValues})
const compressOptions = {maxWidth: 128, maxHeight: 128}
const back = () => history.back()
const submit = async () => {
@ -51,11 +53,10 @@
}
}
if (imageFile) {
const compressedFile = await compressFileForUpload(imageFile, {maxWidth: 128, maxHeight: 128})
const result = await uploadFileOrFallback(compressedFile)
const icon = await resolveImageInput(imageFile, imagePreview, compressOptions)
const res = await $relayManagement.forUrl(url).changeRelayIcon(result.url)
if (icon && icon !== initialValues.icon) {
const res = await $relayManagement.forUrl(url).changeRelayIcon(icon)
if (res.error) {
return pushToast({theme: "error", message: res.error})

View file

@ -28,7 +28,7 @@
import {derivePlans} from "@app/hosting"
import {HOSTING_RELAY_DOMAIN} from "@app/env"
import {pushToast} from "@app/toast"
import {compressFileForUpload, uploadFileOrFallback} from "@app/uploads"
import {resolveImageInput} from "@app/uploads"
type Props = {
mode: "create" | "edit"
@ -48,6 +48,8 @@
onSubmit,
}: Props = $props()
const compressOptions = {maxWidth: 128, maxHeight: 128}
const slugify = (value: string) =>
value
.toLowerCase()
@ -123,17 +125,11 @@
loading = true
try {
if (imageFile) {
const compressedFile = await compressFileForUpload(imageFile, {
maxWidth: 128,
maxHeight: 128,
})
const result = await uploadFileOrFallback(compressedFile)
const resolvedIcon = await resolveImageInput(imageFile, imagePreview, compressOptions)
icon = result.url
imagePreview = result.url
imageFile = undefined
}
icon = resolvedIcon ?? ""
imagePreview = icon
imageFile = undefined
await onSubmit({
plan_id: planId,

View file

@ -1,3 +1,4 @@
import type {Maybe} from "@welshman/lib"
import {first, normalizeUrl, parseJson, sha256, simpleCache} from "@welshman/lib"
import {canUploadBlob, encryptFile, makeBlossomAuthEvent, uploadBlob} from "@welshman/util"
import {Nip01Signer} from "@welshman/signer"
@ -177,3 +178,18 @@ export const uploadFileOrFallback = async (
return {url: await readFileAsDataUrl(file), tags: []}
}
export const resolveImageInput = async (
file: Maybe<File>,
url: Maybe<string>,
options: CompressFileOptions = {},
) => {
if (!file) {
return url
}
const compressedFile = await compressFileForUpload(file, options)
const result = await uploadFileOrFallback(compressedFile)
return result.url
}

View file

@ -4,17 +4,20 @@
import Icon from "@lib/components/Icon.svelte"
import ImageIcon from "@lib/components/ImageIcon.svelte"
import IconPickerButton from "@lib/components/IconPickerButton.svelte"
import ImageInputButton from "@lib/components/ImageInputButton.svelte"
type Props = {
// The parent uploads this on submit — never `preview`, which may be a data: URL.
file?: File | undefined
// An existing hosted URL, or the data: URL of a freshly picked image.
// An existing hosted URL, the data: URL of a freshly picked image, or a URL the user pasted.
preview?: string | undefined
previewClass?: string
}
let {file = $bindable(), preview = $bindable(), previewClass = ""}: Props = $props()
const initialUrlValue = $derived(preview?.startsWith("data:") ? undefined : preview)
// Decode a built-in icon's base64 SVG data: URL into a File so it uploads on
// submit like any image.
const handleIconSelect = (iconUrl: string) => {
@ -31,19 +34,21 @@
file = new File([bytes], "icon.svg", {type: "image/svg+xml"})
}
const handleImageUpload = (event: Event) => {
const selected = (event.target as HTMLInputElement).files?.[0]
if (selected && selected.type.startsWith("image/")) {
const reader = new FileReader()
reader.onload = e => {
file = selected
preview = e.target?.result as string
}
reader.readAsDataURL(selected)
const handleImageSelect = (image: File | string) => {
if (typeof image === "string") {
file = undefined
preview = image
return
}
const reader = new FileReader()
reader.onload = e => {
file = image
preview = e.target?.result as string
}
reader.readAsDataURL(image)
}
</script>
@ -60,9 +65,11 @@
<IconPickerButton onSelect={handleIconSelect} class="button button-primary button-sm">
<Icon icon={StickerSmileSquare} size={4} />
</IconPickerButton>
<label class="button button-neutral button-sm cursor-pointer">
<ImageInputButton
onSelect={handleImageSelect}
initialValue={initialUrlValue}
class="button button-neutral button-sm">
<Icon icon={UploadMinimalistic} size={4} />
<input type="file" accept="image/*" class="hidden" onchange={handleImageUpload} />
</label>
</ImageInputButton>
</div>
</div>

View file

@ -0,0 +1,21 @@
<script lang="ts">
import type {Snippet} from "svelte"
import Button from "@lib/components/Button.svelte"
import ImageInputModal from "@app/components/ImageInputModal.svelte"
import {pushModal} from "@app/modal"
type Props = {
onSelect: (image: File | string) => void
initialValue?: string
children?: Snippet
[key: string]: any
}
const {onSelect, initialValue, children, ...props}: Props = $props()
const open = () => pushModal(ImageInputModal, {onSelect, initialValue}, {nested: true})
</script>
<Button onclick={open} {...props}>
{@render children?.()}
</Button>