chadtmiller.com/spaces-bookclub
Book club: a Svelte demo app for atproto spaces (@atproto/lex-space)
0
0
<script lang="ts">
import type { Snippet } from 'svelte'
import Button from '../atoms/Button.svelte'
import type { IconName } from '../atoms/Icon.svelte'
import Alert from '../molecules/Alert.svelte'
import Dialog from './Dialog.svelte'
import { errorMessage } from '../../lib/atproto.ts'
/**
* A dialog wrapping a form whose submit runs an async action: it shows
* progress, keeps the dialog open with the error on failure, and closes on
* success.
*/
let {
open = $bindable(false),
title,
description,
submitLabel,
submitIcon,
tone = 'accent',
onsubmit,
children,
}: {
open?: boolean
title: string
description?: string
submitLabel: string
submitIcon?: IconName
tone?: 'accent' | 'danger'
onsubmit: () => Promise<void>
children?: Snippet
} = $props()
let busy = $state(false)
let error = $state('')
$effect(() => {
if (open) error = ''
})
async function submit(event: SubmitEvent) {
event.preventDefault()
busy = true
error = ''
try {
await onsubmit()
open = false
} catch (err) {
error = errorMessage(err)
} finally {
busy = false
}
}
</script>
<!-- The form wraps the dialog so the footer's submit button belongs to it.
The <dialog> renders in the top layer regardless. -->
<form onsubmit={submit}>
<Dialog bind:open {title} {description} children={children || error ? fields : undefined}>
{#snippet footer()}
<Button variant="ghost" onclick={() => (open = false)} disabled={busy}>Cancel</Button>
<Button
type="submit"
variant={tone === 'danger' ? 'danger' : 'primary'}
icon={submitIcon}
loading={busy}
>
{submitLabel}
</Button>
{/snippet}
</Dialog>
</form>
{#snippet fields()}
{@render children?.()}
{#if error}<Alert>{error}</Alert>{/if}
{/snippet}
<style>
form {
display: contents;
}
</style>