impr: rewrite PostForm component to be stabler and more sustainable (#684)
* impr: rewrite PostForm component into extracted state class * fix: use base community as PostFormState * fix: add else clause to ensure 'unset' unsets the language
This commit is contained in:
1 parent
6f7501ffc5
commit
e4507cbf91
16 files changed
+506
-586
No files matched your search
@@ -137,15 +137,16 @@
|
||||
"url": "URL",
|
||||
"body": "Body",
|
||||
"nsfw": "NSFW",
|
||||
"generateTitle": "Generate title",
|
||||
"generateTitle": "Autofill post",
|
||||
"uploadImage": "Upload image",
|
||||
"selectFile": "Select a file",
|
||||
"altText": "Alt text",
|
||||
"addUrl": "Add URL",
|
||||
"addUrl": "Add link",
|
||||
"setLanguage": "Set language",
|
||||
"unset": "Unset",
|
||||
"readMore": "Read more",
|
||||
"flair": "Add flair"
|
||||
"flair": "Add flair",
|
||||
"fetching": "Fetching site metadata"
|
||||
},
|
||||
"profile": {
|
||||
"displayName": "Display name",
|
||||
|
||||
@@ -1,517 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { client, site } from '$lib/api/client.svelte'
|
||||
import type {
|
||||
CommunityView,
|
||||
Post,
|
||||
PostResponse,
|
||||
PostView,
|
||||
} from '$lib/api/types'
|
||||
import { errorMessage } from '$lib/app/error'
|
||||
import { t } from '$lib/app/i18n'
|
||||
import MarkdownEditor from '$lib/app/markdown/MarkdownEditor.svelte'
|
||||
import { getSessionStorage, setSessionStorage } from '$lib/app/session'
|
||||
import { placeholders } from '$lib/app/util.svelte'
|
||||
import FreeTextInput from '$lib/ui/form/FreeTextInput.svelte'
|
||||
import ObjectAutocomplete from '$lib/ui/form/ObjectAutocomplete.svelte'
|
||||
import Avatar from '$lib/ui/generic/Avatar.svelte'
|
||||
import ErrorContainer, {
|
||||
clearErrorScope,
|
||||
pushError,
|
||||
} from '$lib/ui/info/ErrorContainer.svelte'
|
||||
import { Header } from '$lib/ui/layout'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Material,
|
||||
modal,
|
||||
Option,
|
||||
Select,
|
||||
Spinner,
|
||||
Switch,
|
||||
TextArea,
|
||||
TextInput,
|
||||
toast,
|
||||
} from 'mono-svelte'
|
||||
import { onDestroy, onMount } from 'svelte'
|
||||
import {
|
||||
ArrowPath,
|
||||
ChatBubbleBottomCenterText,
|
||||
Check,
|
||||
Icon,
|
||||
Language,
|
||||
Link,
|
||||
Photo,
|
||||
Plus,
|
||||
Sparkles,
|
||||
Tag,
|
||||
XMark,
|
||||
} from 'svelte-hero-icons/dist'
|
||||
|
||||
interface Props {
|
||||
edit?: boolean
|
||||
/**
|
||||
* The post to edit
|
||||
*/
|
||||
editingPost?: Post | undefined
|
||||
passedCommunity?: CommunityView
|
||||
passedData?: {
|
||||
community: CommunityView | null
|
||||
title: string
|
||||
body?: string
|
||||
image: FileList | null
|
||||
thumbnail?: string
|
||||
url?: string
|
||||
nsfw: boolean
|
||||
loading: boolean
|
||||
alt_text?: string
|
||||
language_id?: number | string
|
||||
flair_list: number[]
|
||||
}
|
||||
formtitle?: import('svelte').Snippet
|
||||
onsubmit?: (post: PostView) => void
|
||||
}
|
||||
|
||||
let {
|
||||
edit = false,
|
||||
editingPost = undefined,
|
||||
passedCommunity = undefined,
|
||||
passedData = {
|
||||
community: null,
|
||||
title: '',
|
||||
body: '',
|
||||
image: null,
|
||||
nsfw: false,
|
||||
loading: false,
|
||||
flair_list: [],
|
||||
},
|
||||
formtitle,
|
||||
onsubmit,
|
||||
}: Props = $props()
|
||||
|
||||
let data = $state(passedData)
|
||||
|
||||
// weird select menu language handling
|
||||
$effect(() => {
|
||||
if (data.language_id === '') data.language_id = undefined
|
||||
})
|
||||
|
||||
let saveDraft = edit ? false : true
|
||||
let communitySearch = $state(passedCommunity?.community.name ?? '')
|
||||
|
||||
onMount(async () => {
|
||||
if (editingPost) Object.assign(data, editingPost)
|
||||
|
||||
if (editingPost?.community_id && !data.community) {
|
||||
data.community = (
|
||||
await client().getCommunity({ id: editingPost.community_id })
|
||||
).community_view
|
||||
}
|
||||
|
||||
if (passedCommunity) {
|
||||
data.community = passedCommunity
|
||||
communitySearch = passedCommunity.community.name
|
||||
}
|
||||
})
|
||||
|
||||
onDestroy(() => {
|
||||
if (saveDraft) setSessionStorage('postDraft', data)
|
||||
})
|
||||
|
||||
async function submit() {
|
||||
clearErrorScope('post-form')
|
||||
if (!data.community && !edit) {
|
||||
pushError({
|
||||
message: $t('toast.needCommunity'),
|
||||
scope: 'post-form',
|
||||
})
|
||||
return
|
||||
}
|
||||
if (data.url && data.url != '') {
|
||||
try {
|
||||
new URL(data.url)
|
||||
} catch {
|
||||
pushError({
|
||||
message: $t('toast.invalidURL'),
|
||||
scope: 'post-form',
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
data.loading = true
|
||||
|
||||
try {
|
||||
let post: PostResponse
|
||||
if (edit) {
|
||||
if (!editingPost) {
|
||||
throw new Error('Post is being edited but editingPost is null')
|
||||
}
|
||||
|
||||
post = await client().editPost({
|
||||
name: data.title,
|
||||
body: data.body,
|
||||
url: data.url || undefined,
|
||||
post_id: editingPost.id,
|
||||
nsfw: data.nsfw,
|
||||
alt_text: data.alt_text,
|
||||
custom_thumbnail: data.thumbnail,
|
||||
language_id: data.language_id ? Number(data.language_id) : undefined,
|
||||
})
|
||||
|
||||
if (!post) throw new Error('Failed to edit post')
|
||||
} else {
|
||||
post = await client().createPost({
|
||||
community_id: data.community!.community.id,
|
||||
name: data.title,
|
||||
body: data.body,
|
||||
url: data.url || undefined,
|
||||
nsfw: data.nsfw,
|
||||
custom_thumbnail: data.thumbnail,
|
||||
alt_text: data.alt_text,
|
||||
language_id: data.language_id ? Number(data.language_id) : undefined,
|
||||
})
|
||||
|
||||
if (!post) throw new Error('Failed to upload post')
|
||||
|
||||
saveDraft = false
|
||||
}
|
||||
|
||||
const piefed = client()
|
||||
if (piefed.assignFlair) {
|
||||
await piefed.assignFlair({
|
||||
flair_id_list: data.flair_list,
|
||||
post_id: post.post_view.post.id,
|
||||
})
|
||||
}
|
||||
|
||||
onsubmit?.(post.post_view)
|
||||
} catch (err) {
|
||||
pushError({ message: errorMessage(err as string), scope: 'post-form' })
|
||||
data.loading = false
|
||||
}
|
||||
}
|
||||
|
||||
let uploadingImage = $state(false)
|
||||
|
||||
const generateTitle = async (url: string | undefined) => {
|
||||
if (!url) return
|
||||
generation.loading = true
|
||||
try {
|
||||
const res = await client().getSiteMetadata({
|
||||
url: url,
|
||||
})
|
||||
|
||||
// for backup
|
||||
const oldData = { ...data }
|
||||
|
||||
if (res.metadata.title) data.title = res.metadata.title
|
||||
if (res.metadata.description)
|
||||
data.body = res.metadata.description
|
||||
.split('\n')
|
||||
.map((l) => `> ${l}`)
|
||||
.join('\n')
|
||||
|
||||
toast({
|
||||
content: $t('toast.generatedTitle'),
|
||||
type: 'info',
|
||||
action: () => (data = oldData),
|
||||
duration: 15 * 1000,
|
||||
})
|
||||
} catch {
|
||||
pushError({
|
||||
message: $t('toast.failGenerateTitle'),
|
||||
scope: 'post-form',
|
||||
})
|
||||
}
|
||||
generation.loading = false
|
||||
}
|
||||
|
||||
const canGenerateTitle = (url: string | undefined) => {
|
||||
if (!url) return false
|
||||
try {
|
||||
new URL(url)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
let generation = $state({
|
||||
loading: false,
|
||||
generatable: false,
|
||||
title: '',
|
||||
})
|
||||
|
||||
$effect(() => {
|
||||
generation.generatable = canGenerateTitle(data.url)
|
||||
})
|
||||
</script>
|
||||
|
||||
{#if uploadingImage}
|
||||
{#await import('$lib/ui/form/ImageInputModal.svelte') then { default: UploadModal }}
|
||||
<UploadModal
|
||||
bind:open={uploadingImage}
|
||||
bind:imageUrl={() => '', (v) => (data.url = v)}
|
||||
/>
|
||||
{/await}
|
||||
{/if}
|
||||
|
||||
{#snippet altText()}
|
||||
<TextArea bind:value={data.alt_text} />
|
||||
{/snippet}
|
||||
|
||||
{#snippet flairs()}
|
||||
<Material color="uniform" class="flex flex-row gap-4 flex-wrap">
|
||||
{#if data.community?.flair_list}
|
||||
{#each data.community.flair_list as flair}
|
||||
{@const selected = data.flair_list?.some((i) => i == flair.id)}
|
||||
<button
|
||||
class="rounded-full cursor-pointer hover:brightness-100 badge-tag-color"
|
||||
style="--tag-color: {flair.background_color}; --tag-text-color: {flair.text_color};"
|
||||
onclick={() => {
|
||||
if (selected) {
|
||||
const index = data.flair_list.findIndex((i) => i == flair.id)
|
||||
if (index != -1) data.flair_list.splice(index, 1)
|
||||
} else data.flair_list.push(flair.id)
|
||||
}}
|
||||
>
|
||||
<Badge
|
||||
color={selected ? 'gray-subtle' : 'custom'}
|
||||
class="ring-white/20"
|
||||
>
|
||||
{#snippet icon()}
|
||||
<Icon src={selected ? Check : Plus} size="16" micro />
|
||||
{/snippet}
|
||||
{flair.flair_title}
|
||||
</Badge>
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</Material>
|
||||
{/snippet}
|
||||
|
||||
<form
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault()
|
||||
submit()
|
||||
}}
|
||||
class="flex flex-col gap-4 h-full"
|
||||
>
|
||||
{#if formtitle}{@render formtitle()}{:else}
|
||||
<Header class="font-bold text-xl">
|
||||
{edit ? $t('form.post.edit') : $t('form.post.create')}
|
||||
</Header>
|
||||
{/if}
|
||||
<ErrorContainer scope="post-form" />
|
||||
{#if !edit && data}
|
||||
{#if !data.community}
|
||||
<ObjectAutocomplete
|
||||
bind:q={communitySearch}
|
||||
listing_type="All"
|
||||
label={$t('form.post.community')}
|
||||
onselect={(e) => {
|
||||
const c = e
|
||||
if (!c) {
|
||||
data.community = null
|
||||
return
|
||||
}
|
||||
|
||||
communitySearch = ''
|
||||
|
||||
data.community = c
|
||||
}}
|
||||
/>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="font-medium text-sm">{$t('form.post.community')}</span>
|
||||
<Button
|
||||
class="w-full"
|
||||
onclick={() => (data.community = null)}
|
||||
alignment="left"
|
||||
size="sm"
|
||||
rounding="xl"
|
||||
>
|
||||
{#snippet prefix()}
|
||||
<Avatar
|
||||
url={data?.community?.community.icon}
|
||||
alt={data.community?.community.name}
|
||||
width={24}
|
||||
/>
|
||||
{/snippet}
|
||||
<div class="flex flex-col gap-0">
|
||||
<span class="text-sm">{data.community?.community.name}</span>
|
||||
<span class="text-[10px] leading-3">
|
||||
{new URL(data.community.community.actor_id).hostname}
|
||||
</span>
|
||||
</div>
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
<FreeTextInput
|
||||
required
|
||||
bind:value={data.title}
|
||||
placeholder={placeholders.get('post')}
|
||||
label={$t('form.post.title')}
|
||||
/>
|
||||
<MarkdownEditor
|
||||
label={$t('form.post.body')}
|
||||
bind:value={data.body}
|
||||
placeholder={placeholders.get('body')}
|
||||
previewButton
|
||||
/>
|
||||
{#if data.url !== undefined}
|
||||
<div class="flex flex-col gap-2">
|
||||
<TextInput
|
||||
label={$t('form.post.url')}
|
||||
bind:value={data.url}
|
||||
placeholder={placeholders.get('url')}
|
||||
class="w-full"
|
||||
/>
|
||||
<div class="flex items-center gap-2 actions">
|
||||
{#if data.url}
|
||||
<Button
|
||||
onclick={() =>
|
||||
modal({ title: $t('form.post.altText'), snippet: altText })}
|
||||
rounding="pill"
|
||||
size="sm"
|
||||
color={data.alt_text ? 'primary' : 'ghost'}
|
||||
class="text-xs"
|
||||
icon={ChatBubbleBottomCenterText}
|
||||
>
|
||||
{$t('form.post.altText')}
|
||||
</Button>
|
||||
{/if}
|
||||
<Button
|
||||
onclick={() => (uploadingImage = !uploadingImage)}
|
||||
rounding="pill"
|
||||
size="sm"
|
||||
color="ghost"
|
||||
class="text-xs"
|
||||
icon={Photo}
|
||||
>
|
||||
{$t('form.post.uploadImage')}
|
||||
</Button>
|
||||
{#if generation.generatable}
|
||||
<Button
|
||||
onclick={() => generateTitle(data.url)}
|
||||
loading={generation.loading}
|
||||
rounding="pill"
|
||||
size="sm"
|
||||
color="ghost"
|
||||
class="text-xs"
|
||||
icon={Sparkles}
|
||||
>
|
||||
{$t('form.post.generateTitle')}
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="flex flex-row gap-2 flex-wrap">
|
||||
{#if data.url === undefined}
|
||||
<Button
|
||||
onclick={async () => {
|
||||
data.url = ''
|
||||
try {
|
||||
const url = new URL(await navigator.clipboard.readText())
|
||||
|
||||
data.url = url.toString()
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
}}
|
||||
size="sm"
|
||||
rounding="pill"
|
||||
icon={Link}
|
||||
>
|
||||
{$t('form.post.addUrl')}
|
||||
</Button>
|
||||
<Button
|
||||
onclick={() => {
|
||||
data.url = ''
|
||||
uploadingImage = true
|
||||
}}
|
||||
size="sm"
|
||||
rounding="pill"
|
||||
icon={Photo}
|
||||
>
|
||||
{$t('form.post.uploadImage')}
|
||||
</Button>
|
||||
{/if}
|
||||
{#if data.language_id === undefined}
|
||||
<Button
|
||||
size="sm"
|
||||
rounding="pill"
|
||||
onclick={() => (data.language_id = 0)}
|
||||
icon={Language}
|
||||
>
|
||||
{$t('form.post.setLanguage')}
|
||||
</Button>
|
||||
{/if}
|
||||
{#if (data.community?.flair_list?.length ?? 0) > 0}
|
||||
<Button
|
||||
onclick={() => modal({ title: $t('form.post.flair'), snippet: flairs })}
|
||||
size="sm"
|
||||
rounding="pill"
|
||||
icon={Tag}
|
||||
color={(data.flair_list?.length ?? 0) > 0 ? 'primary' : 'secondary'}
|
||||
>
|
||||
{$t('form.post.flair')}
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
<Switch bind:checked={data.nsfw}>{$t('form.post.nsfw')}</Switch>
|
||||
{#if data.language_id !== undefined}
|
||||
{#if site.data}
|
||||
<Select
|
||||
class="w-max"
|
||||
label={$t('settings.app.lang.title')}
|
||||
bind:value={data.language_id}
|
||||
>
|
||||
<Option value={undefined}>
|
||||
<Icon src={XMark} size="16" micro />
|
||||
{$t('form.post.unset')}
|
||||
</Option>
|
||||
{#each site.data?.all_languages as language}
|
||||
<Option value={language.id.toString()}>{language.name}</Option>
|
||||
{/each}
|
||||
</Select>
|
||||
{:else}
|
||||
<div style="height: 58px;">
|
||||
<Spinner width={24} />
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
<div class="mt-auto"></div>
|
||||
<div class="flex flex-row items-center gap-2 w-full">
|
||||
<Button
|
||||
submit
|
||||
color="primary"
|
||||
loading={data.loading}
|
||||
size="lg"
|
||||
disabled={data.loading}
|
||||
class="flex-1"
|
||||
>
|
||||
{$t('form.submit')}
|
||||
</Button>
|
||||
|
||||
{#if !edit}
|
||||
<Button
|
||||
onclick={() => {
|
||||
toast({ content: $t('toast.restoredFromDraft') })
|
||||
const draft = getSessionStorage('postDraft')
|
||||
if (draft && !edit) {
|
||||
draft.loading = false
|
||||
data = draft
|
||||
}
|
||||
}}
|
||||
size="square-lg"
|
||||
disabled={!getSessionStorage('postDraft')}
|
||||
title="Restore From Draft"
|
||||
>
|
||||
<Icon src={ArrowPath} size="16" mini />
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</form>
|
||||
@@ -30,6 +30,7 @@
|
||||
ShieldCheck,
|
||||
} from 'svelte-hero-icons/dist'
|
||||
import { PostVote } from '..'
|
||||
import { PostFormState } from '../form/postform.svelte'
|
||||
import { postLink } from '../helpers'
|
||||
|
||||
let saving = $state(false)
|
||||
@@ -76,32 +77,21 @@
|
||||
{#snippet customTitle()}
|
||||
<h1 class="text-2xl font-bold">{$t('form.edit')}</h1>
|
||||
{/snippet}
|
||||
{#await import('../PostForm.svelte')}
|
||||
{#await import('../form/PostForm.svelte')}
|
||||
<div class="mx-auto h-96 flex justify-center items-center">
|
||||
<Spinner width={32} />
|
||||
</div>
|
||||
{:then { default: PostForm }}
|
||||
<PostForm
|
||||
edit
|
||||
editingPost={post.post}
|
||||
editPost={post.post.id}
|
||||
onsubmit={(e) => {
|
||||
editing = false
|
||||
post = e
|
||||
onedit?.(e)
|
||||
}}
|
||||
passedData={{
|
||||
body: post.post.body,
|
||||
title: post.post.name,
|
||||
community: null,
|
||||
flair_list: post.flair_list?.map((i) => i.id) ?? [],
|
||||
image: null,
|
||||
loading: false,
|
||||
nsfw: post.post.nsfw,
|
||||
}}
|
||||
init={new PostFormState({ ...post.post })}
|
||||
>
|
||||
{#snippet formtitle()}
|
||||
<!-- Have the title not exist at all -->
|
||||
{/snippet}
|
||||
{#snippet title()}{/snippet}
|
||||
</PostForm>
|
||||
{/await}
|
||||
</Modal>
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation'
|
||||
import { client } from '$lib/api/client.svelte'
|
||||
import { PiefedClient } from '$lib/api/piefed/adapter'
|
||||
import type { PostView } from '$lib/api/types'
|
||||
import { profile } from '$lib/app/auth.svelte'
|
||||
import { t } from '$lib/app/i18n'
|
||||
import { setSessionStorage } from '$lib/app/session'
|
||||
import { settings } from '$lib/app/settings.svelte'
|
||||
import { deleteItem, markAsRead } from '$lib/feature/legacy/contentview'
|
||||
import { report } from '$lib/feature/moderation/moderation'
|
||||
@@ -19,6 +17,7 @@
|
||||
Trash,
|
||||
XMark,
|
||||
} from 'svelte-hero-icons/dist'
|
||||
import type { PostFormInit } from '../form/postform.svelte'
|
||||
import { hidePost } from '../helpers'
|
||||
|
||||
interface Props {
|
||||
@@ -50,8 +49,8 @@
|
||||
{/if}
|
||||
{#if profile.current?.jwt}
|
||||
<MenuButton
|
||||
onclick={() => {
|
||||
setSessionStorage('postDraft', {
|
||||
href="/create/post?crosspost={btoa(
|
||||
JSON.stringify({
|
||||
body: `${
|
||||
settings.crosspostOriginalLink
|
||||
? `cross-posted from: ${post.post.ap_id}`
|
||||
@@ -59,16 +58,11 @@
|
||||
}\n${
|
||||
post.post.body ? '>' + post.post.body.split('\n').join('\n> ') : ''
|
||||
}`,
|
||||
name: post.post.name,
|
||||
url: post.post.url,
|
||||
title: post.post.name,
|
||||
loading: false,
|
||||
nsfw: post.post.nsfw,
|
||||
community: null,
|
||||
image: null,
|
||||
})
|
||||
|
||||
goto('/create/post?crosspost=true')
|
||||
}}
|
||||
} as PostFormInit),
|
||||
)}"
|
||||
icon={ArrowTopRightOnSquare}
|
||||
>
|
||||
{$t('post.actions.more.crosspost')}
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
<script lang="ts">
|
||||
import { client, site } from '$lib/api/client.svelte'
|
||||
import { PiefedClient } from '$lib/api/piefed/adapter'
|
||||
import type { PostView } from '$lib/api/types'
|
||||
import { errorMessage } from '$lib/app/error'
|
||||
import { t } from '$lib/app/i18n'
|
||||
import MarkdownEditor from '$lib/app/markdown/MarkdownEditor.svelte'
|
||||
import { placeholders } from '$lib/app/util.svelte'
|
||||
import FreeTextInput from '$lib/ui/form/FreeTextInput.svelte'
|
||||
import ObjectAutocomplete from '$lib/ui/form/ObjectAutocomplete.svelte'
|
||||
import Avatar from '$lib/ui/generic/Avatar.svelte'
|
||||
import ErrorContainer, { pushError } from '$lib/ui/info/ErrorContainer.svelte'
|
||||
import { Header } from '$lib/ui/layout'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
Label,
|
||||
Material,
|
||||
modal,
|
||||
Option,
|
||||
Select,
|
||||
Spinner,
|
||||
Switch,
|
||||
TextArea,
|
||||
TextInput,
|
||||
TextLoader,
|
||||
} from 'mono-svelte'
|
||||
import type { Snippet } from 'svelte'
|
||||
import {
|
||||
ChatBubbleBottomCenterText,
|
||||
Check,
|
||||
Icon,
|
||||
Language,
|
||||
Link,
|
||||
Photo,
|
||||
Plus,
|
||||
Sparkles,
|
||||
XMark,
|
||||
} from 'svelte-hero-icons/dist'
|
||||
import { autofillPost, PostFormState } from './postform.svelte'
|
||||
|
||||
interface Props {
|
||||
editPost?: number
|
||||
init?: PostFormState
|
||||
title?: Snippet
|
||||
onsubmit?: (post: PostView) => void
|
||||
}
|
||||
|
||||
let { editPost, init, title, onsubmit }: Props = $props()
|
||||
|
||||
let form = $state<PostFormState>(init ?? new PostFormState())
|
||||
|
||||
let extendedCommunity = $derived.by(() => {
|
||||
const api = client()
|
||||
if (!(api instanceof PiefedClient)) return undefined
|
||||
|
||||
if (form.community?.id) {
|
||||
return api.getCommunity({ id: form.community.id })
|
||||
} else return undefined
|
||||
})
|
||||
|
||||
let loading = $state<boolean>(false)
|
||||
let uploadImage = $state(false)
|
||||
</script>
|
||||
|
||||
{#if uploadImage}
|
||||
{#await import('$lib/ui/form/ImageInputModal.svelte') then { default: UploadModal }}
|
||||
<UploadModal
|
||||
bind:open={uploadImage}
|
||||
bind:imageUrl={() => '', (v) => (form.url = v)}
|
||||
/>
|
||||
{/await}
|
||||
{/if}
|
||||
|
||||
{#snippet altText()}
|
||||
<TextArea bind:value={form.altText} />
|
||||
{/snippet}
|
||||
|
||||
{#snippet flairs()}
|
||||
<Material color="uniform" class="flex flex-row gap-4 flex-wrap">
|
||||
{#await extendedCommunity}
|
||||
<div class="w-full h-full grid place-items-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
{:then communityView}
|
||||
{#each communityView?.community_view.flair_list ?? [] as flair}
|
||||
{@const selected = form.flairList?.some((i) => i.id == flair.id)}
|
||||
<button
|
||||
class="rounded-full cursor-pointer hover:brightness-100 badge-tag-color"
|
||||
style="--tag-color: {flair.background_color}; --tag-text-color: {flair.text_color};"
|
||||
onclick={() => {
|
||||
if (selected) {
|
||||
const index = form.flairList.findIndex((i) => i.id == flair.id)
|
||||
if (index != -1) form.flairList.splice(index, 1)
|
||||
} else form.flairList.push(flair)
|
||||
}}
|
||||
>
|
||||
<Badge
|
||||
color={selected ? 'gray-subtle' : 'custom'}
|
||||
class="ring-white/20"
|
||||
>
|
||||
{#snippet icon()}
|
||||
<Icon src={selected ? Check : Plus} size="16" micro />
|
||||
{/snippet}
|
||||
{flair.flair_title}
|
||||
</Badge>
|
||||
</button>
|
||||
{/each}
|
||||
{/await}
|
||||
</Material>
|
||||
{/snippet}
|
||||
|
||||
{#snippet autofillPostModal()}
|
||||
<svelte:boundary>
|
||||
{#if form.url}
|
||||
{#await autofillPost(new URL(form.url))}
|
||||
<div class="w-full h-64 grid place-items-center">
|
||||
<TextLoader>
|
||||
{$t('form.post.fetching')}
|
||||
</TextLoader>
|
||||
</div>
|
||||
{:then url}
|
||||
<Material color="info" class="space-y-2">
|
||||
<h2 class="text-xl font-display font-medium">{url.title}</h2>
|
||||
<p>{url.body ?? '...'}</p>
|
||||
</Material>
|
||||
<Button
|
||||
size="lg"
|
||||
color="primary"
|
||||
onclick={() => {
|
||||
form.title = url.title ?? form.title
|
||||
form.body = url.body ?? form.body
|
||||
history.back()
|
||||
}}
|
||||
>
|
||||
{$t('form.submit')}
|
||||
</Button>
|
||||
{:catch err}
|
||||
<ErrorContainer scope="-1" message={err} />
|
||||
{/await}
|
||||
{/if}
|
||||
</svelte:boundary>
|
||||
{/snippet}
|
||||
|
||||
<form
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault()
|
||||
loading = true
|
||||
form
|
||||
.submit(editPost)
|
||||
.then(onsubmit)
|
||||
.catch((err) =>
|
||||
pushError({ message: errorMessage(err as string), scope: 'post-form' }),
|
||||
)
|
||||
.then(() => (loading = false))
|
||||
}}
|
||||
class="flex flex-col gap-4 h-full"
|
||||
>
|
||||
{#if title}
|
||||
{@render title()}
|
||||
{:else}
|
||||
<Header class="font-bold text-xl">
|
||||
{editPost ? $t('form.post.edit') : $t('form.post.create')}
|
||||
</Header>
|
||||
{/if}
|
||||
<ErrorContainer scope="post-form" />
|
||||
{#if !editPost}
|
||||
{#if !form.community}
|
||||
<ObjectAutocomplete
|
||||
listing_type="All"
|
||||
label={$t('form.post.community')}
|
||||
onselect={(i) => {
|
||||
form.community = i.community
|
||||
}}
|
||||
required
|
||||
/>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-1">
|
||||
<Label>{$t('form.post.community')}</Label>
|
||||
<Button
|
||||
class="w-full"
|
||||
onclick={() => (form.community = undefined)}
|
||||
alignment="left"
|
||||
size="sm"
|
||||
rounding="xl"
|
||||
>
|
||||
{#snippet prefix()}
|
||||
<Avatar
|
||||
url={form.community?.icon}
|
||||
alt={form.community?.name}
|
||||
width={24}
|
||||
/>
|
||||
{/snippet}
|
||||
<div class="flex flex-col gap-0">
|
||||
<span class="text-sm">{form.community.name}</span>
|
||||
<span class="text-[10px] leading-3">
|
||||
{new URL(form.community?.actor_id).hostname}
|
||||
</span>
|
||||
</div>
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<FreeTextInput
|
||||
required
|
||||
bind:value={form.title}
|
||||
placeholder={placeholders.get('post')}
|
||||
label={$t('form.post.title')}
|
||||
/>
|
||||
<MarkdownEditor
|
||||
label={$t('form.post.body')}
|
||||
bind:value={form.body}
|
||||
placeholder={placeholders.get('body')}
|
||||
previewButton
|
||||
/>
|
||||
|
||||
{#if form.url !== undefined}
|
||||
<TextInput
|
||||
label={$t('form.post.url')}
|
||||
bind:value={form.url}
|
||||
placeholder={placeholders.get('url')}
|
||||
>
|
||||
{#snippet suffix()}
|
||||
<Button
|
||||
color="none"
|
||||
rounding="none"
|
||||
class="h-full border-l border-slate-200 dark:border-zinc-800 aspect-square hover:bg-slate-50 hover:dark:bg-zinc-900 rounded-[inherit]"
|
||||
size="custom"
|
||||
disabled={!form.url || !URL.canParse(form.url)}
|
||||
icon={Sparkles}
|
||||
aria-label={$t('form.post.generateTitle')}
|
||||
onclick={() =>
|
||||
modal({
|
||||
title: $t('form.post.generateTitle'),
|
||||
snippet: autofillPostModal,
|
||||
actions: [],
|
||||
})}
|
||||
/>
|
||||
{/snippet}
|
||||
</TextInput>
|
||||
{/if}
|
||||
|
||||
<div class="flex flex-row flex-wrap gap-2">
|
||||
<ButtonGroup
|
||||
orientation="horizontal"
|
||||
class="flex flex-row flex-wrap w-full"
|
||||
>
|
||||
<Button
|
||||
onclick={() => (form.url = '')}
|
||||
disabled={form.url !== undefined}
|
||||
icon={Link}
|
||||
>
|
||||
{$t('form.post.addUrl')}
|
||||
</Button>
|
||||
<Button
|
||||
onclick={() => {
|
||||
uploadImage = !uploadImage
|
||||
}}
|
||||
icon={Photo}
|
||||
>
|
||||
{$t('form.post.uploadImage')}
|
||||
</Button>
|
||||
{#if form.url && URL.canParse(form.url)}
|
||||
<Button
|
||||
class="animate-pop-in"
|
||||
color={(form.altText ?? '') != '' ? 'primary' : 'secondary'}
|
||||
onclick={() =>
|
||||
modal({ title: $t('form.post.altText'), snippet: altText })}
|
||||
icon={ChatBubbleBottomCenterText}
|
||||
>
|
||||
{$t('form.post.altText')}
|
||||
</Button>
|
||||
{/if}
|
||||
{#if form.language === undefined}
|
||||
<Button
|
||||
class="animate-pop-in"
|
||||
onclick={() => (form.language = '')}
|
||||
icon={Language}
|
||||
>
|
||||
{$t('form.post.setLanguage')}
|
||||
</Button>
|
||||
{/if}
|
||||
{#await extendedCommunity then communityView}
|
||||
{#if (communityView?.community_view.flair_list?.length || 0) > 0}
|
||||
<Button
|
||||
color={form.flairList.length > 0 ? 'primary' : 'secondary'}
|
||||
class="animate-pop-in"
|
||||
onclick={() =>
|
||||
modal({ title: $t('form.post.flair'), snippet: flairs })}
|
||||
icon={ChatBubbleBottomCenterText}
|
||||
>
|
||||
{$t('form.post.flair')}
|
||||
</Button>
|
||||
{/if}
|
||||
{/await}
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
|
||||
{#if form.language !== undefined}
|
||||
{#if site.data}
|
||||
<Select
|
||||
class="w-max"
|
||||
label={$t('settings.app.lang.title')}
|
||||
bind:value={
|
||||
() => form.language,
|
||||
(v) => {
|
||||
if (v == '') form.language = undefined
|
||||
else form.language = v
|
||||
}
|
||||
}
|
||||
>
|
||||
<Option value="">
|
||||
<Icon src={XMark} size="16" micro />
|
||||
{$t('form.post.unset')}
|
||||
</Option>
|
||||
{#each site.data?.all_languages as language}
|
||||
<Option value={language.id.toString()}>{language.name}</Option>
|
||||
{/each}
|
||||
</Select>
|
||||
{:else}
|
||||
<div style="height: 58px;">
|
||||
<Spinner width={24} />
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<Switch bind:checked={form.nsfw}>{$t('form.post.nsfw')}</Switch>
|
||||
|
||||
<Button submit color="primary" {loading} size="lg" class="mt-auto">
|
||||
{$t('form.submit')}
|
||||
</Button>
|
||||
</form>
|
||||
@@ -0,0 +1,105 @@
|
||||
import { client } from '$lib/api/client.svelte'
|
||||
import { PiefedClient } from '$lib/api/piefed/adapter'
|
||||
import type { Community, CommunityFlair, PostView } from '$lib/api/types'
|
||||
|
||||
export type PostFormInit = {
|
||||
community?: Community
|
||||
name?: string
|
||||
body?: string
|
||||
url?: string
|
||||
nsfw?: boolean
|
||||
alt_text?: string
|
||||
thumbnail?: string
|
||||
language_id?: number
|
||||
flair_list?: CommunityFlair[]
|
||||
}
|
||||
|
||||
export class PostFormState {
|
||||
community?: Community
|
||||
title: string
|
||||
body?: string
|
||||
url?: string
|
||||
nsfw: boolean
|
||||
altText?: string
|
||||
thumbnail?: string
|
||||
language?: string
|
||||
flairList: CommunityFlair[]
|
||||
|
||||
constructor(post?: PostFormInit) {
|
||||
this.community = $state(post?.community)
|
||||
this.title = $state(post?.name ?? '')
|
||||
this.body = $state(post?.body)
|
||||
this.url = $state(post?.url)
|
||||
this.nsfw = $state(post?.nsfw ?? false)
|
||||
this.altText = $state(post?.alt_text)
|
||||
this.language = $state(post?.language_id?.toString())
|
||||
this.flairList = $state(post?.flair_list ?? [])
|
||||
}
|
||||
|
||||
validate(mode: 'edit' | 'create'): boolean {
|
||||
if (mode == 'create' && !this.community) return false
|
||||
if (this.url && !URL.canParse(this.url)) return false
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
async submit(postId?: number): Promise<PostView> {
|
||||
if (!this.validate(postId ? 'edit' : 'create'))
|
||||
throw new Error('failed validation')
|
||||
|
||||
const api = client()
|
||||
|
||||
let res: PostView
|
||||
if (postId) {
|
||||
res = (
|
||||
await api.editPost({
|
||||
post_id: postId,
|
||||
name: this.title,
|
||||
body: this.body,
|
||||
url: this.url,
|
||||
nsfw: this.nsfw,
|
||||
alt_text: this.altText,
|
||||
custom_thumbnail: this.thumbnail,
|
||||
language_id: Number(this.language) || undefined,
|
||||
})
|
||||
).post_view
|
||||
} else {
|
||||
res = (
|
||||
await api.createPost({
|
||||
community_id: this.community!.id,
|
||||
name: this.title,
|
||||
body: this.body,
|
||||
url: this.url,
|
||||
alt_text: this.altText,
|
||||
custom_thumbnail: this.thumbnail,
|
||||
nsfw: this.nsfw,
|
||||
language_id: Number(this.language) || undefined,
|
||||
})
|
||||
).post_view
|
||||
}
|
||||
|
||||
if (api instanceof PiefedClient) {
|
||||
const flairRes = await api.assignFlair({
|
||||
flair_id_list: this.flairList.map((i) => i.id),
|
||||
post_id: res.post.id,
|
||||
})
|
||||
|
||||
res.flair_list = flairRes.flair_list
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
export async function autofillPost(
|
||||
url: URL,
|
||||
): Promise<{ title?: string; body?: string }> {
|
||||
const res = await client().getSiteMetadata({
|
||||
url: url.toString(),
|
||||
})
|
||||
|
||||
return {
|
||||
title: res.metadata.title,
|
||||
body: res.metadata.description,
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<form class="space-y-2">
|
||||
<form class="space-y-2" onsubmit={() => castVote(selected!)}>
|
||||
<CommonList class="">
|
||||
{#each options.toSorted((a, b) => a.sort_order - b.sort_order) as choice}
|
||||
{@const active = selected == choice.id}
|
||||
@@ -125,9 +125,10 @@
|
||||
{#if (selected && canVote) || loading}
|
||||
<Button
|
||||
class="w-24"
|
||||
onclick={() => castVote(selected!)}
|
||||
color="primary"
|
||||
submit
|
||||
{loading}
|
||||
disabled={loading}
|
||||
>
|
||||
{$t('form.submit')}
|
||||
</Button>
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
placeholder?: string
|
||||
onselect?: (item: any) => void
|
||||
label?: string
|
||||
required?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -24,6 +25,7 @@
|
||||
instance = undefined,
|
||||
listing_type = 'Subscribed',
|
||||
showWhenEmpty = false,
|
||||
required,
|
||||
...rest
|
||||
}: Props = $props()
|
||||
|
||||
@@ -49,6 +51,7 @@
|
||||
extractName={(c) =>
|
||||
`${c.community.name}@${new URL(c.community.actor_id).hostname}`}
|
||||
bind:query={q}
|
||||
{required}
|
||||
{...rest}
|
||||
>
|
||||
{#snippet noresults()}
|
||||
|
||||
@@ -26,17 +26,18 @@
|
||||
})
|
||||
interface Props {
|
||||
scope?: string | undefined | null
|
||||
message?: string
|
||||
class?: string
|
||||
}
|
||||
|
||||
let { scope = undefined, class: clazz = '' }: Props = $props()
|
||||
let { scope, message, class: clazz = '' }: Props = $props()
|
||||
|
||||
let scopedErrors = $derived(
|
||||
errors.filter((e) => e.scope == scope || e.scope == 'global'),
|
||||
)
|
||||
</script>
|
||||
|
||||
{#if scopedErrors.length > 0}
|
||||
{#if scopedErrors.length > 0 || message}
|
||||
<div
|
||||
class={['flex flex-col gap-4', clazz]}
|
||||
in:slide={{ duration: 400, easing: expoOut }}
|
||||
@@ -59,6 +60,9 @@
|
||||
micro
|
||||
class="inline-block rounded-lg clear-both float-left mr-2"
|
||||
/>
|
||||
{#if message}
|
||||
{message}
|
||||
{/if}
|
||||
{#each scopedErrors as error}
|
||||
<p>{error.message}</p>
|
||||
{/each}
|
||||
|
||||
@@ -58,6 +58,7 @@
|
||||
xl: 'rounded-xl',
|
||||
lg: 'rounded-lg',
|
||||
md: 'rounded-md',
|
||||
inherit: 'rounded-[inherit]',
|
||||
none: '',
|
||||
}
|
||||
type ButtonRoundness = keyof typeof buttonRounding
|
||||
|
||||
@@ -35,16 +35,18 @@
|
||||
|
||||
.btn-group.btn-group-horizontal {
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
:global(*) {
|
||||
position: relative;
|
||||
&:first-child {
|
||||
border-radius: 24px 8px 8px 24px !important;
|
||||
}
|
||||
.btn-group.btn-group-horizontal :global(> *) {
|
||||
position: relative;
|
||||
border-radius: 8px 8px 8px 8px !important;
|
||||
|
||||
&:last-child {
|
||||
border-radius: 8px 24px 24px 8px !important;
|
||||
}
|
||||
&:first-child {
|
||||
border-radius: 24px 12px 12px 24px !important;
|
||||
}
|
||||
|
||||
&:last-child {
|
||||
border-radius: 12px 24px 24px 12px !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -101,6 +101,7 @@
|
||||
{disabled}
|
||||
bind:value
|
||||
bind:this={element}
|
||||
{required}
|
||||
{...rest}
|
||||
class={[
|
||||
sizeClass[size],
|
||||
@@ -118,7 +119,7 @@
|
||||
{#if suffix}
|
||||
<div
|
||||
class={[
|
||||
'rounded-xl rounded-l-none text-slate-600 dark:text-zinc-400',
|
||||
'rounded-xl rounded-l-none text-slate-600 dark:text-zinc-400 h-full',
|
||||
inlineAffixes && 'bg-white dark:bg-zinc-900 pl-0',
|
||||
]}
|
||||
>
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
bind:open={$shownModal}
|
||||
>
|
||||
{#if $shownModal.snippet}
|
||||
{@render $shownModal.snippet()}
|
||||
{@render $shownModal.snippet?.()}
|
||||
{/if}
|
||||
{#if $shownModal.body}
|
||||
<p>{$shownModal.body}</p>
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
select?: (item: T) => void
|
||||
input?: import('svelte').Snippet
|
||||
noresults?: import('svelte').Snippet
|
||||
required?: boolean
|
||||
children?: import('svelte').Snippet<
|
||||
[
|
||||
{
|
||||
@@ -47,6 +48,7 @@
|
||||
query = extractName(item)
|
||||
onselect?.(item)
|
||||
},
|
||||
required,
|
||||
input,
|
||||
noresults,
|
||||
children,
|
||||
@@ -82,6 +84,7 @@
|
||||
oninput?.(e)
|
||||
debounceFunc()
|
||||
}}
|
||||
{required}
|
||||
{...rest}
|
||||
inlineAffixes
|
||||
>
|
||||
|
||||
Reference in new issue
Block a user