Merge pull request #683 from Xyphyn/feat/piefed-polls

feat: add piefed polls, events, user notes
This commit is contained in:
xylight authored and GitHub committed 2025-11-15 22:13:31 -08:00
commit e0e9ca77cd
36 files changed
+2044 -721

No files matched your search

+1 -1
View File
@@ -66,7 +66,7 @@
],
}
})
let type = $derived(mediaType(post.post.url))
let type = $derived(mediaType(post.post))
let rule = $derived(getTagRule(tags.tags))
let hideTitle = $derived(
settings.posts.deduplicateEmbed &&
-517
View File
@@ -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,24 @@
{#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({
type: post.post.poll ? 'poll' : post.post.event ? 'event' : 'normal',
...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')}
+1 -1
View File
@@ -203,7 +203,7 @@
onhide={() => {
posts = posts.toSpliced(row, 1)
}}
class="px-3 sm:px-6 hover:bg-slate-100/50 hover:dark:bg-zinc-900/50 transition-colors"
class="px-3 sm:px-6 hover:bg-slate-100/30 hover:dark:bg-zinc-900/30 transition-colors"
></Post>
</li>
{/snippet}
+443
View File
@@ -0,0 +1,443 @@
<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 { settings } from '$lib/app/settings.svelte'
import { placeholders } from '$lib/app/util.svelte'
import Duration from '$lib/ui/form/Duration.svelte'
import FreeTextInput from '$lib/ui/form/FreeTextInput.svelte'
import ObjectAutocomplete from '$lib/ui/form/ObjectAutocomplete.svelte'
import MultiSelect from '$lib/ui/form/Switch.svelte'
import Avatar from '$lib/ui/generic/Avatar.svelte'
import ErrorContainer, { pushError } from '$lib/ui/info/ErrorContainer.svelte'
import { CommonList, Header } from '$lib/ui/layout'
import EndPlaceholder from '$lib/ui/layout/EndPlaceholder.svelte'
import { publishedToDate } from '$lib/ui/util/date'
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,
Tag,
Trash,
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({ type: 'normal' }),
)
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 client() instanceof PiefedClient}
<div class="mb-3">
<MultiSelect
options={['normal', 'poll']}
optionNames={[
$t('form.post.types.normal'),
$t('form.post.types.poll'),
$t('form.post.types.event'),
]}
bind:selected={form.type}
/>
</div>
{/if}
{#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')}
class="font-display font-medium text-2xl"
/>
<MarkdownEditor
label={$t('form.post.body')}
bind:value={form.body}
placeholder={placeholders.get('body')}
previewButton
/>
{#if form.type == 'normal' && 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}
{#if form.type == 'poll' && form.poll}
<div>
<Label>{$t('post.poll.choices')}</Label>
<CommonList>
<!--eslint-disable-next-line @typescript-eslint/no-unused-vars-->
{#each form.poll.choices as _, index}
<li class="px-4 py-1 flex flex-row items-center xs">
<div class="p-0! font-medium flex-1">
<FreeTextInput
bind:value={form.poll.choices[index].choice_text}
class="w-full"
/>
</div>
<div>
<Button
onclick={() => form.poll?.choices.splice(index, 1)}
size="square-md"
aria-label={$t('post.actions.more.delete')}
>
<Icon src={Trash} size="16" mini />
</Button>
</div>
</li>
{/each}
<li class="xs">
<button
onclick={() =>
form.poll?.choices.push({
choice_text: `Option ${form.poll?.choices.length + 1}`,
id: Math.max(...form.poll.choices.map((i) => i.id)) + 1,
num_votes: 0,
sort_order: 2,
})}
type="button"
class="font-medium w-full px-4 py-2! flex flex-row items-center gap-1 justify-center cursor-pointer"
>
<Icon src={Plus} size="16" micro />
{$t('common.add')}
</button>
</li>
</CommonList>
</div>
<EndPlaceholder margin="bottom-lg">
<Select label={$t('post.poll.mode')} bind:value={form.poll!.mode}>
<Option value="single">
{$t('post.poll.single')}
</Option>
<Option value="multiple">
{$t('post.poll.multiple')}
</Option>
</Select>
{#snippet action()}
{#if !editPost}
<Duration
bind:value={
() => {
return form.poll?.end_poll
? Math.floor(
Date.now() -
publishedToDate(form.poll?.end_poll).getTime(),
)
: Date.now() + 24 * 60 * 60
},
(v) => {
if (v == -1) form.poll!.end_poll = undefined
else
form.poll!.end_poll = new Date(
Date.now() + v * 1000,
).toISOString()
}
}
/>
{/if}
{/snippet}
</EndPlaceholder>
{#if settings.debugInfo}
{form.poll?.end_poll}
{/if}
{/if}
<div class="flex flex-row flex-wrap gap-2">
<ButtonGroup
orientation="horizontal"
class="flex flex-row flex-wrap w-full"
>
{#if form.type == 'normal'}
<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}
{#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={Tag}
>
{$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,144 @@
import { client } from '$lib/api/client.svelte'
import { PiefedClient } from '$lib/api/piefed/adapter'
import type {
Community,
CommunityFlair,
PostEvent,
PostPoll,
PostView,
} from '$lib/api/types'
export type PostFormInit = {
type?: 'normal' | 'poll' | 'event'
community?: Community
name?: string
body?: string
url?: string
nsfw?: boolean
alt_text?: string
thumbnail?: string
language_id?: number
poll?: PostPoll
event?: PostEvent
flair_list?: CommunityFlair[]
}
export class PostFormState {
type?: 'normal' | 'poll' | 'event'
community?: Community
title: string
body?: string
url?: string
nsfw: boolean
altText?: string
thumbnail?: string
language?: string
poll?: PostPoll
event?: PostEvent
flairList: CommunityFlair[]
constructor(post?: PostFormInit) {
this.type = $state(post?.type ?? 'normal')
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.poll = $state(
post?.poll ?? {
mode: 'single',
local_only: false,
choices: [
{
choice_text: 'Option 1',
id: 1,
num_votes: 0,
sort_order: 0,
},
{
choice_text: 'Option 2',
id: 2,
num_votes: 0,
sort_order: 1,
},
],
},
)
this.event = $state(post?.event)
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,
poll: this.type == 'poll' ? this.poll : undefined,
event: this.type == 'event' ? this.event : 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,
poll: this.type == 'poll' ? this.poll : undefined,
event: this.type == 'event' ? this.event : 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,
}
}
+20 -2
View File
@@ -70,11 +70,29 @@ export function postLink(post: Post) {
return `/post/${encodeURIComponent(profile.current.instance)}/${post.id}`
}
export type MediaType = 'video' | 'image' | 'iframe' | 'embed' | 'none'
export type MediaType =
| 'video'
| 'image'
| 'iframe'
| 'embed'
| 'poll'
| 'event'
| 'none'
export type IframeType = 'youtube' | 'video' | 'none'
export function mediaType(url?: string): MediaType {
export function mediaType(post?: Post | string): MediaType {
if (!post) return 'none'
const isPost = typeof post != 'string'
const url = isPost ? post.url : post
if (isPost) {
if (post.poll) return 'poll'
if (post.event) return 'event'
}
if (!url) return 'none'
try {
new URL(url)
} catch {
@@ -0,0 +1,91 @@
<script lang="ts">
import type { Post, PostEvent } from '$lib/api/types'
import { locale, t } from '$lib/app/i18n'
import Blobs from '$lib/ui/generic/Blobs.svelte'
import { publishedToDate } from '$lib/ui/util/date'
import RelativeDate from '$lib/ui/util/RelativeDate.svelte'
import { Material } from 'mono-svelte'
import {
Calendar,
Clock,
CurrencyDollar,
Icon,
MapPin,
} from 'svelte-hero-icons/dist'
interface Props {
post: Post & { event: PostEvent }
}
let { post }: Props = $props()
</script>
<div class="grid grid-cols-2 gap-4">
<Material
rounding="2xl"
color="info"
class="relative z-0 flex flex-col overflow-hidden col-span-2"
>
<div class="-m-4 mask-b-from-0 scale-125 -z-10">
<Blobs seed={post.name} />
</div>
<h3 class="font-display text-3xl tracking-tight">
{post.name}
</h3>
</Material>
{#if post.event.start}
{@const startDate = publishedToDate(post.event.start)}
<Material rounding="2xl" color="info" class="space-y-1">
<Icon src={Calendar} size="20" mini />
<h4 class="capitalize text-xl font-display">
<date>
{startDate.toLocaleDateString($locale, {
dateStyle: 'long',
})}
</date>
</h4>
<RelativeDate options={{ style: 'long' }} date={startDate} />
</Material>
<Material rounding="2xl" color="info" class="space-y-1">
<Icon src={Clock} size="20" mini />
<h4 class="capitalize text-xl font-display">
<time>
{startDate.toLocaleTimeString($locale, {
timeStyle: 'long',
})}
</time>
</h4>
<time>
{startDate.toLocaleTimeString($locale, {
timeZone: 'GMT',
timeStyle: 'long',
})}
</time>
</Material>
{/if}
{#if post.event.event_fee_amount}
<Material rounding="2xl" color="info" class="space-y-1">
<Icon src={CurrencyDollar} size="20" mini />
<h5 class="capitalize text-lg font-display">
{post.event.event_fee_amount}
{post.event.event_fee_currency ?? ''}
</h5>
</Material>
{/if}
{#if post.event.location && Object.keys(post.event.location).length > 0}
<Material rounding="2xl" color="info" class="space-y-1">
<Icon src={MapPin} size="20" mini />
<h4 class="capitalize text-xl font-display">
{$t('filter.location.label')}
</h4>
<dl class="space-y-2">
{#each Object.keys(post.event.location) as key}
<div class="flex flex-row justify-between flex-wrap">
<dt class="capitalize font-medium">{key}</dt>
<dd>{post.event.location[key]}</dd>
</div>
{/each}
</dl>
</Material>
{/if}
</div>
@@ -3,6 +3,8 @@
import { settings, type View } from '$lib/app/settings.svelte'
import { PostIframe, PostImage, PostLink } from '..'
import { iframeType, type MediaType } from '../helpers'
import PostEvent from './PostEvent.svelte'
import PostPoll from './PostPoll.svelte'
interface Props {
view?: View
@@ -40,6 +42,10 @@
title={post.name}
{...rest}
/>
{:else if type == 'poll' && post.poll && view == 'cozy'}
<PostPoll post={{ ...post, poll: post.poll! }} />
{:else if type == 'event' && post.event && view == 'cozy'}
<PostEvent post={{ ...post, event: post.event! }} />
{:else if type == 'embed' && post.url}
<PostLink
url={post.url}
@@ -5,11 +5,13 @@
import { showImage } from '$lib/ui/generic/ExpandableImage.svelte'
import { Button, modal } from 'mono-svelte'
import {
Calendar,
DocumentText,
ExclamationTriangle,
Icon,
Link,
Photo,
PresentationChartBar,
VideoCamera,
} from 'svelte-hero-icons/dist'
import { bestImageURL, postLink, type MediaType } from '../helpers'
@@ -109,21 +111,19 @@
</div>
{/if}
{:else}
{@const typeIconMap = new Map([
['embed', Link],
['iframe', VideoCamera],
['poll', PresentationChartBar],
['event', Calendar],
])}
<div
class={[
'bg-slate-100 dark:bg-zinc-900 w-full h-full rounded-xl grid place-items-center',
'text-slate-600 dark:text-zinc-400',
]}
>
<Icon
src={type == 'embed'
? Link
: type == 'iframe'
? VideoCamera
: DocumentText}
solid
size="32"
/>
<Icon src={typeIconMap.get(type) ?? DocumentText} solid size="32" />
</div>
{/if}
</div>
+217
View File
@@ -0,0 +1,217 @@
<script lang="ts">
import { client } from '$lib/api/client.svelte'
import { PiefedClient } from '$lib/api/piefed/adapter'
import type { Post, PostPoll } from '$lib/api/types'
import { errorMessage } from '$lib/app/error'
import { t } from '$lib/app/i18n'
import { CommonList } from '$lib/ui/layout'
import EndPlaceholder from '$lib/ui/layout/EndPlaceholder.svelte'
import { publishedToDate } from '$lib/ui/util/date'
import { formatRelativeDate } from '$lib/ui/util/RelativeDate.svelte'
import { Button, toast } from 'mono-svelte'
import { expoOut } from 'svelte/easing'
import { slide } from 'svelte/transition'
interface Props {
post: Post & { poll: PostPoll }
}
let { post }: Props = $props()
let selected = $state<number | number[]>()
let chosen = $state<number>()
let canVote = $state<boolean>(
!(
post.poll.end_poll &&
publishedToDate(post.poll.end_poll).getTime() < Date.now()
),
)
let options = $derived(
post.poll.choices.map((i) => ({
...i,
num_votes: chosen == i.id ? i.num_votes + 1 : i.num_votes,
})),
)
let totalVotes = $derived(options.reduce((a, b) => a + b.num_votes, 0))
let loading = $state(false)
async function castVote(id: number | number[]) {
try {
const api = client()
if (!(api instanceof PiefedClient)) throw new Error('unsupported')
loading = true
if (typeof id !== 'number') chosen = id[0]
else chosen = id
canVote = false
if (typeof id !== 'number') {
await Promise.all([
id.map((i) =>
api
.voteOnPoll({
post_id: post.id,
choice_id: i,
})
.catch((err) => {
throw err
}),
),
])
} else {
await api.voteOnPoll({
post_id: post.id,
choice_id: id,
})
}
} catch (err) {
toast({
content: errorMessage(err as string),
type: 'error',
})
chosen = undefined
canVote = true
} finally {
loading = false
}
}
</script>
<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 ||
(typeof selected !== 'number' && selected?.includes(choice.id))}
{@const percentage = Math.floor(
(choice.num_votes / totalVotes || 0) * 100,
)}
{@const multi = post.poll.mode != 'single'}
<li
class="relative z-10 overflow-hidden has-disabled:pointer-events-none"
role="progressbar"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow={percentage}
>
{#if chosen}
<div
in:slide={{ axis: 'x', duration: 500, easing: expoOut }}
class={[
'absolute inset-0 -z-10 p-0!',
active
? 'bg-primary-900/10 dark:bg-primary-100/10'
: 'bg-primary-900/5 dark:bg-primary-100/5',
]}
style="width: {percentage}%; transition: all 0.5s cubic-bezier(0.075, 0.82, 0.165, 1);"
></div>
{/if}
<label
class="px-4 py-2 w-full text-left flex flex-row gap-2 items-center"
>
{#if !multi}
<input
class="appearance-none absolute inset-0 cursor-pointer w-full h-full peer"
name="poll={post.id}"
value={choice.id}
bind:group={selected}
type="radio"
disabled={!canVote}
/>
{:else}
<input
class="appearance-none absolute inset-0 cursor-pointer w-full h-full peer"
name="poll={post.id}"
value={choice.id}
bind:group={selected}
type="checkbox"
disabled={!canVote}
/>
{/if}
<div
class={['choice-indicator', multi ? 'rounded-md' : 'rounded-full']}
>
<div></div>
</div>
<div class={['choice-text', 'text-slate-600 dark:text-zinc-400']}>
{choice.choice_text}
</div>
{#if chosen}
<div class="ml-auto">
{percentage}%
</div>
{/if}
</label>
</li>
{/each}
</CommonList>
<EndPlaceholder size="md" margin="bottom-sm">
{$t('post.poll.votes', { votes: totalVotes })}
{#snippet action()}
{#if (selected && canVote) || loading}
<Button
class="w-24"
color="primary"
submit
{loading}
disabled={loading}
>
{$t('form.submit')}
</Button>
{:else if post.poll.end_poll}
{$t('post.poll.results.ends', {
time: formatRelativeDate(publishedToDate(post.poll.end_poll), {}),
})}
{/if}
{/snippet}
</EndPlaceholder>
</form>
<style>
@reference '../../../../app.css';
input:checked ~ .choice-text {
font-weight: var(--font-weight-medium);
color: var(--color-primary-900);
@variant dark {
color: var(--color-primary-100);
}
}
.choice-indicator {
width: calc(var(--spacing) * 5);
height: calc(var(--spacing) * 5);
background: var(--color-slate-100);
display: inline-grid;
place-items: center;
@variant dark {
background: var(--color-zinc-800);
}
}
input:checked ~ .choice-indicator > div {
width: calc(var(--spacing) * 4);
height: calc(var(--spacing) * 4);
border-radius: inherit;
background: var(--color-primary-900);
@variant dark {
background: var(--color-primary-100);
}
}
li:has(label:focus-within) {
border: 1px solid --alpha(var(--color-primary-900) / 50%);
@variant dark {
border-color: --alpha(var(--color-primary-100) / 50%);
}
}
</style>
+5
View File
@@ -148,6 +148,11 @@
{user.flair}
</Badge>
{/if}
{#if user.note}
<Badge color="gray-subtle" class="px-1.5! py-0.5! whitespace-nowrap">
{user.note}
</Badge>
{/if}
{@render extraBadges?.()}
{/if}
</a>
+58
View File
@@ -0,0 +1,58 @@
<script lang="ts">
import { client } from '$lib/api/client.svelte'
import { errorMessage } from '$lib/app/error'
import { t } from '$lib/app/i18n'
import { Button, TextInput, toast } from 'mono-svelte'
interface Props {
note?: string
person: number
onsubmit?: (note: string | null) => void
}
let { note: passedNote = '', person, onsubmit }: Props = $props()
let note = $state(passedNote)
// man wtf is this
let loading = $state<boolean | null>(false)
async function submit(note: string | null) {
try {
loading = note ? true : null
if (!client().setNote) throw new Error('unsupported')
await client().setNote!({ person_id: person, note: note })
onsubmit?.(note)
} catch (err) {
toast({
content: errorMessage(err as string),
type: 'error',
})
}
loading = false
}
</script>
<form
onsubmit={(e) => {
e.preventDefault()
submit(note)
}}
class="contents"
>
<TextInput bind:value={note} label={$t('nav.commands.content')} required />
<div class="flex flex-row gap-2 *:flex-1">
<Button loading={loading === true} submit color="primary" size="lg">
{$t('form.submit')}
</Button>
<Button
onclick={() => submit(null)}
loading={loading === null}
color="danger"
size="lg"
>
{$t('common.remove')}
</Button>
</div>
</form>