impr: restructure src/lib

This commit is contained in:
Xylight committed 2025-09-24 17:12:19 -07:00
1 parent d85b889409
commit 75f907743e
376 files changed
+1000 -1033

No files matched your search

+199
View File
@@ -0,0 +1,199 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte'
import { publishedToDate } from '$comp/util/date.js'
import { settings, type View } from '$lib/settings.svelte.js'
import type { PostView } from '$lib/api/types'
import type { ClassValue } from 'svelte/elements'
import {
type Tag,
PostMeta,
PostActions,
PostMedia,
PostBody,
parseTags,
mediaType,
PostMediaCompact,
} from '.'
function getTagRule(tags: Tag[]): 'blur-sm' | 'hide' | undefined {
const tagContent = tags.map((t) => t.content.toLowerCase())
let rule: 'blur-sm' | 'hide' | undefined
if (settings.nsfwBlur && (post.post.nsfw || post.community.nsfw))
rule = 'blur-sm'
tagContent.forEach(() => {
if (rule == 'hide') return rule
})
return rule
}
interface Props {
post: PostView
actions?: boolean
hideCommunity?: boolean
view?: View
style?: string
class?: ClassValue
extraBadges?: import('svelte').Snippet
onhide?: (hide: boolean) => void
}
let {
post = $bindable(),
actions = true,
hideCommunity = false,
view = settings.view,
style = '',
class: clazz = '',
extraBadges,
onhide,
}: Props = $props()
let tags = $derived.by<{ title?: string; tags: Tag[] }>(() => {
const parsed = parseTags(post.post.name)
return {
title: parsed.title,
tags: [
...parsed.tags,
...(post.flair_list?.map((i) => ({
content: i.flair_title,
color: i.background_color,
icon: null,
type: 'flair' as 'flair' | 'custom',
textColor: i.text_color,
})) ?? []),
],
}
})
let type = $derived(mediaType(post.post.url))
let rule = $derived(getTagRule(tags.tags))
let hideTitle = $derived(
settings.posts.deduplicateEmbed &&
post.post.embed_title == post.post.name &&
view != 'compact' &&
type != 'iframe',
)
let badges = $derived({
deleted: post.post.deleted,
removed: post.post.removed,
locked: post.post.locked,
featured: post.post.featured_local || post.post.featured_community,
nsfw: post.post.nsfw || post.community.nsfw,
saved: post.saved,
admin: post.creator_is_admin,
moderator: post.creator_is_moderator,
})
</script>
<!--
@component
This is the sole component for displaying posts.
It adapts to all kinds of form factors for different contexts, such as feeds, full post view, and crosspost list.
-->
<article
class={[
'relative group/post',
settings.leftAlign && 'left-align',
view == 'compact' && 'py-3 list-type compact',
view == 'cozy' && 'py-5 flex flex-col gap-2',
clazz,
]}
id={post.post.id.toString()}
{style}
>
<PostMeta
community={post.community}
showCommunity={!hideCommunity}
user={post.creator}
published={publishedToDate(post.post.published)}
{badges}
subscribed={profile.current?.user?.follows
.map((c) => c.community.id)
.includes(post.community.id)
? 'Subscribed'
: 'NotSubscribed'}
id={post.post.id}
title={hideTitle ? undefined : tags?.title ? tags.title : post.post.name}
read={post.read}
style="grid-area: meta;"
edited={post.post.updated}
tags={tags?.tags}
postUrl={post.post.url}
{view}
{extraBadges}
/>
{#key post.post.url}
<div style="grid-area:embed;" class={{ contents: view == 'cozy' }}>
{#if rule != 'hide'}
<PostMedia
post={post.post}
blur={rule == 'blur-sm' ? true : undefined}
{view}
{type}
/>
{/if}
</div>
{#if view == 'compact'}
<PostMediaCompact
post={post.post}
{type}
class="{settings.leftAlign ? 'mr-3' : 'ml-3'} shrink no-list-margin"
style="grid-area: media;"
blur={rule == 'blur-sm' ? true : undefined}
{view}
/>
{/if}
{/key}
{#if post.post.body && !post.post.nsfw && view != 'compact'}
<PostBody
element="section"
body={post.post.body}
style="grid-area: body"
class="relative"
/>
{/if}
{#if actions}
<PostActions {onhide} bind:post style="grid-area: actions;" {view} />
{/if}
</article>
<style>
.list-type {
display: grid;
grid-template-areas: 'meta media' 'title media' 'body media' 'embed embed' 'actions actions';
grid-template-columns: minmax(0, 1fr) auto;
width: 100%;
height: 100%;
}
/* Swap media/item positions */
.list-type.left-align {
grid-template-areas: 'media meta' 'media title' 'media body' 'embed embed' 'actions actions';
grid-template-columns: auto minmax(0, 1fr);
}
/* Has media on the right for all of them */
@media (min-width: 480px) {
.list-type.compact {
grid-template-areas: 'meta media' 'title media' 'body media' 'embed media' 'actions media';
}
}
/* Swap above again */
@media (min-width: 480px) {
.list-type.compact.left-align {
grid-template-areas: 'media meta' 'media title' 'media body' 'media embed' 'media actions';
}
}
:global(.compact > *:not(.no-list-margin):not(:first-child)) {
margin-top: 0.3rem;
}
:global(.list-type:not(.compact) > *:not(.no-list-margin):not(:first-child)) {
margin-top: 0.5rem;
}
</style>
+76
View File
@@ -0,0 +1,76 @@
<script lang="ts">
import Markdown from '$lib/app/markdown/Markdown.svelte'
import { Button } from 'mono-svelte'
import { ChevronDown, Icon } from 'svelte-hero-icons'
const MAX_HEIGHT = 192
let element = $state<Element>()
function isOverflown(element: Element) {
if (!element) return false
return element.scrollHeight > MAX_HEIGHT
}
interface Props {
body: string
clickThrough?: boolean
element?: string
style?: string
class?: string
}
let {
body,
clickThrough = false,
element: htmlElement = 'div',
style = '',
class: clazz = '',
}: Props = $props()
let overflows = $derived(element ? isOverflown(element) : false)
let expanded = $state(false)
$effect(() => {
expanded = !overflows
})
</script>
<svelte:element
this={htmlElement}
{style}
class={[
expanded
? 'text-slate-600 dark:text-zinc-400 max-h-full'
: [
'overflow-hidden bg-linear-to-b text-transparent from-slate-600 via-slate-600',
'dark:from-zinc-400 dark:via-zinc-400 bg-clip-text z-0 max-h-36',
],
clazz,
]}
class:pointer-events-none={!clickThrough}
bind:this={element}
>
<Markdown source={expanded ? body : body.slice(0, 1000)} />
{#if overflows}
<Button
onclick={() => (expanded = !expanded)}
size="square-sm"
color="tertiary"
class={[
'text-black dark:text-white absolute z-10 isolate pointer-events-auto bottom-0',
'left-1/2 -translate-x-1/2 mb-4',
expanded && 'bg-slate-200/50 dark:bg-zinc-900 shadow-md',
]}
title="Expand"
>
<Icon
src={ChevronDown}
size="20"
mini
class="{expanded ? 'rotate-180' : ''} transition-transform"
/>
</Button>
{/if}
</svelte:element>
+523
View File
@@ -0,0 +1,523 @@
<script lang="ts">
// This file is genuinely atrocious. It was here since the start of Photon,
// 2 years ago. I'm very sorry about this. please don't think this is
// my peak of development.
import { client, site } from '$lib/api/client.svelte'
import type {
CommunityView,
Post,
PostResponse,
PostView,
} from '$lib/api/types'
import ErrorContainer, {
clearErrorScope,
pushError,
} from '$lib/ui/info/ErrorContainer.svelte'
import FreeTextInput from '$lib/ui/form/FreeTextInput.svelte'
import ObjectAutocomplete from '$lib/ui/form/ObjectAutocomplete.svelte'
import MarkdownEditor from '$lib/app/markdown/MarkdownEditor.svelte'
import Avatar from '$lib/ui/generic/Avatar.svelte'
import { Header } from '$comp/ui/layout'
import { t } from '$lib/app/i18n'
import { errorMessage } from '$lib/lemmy/error'
import { getSessionStorage, setSessionStorage } from '$lib/session.js'
import { placeholders } from '$lib/util.svelte.js'
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'
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('$comp/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"
style="background-color: {flair.background_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
}
}}
rounding="xl"
size="custom"
disabled={!getSessionStorage('postDraft')}
title="Restore From Draft"
class=" aspect-square h-full"
>
<Icon src={ArrowPath} size="16" mini />
</Button>
{/if}
</div>
</form>
+12
View File
@@ -0,0 +1,12 @@
<script lang="ts">
import type { PostView } from '$lib/api/types'
import { Post } from '.'
interface Props {
post: PostView
}
let { post }: Props = $props()
</script>
<Post {post} />
+117
View File
@@ -0,0 +1,117 @@
<script lang="ts">
import { parseURL } from '$comp/input/Link.svelte'
import type { View } from '$lib/settings.svelte'
import { Material } from 'mono-svelte'
import { optimizeImageURL } from './helpers'
import { Icon, Link } from 'svelte-hero-icons'
interface Props {
url: string
thumbnail_url?: string
nsfw?: boolean
embed_title?: string
view?: View
}
let {
url,
thumbnail_url,
nsfw = false,
embed_title,
view = 'cozy',
}: Props = $props()
let richURL = $derived(parseURL(url))
</script>
<!--
@component
For embed-type posts. Displays embed card or a compact link.
-->
{#if embed_title && view == 'cozy'}
<Material
color="uniform"
class={[
'flex flex-col-reverse sm:flex-row overflow-hidden gap-4 z-0 relative',
'dark:bg-zinc-950 hover:bg-slate-50 hover:dark:bg-zinc-900 transition-colors',
'group/link',
]}
rounding="2xl"
element="a"
padding="sm"
href={url}
target="_blank"
rel="noopener"
>
{#if thumbnail_url}
<img
src={optimizeImageURL(thumbnail_url, 32)}
alt=""
class="-z-10 absolute w-full object-cover h-full opacity-5 brightness-150
dark:brightness-70 dark:opacity-10 blur-2xl -inset-px"
/>
{/if}
<div class={['flex flex-col gap-1 p-2', thumbnail_url && '-mt-2 sm:mt-0']}>
{#if richURL}
<div
class="text-slate-600 dark:text-zinc-400 inline-flex items-center gap-1 text-xs font-medium"
>
{richURL.hostname}
</div>
{/if}
<p class="font-medium text-base">{embed_title}</p>
</div>
{#if thumbnail_url}
<picture class="mb-auto sm:ml-auto shrink-0 sm:w-1/3 sm:max-w-60">
{#each ['webp'] as format}
<source
srcset="{optimizeImageURL(
thumbnail_url,
256,
format as 'avif' | 'webp',
)} 256w, {optimizeImageURL(
thumbnail_url,
512,
format as 'avif' | 'webp',
)} 512w"
media="(min-width: 0px)"
type="image/{format}"
/>
{/each}
<img
src={optimizeImageURL(thumbnail_url, -1)}
class="object-cover w-full sm:max-w-96 h-32 sm:min-h-16 bg-slate-200 dark:bg-zinc-800 rounded-xl"
width={600}
height={400}
alt=""
class:blur-3xl={nsfw}
/>
</picture>
{/if}
</Material>
{:else}
<a
href={url}
target="_blank"
rel="noopener noreferrer"
class="flex flex-row text-slate-900 dark:text-zinc-400 items-center overflow-hidden group/link hover:underline space-x-1 my-1"
>
<Icon src={Link} size="16" micro class="shrink-0" />
{#if richURL}
<div
class="flex max-w-full overflow-hidden font-medium self-start justify-self-start w-max text-sm"
>
{richURL.hostname}
{#if richURL.pathname != '/'}
<span
class="text-slate-500 dark:text-zinc-500 whitespace-nowrap font-normal group-hover/link:opacity-100 opacity-0 transition-opacity duration-100"
>
{richURL.pathname}
</span>
{/if}
</div>
{:else}
{url}
{/if}
</a>
{/if}
+452
View File
@@ -0,0 +1,452 @@
<script lang="ts" module>
type BadgeType =
| 'nsfw'
| 'saved'
| 'featured'
| 'deleted'
| 'removed'
| 'locked'
| 'moderator'
| 'admin'
export interface Tag {
content: string
color?: string
icon?: IconSource | null
textColor?: string
type: 'flair' | 'custom'
}
export const textToTag: Map<string, Tag> = new Map<string, Tag>([
['OC', { content: 'OC', color: '#03A8F240', type: 'custom' }],
['NSFL', { content: 'NSFL', color: '#ff000040', type: 'custom' }],
['CW', { content: 'CW', color: '#ff000040', type: 'custom' }],
])
export const parseTags = (
title?: string,
): { tags: Tag[]; title?: string } => {
if (!title) return { tags: [] }
let extracted: Tag[] = []
const newTitle = title
.toString()
.replace(/^(\[.[^\]]+\])|(\[.[^\]]+\])$/g, (match) => {
const contents = match.split(',').map((part: string) => part.trim())
contents
.map((i) => i.replaceAll(/(\[|\])/g, ''))
.forEach((content: string) => {
extracted.push(
textToTag.get(content) ?? {
content: content,
type: 'custom',
},
)
})
return ''
})
return {
tags: extracted,
title: newTitle,
}
}
</script>
<script lang="ts">
import { profile } from '$lib/app/auth.svelte'
import type { Community, Person, SubscribedType } from '$lib/api/types'
import UserLink from '$comp/lemmy/user/UserLink.svelte'
import Markdown from '$lib/app/markdown/Markdown.svelte'
import Avatar from '$lib/ui/generic/Avatar.svelte'
import { publishedToDate } from '$comp/util/date'
import RelativeDate, {
formatRelativeDate,
} from '$comp/util/RelativeDate.svelte'
import { t } from '$lib/app/i18n'
import { settings, type View } from '$lib/settings.svelte'
import { Badge, Material, modal, Popover } from 'mono-svelte'
import {
Bookmark,
ExclamationTriangle,
Icon,
LockClosed,
Megaphone,
PaperAirplane,
Pencil,
ShieldCheck,
Tag,
Trash,
type IconSource,
} from 'svelte-hero-icons'
import { SvelteMap } from 'svelte/reactivity'
import CommunityLink from '../community/CommunityLink.svelte'
interface Props {
community?: Community
showCommunity?: boolean
subscribed?: SubscribedType
user?: Person
published?: Date
title?: string
id?: number
read?: boolean
edited?: string
view?: View
// Badges
badges?: Record<BadgeType, boolean>
tags?: Tag[]
style?: string
titleClass?: string
extraBadges?: import('svelte').Snippet
postUrl?: string
}
let {
community = $bindable(undefined),
showCommunity = true,
subscribed = $bindable(undefined),
user,
published,
title,
id,
read = false,
edited,
view = 'cozy',
badges = {
nsfw: false,
saved: false,
featured: false,
deleted: false,
removed: false,
locked: false,
moderator: false,
admin: false,
},
tags = [],
postUrl,
style = '',
titleClass = '',
extraBadges,
}: Props = $props()
const badgeToData: Map<
BadgeType,
{
icon: IconSource
color: 'red-subtle' | 'yellow-subtle' | 'green-subtle'
label: string
}
> = new SvelteMap([
[
'nsfw',
{
icon: ExclamationTriangle,
color: 'red-subtle',
label: $t('post.badges.nsfw'),
},
],
[
'saved',
{
icon: Bookmark,
color: 'yellow-subtle',
label: $t('post.badges.saved'),
},
],
[
'featured',
{
icon: Megaphone,
color: 'green-subtle',
label: $t('post.badges.featured'),
},
],
[
'removed',
{
icon: Trash,
color: 'green-subtle',
label: $t('post.badges.removed'),
},
],
[
'deleted',
{
icon: Trash,
color: 'red-subtle',
label: $t('post.badges.deleted'),
},
],
[
'locked',
{
icon: LockClosed,
color: 'yellow-subtle',
label: $t('post.badges.locked'),
},
],
])
</script>
<!--
@component
This component will build two different things: a post's meta block and the title.
-->
<header
class={[
'grid w-full meta',
community ? 'grid-rows-2' : 'grid-rows-1 minimal',
'text-xs min-w-0 max-w-full text-slate-600 dark:text-zinc-400',
]}
class:compact={view == 'compact'}
{style}
>
{#if showCommunity && community}
<Popover>
{#snippet target(attachment)}
<button
{@attach attachment}
class={[
'row-span-2 shrink-0 mr-2 self-center group/btn',
'bg-slate-200 dark:bg-zinc-800 rounded-lg cursor-pointer',
]}
>
{#if community.nsfw && settings.nsfwBlur}
<div
style="width: {view == 'compact' ? 24 : 32}; height: {view ==
'compact'
? 24
: 32}"
class="bg-red-400 rounded-xl"
></div>
{:else}
<Avatar
url={community?.icon}
width={view == 'compact' ? 24 : 32}
alt={community?.name}
circle={false}
class="group-hover/btn:scale-90 group-active/btn:scale-[.85] transition-transform"
/>
{/if}
</button>
{/snippet}
{#snippet popover(open)}
{#if open && community && subscribed}
<Material
color="uniform"
rounding="2xl"
elevation="high"
class="max-w-2xl w-full max-h-128 overflow-auto"
data-autoclose="false"
>
{#await import('../community/CommunityHeader.svelte') then { default: CommunityHeader }}
<CommunityHeader {community} {subscribed} />
{/await}
</Material>
{/if}
{/snippet}
</Popover>
{/if}
{#if showCommunity && community}
<CommunityLink
{community}
style="grid-area: community;"
class="shrink no-list-margin"
badges={{
nsfw: community.nsfw,
}}
/>
{/if}
<div
class="flex flex-row gap-1.5 items-center
no-list-margin {view == 'compact' && showCommunity ? 'min-sm:mx-2' : ''}"
style="grid-area: stats;"
>
{#if user}
<address class="contents not-italic">
{#if view == 'compact' && showCommunity}
<Icon
src={PaperAirplane}
size="12"
micro
class="rotate-180 text-slate-400 dark:text-zinc-600 max-sm:hidden"
/>
{/if}
<UserLink avatarSize={20} {user} avatar={!showCommunity} class="shrink">
{#snippet extraBadges()}
{#if badges.moderator}
<Icon src={ShieldCheck} size="14" mini class="text-green-500" />
{/if}
{#if badges.admin}
<Icon src={ShieldCheck} size="14" mini class="text-red-500" />
{/if}
{/snippet}
</UserLink>
</address>
{/if}
{#if published}
<RelativeDate date={published} class="shrink-0" />
{/if}
{#if edited}
<button
title={$t('post.meta.lastEdited', {
default: formatRelativeDate(publishedToDate(edited), {
style: 'long',
}),
})}
onclick={() =>
modal({
title: $t('common.info'),
body: $t('post.meta.lastEdited', {
default: formatRelativeDate(publishedToDate(edited), {
style: 'long',
}),
}),
})}
>
<Icon src={Pencil} micro size="14" />
</button>
{/if}
</div>
<div
class="flex flex-row min-sm:justify-end items-center self-center flex-wrap gap-2 *:shrink-0 badges min-sm:ml-2"
style="grid-area: badges;"
>
{#if tags}
{#each tags as tag}
{@const href =
tag.type == 'flair'
? null
: `/search?community=${community?.id}&q=[${tag.content}]&type=Posts`}
<svelte:element
this={href ? 'a' : 'div'}
{href}
class="hover:brightness-110"
style="{tag.color ? `--tag-color: ${tag.color};` : ''} {tag.textColor
? `--tag-text-color: ${tag.textColor}`
: ''}"
>
<Badge class={tag.color ? 'badge-tag-color' : ''}>
{#snippet icon()}
{#if tag.icon}
<Icon src={tag.icon} micro size="14" />
{:else if tag === undefined}
<Icon src={Tag} micro size="14" />
{/if}
{/snippet}
{tag.content}
</Badge>
</svelte:element>
{/each}
{/if}
{#each Object.keys(badges)
// filter by ones that are true
.filter((i) => badges[i as BadgeType] == true)
// get from predetermined map
.map((i) => badgeToData.get(i as BadgeType))
// remove null
.filter((i) => i != undefined) as badge}
<Badge label={badge.label} color={badge.color} allowIconOnly>
{#snippet icon()}
<Icon src={badge.icon} micro size="14" />{/snippet}{badge.label}
</Badge>
{/each}
{@render extraBadges?.()}
</div>
</header>
{#if title && id}
{@const useAttachedUrl = settings.posts.titleOpensUrl && postUrl}
<h3
class={[
'font-medium max-sm:mt-0!',
titleClass,
settings.markReadPosts && read && 'text-slate-600 dark:text-zinc-400',
view == 'compact' ? 'text-base' : 'text-lg',
]}
style="grid-area: title;"
>
<a
href={useAttachedUrl
? postUrl
: `/post/${encodeURIComponent(profile.current.instance)}/${id}`}
target={useAttachedUrl ? '_blank' : undefined}
rel={useAttachedUrl ? 'noopener noreferrer' : undefined}
class="inline-block hover:underline hover:text-primary-900 dark:hover:text-primary-100 transition-colors"
>
<Markdown
inline
source={title}
class={view != 'compact' ? '' : 'leading-[1.3]'}
/>
</a>
</h3>
{:else}
<div style="grid-area: title; margin: 0;"></div>
{/if}
<style>
@reference '../../../../app.css';
.meta {
display: grid;
grid-template-areas:
'avatar community badges'
'avatar stats badges';
gap: 0;
grid-template-rows: auto auto auto;
grid-template-columns: 40px minmax(0, auto);
}
.meta.minimal {
grid-template-columns: 0fr;
}
@media screen and (max-width: 40rem) {
.meta.compact {
grid-template-areas:
'avatar community'
'avatar stats'
'badges badges';
gap: 0;
grid-template-columns: 32px minmax(0, auto);
}
.meta.minimal {
grid-template-columns: 0fr;
}
}
@media screen and (min-width: 40rem) {
.meta.compact {
display: flex;
flex-direction: row;
align-items: center;
}
.meta.minimal {
grid-template-columns: 0fr;
}
}
:global(.badge-tag-color) {
background-color: color-mix(
in oklab,
#eee,
var(--tag-color, #fff)
) !important;
color: color-mix(in oklab, #000, var(--tag-text-color, #000)) !important;
@variant dark {
background-color: color-mix(
in oklab,
#222,
var(--tag-color, #fff)
) !important;
color: color-mix(
in oklab,
#fff 80%,
var(--tag-text-color, #fff)
) !important;
}
}
</style>
+177
View File
@@ -0,0 +1,177 @@
<script lang="ts" module>
export const voteColor = (vote: number) =>
vote == 1
? `bg-primary-900 dark:bg-primary-100 text-slate-50 dark:text-zinc-900`
: vote == -1
? `bg-red-500 text-slate-50 dark:bg-red-400 dark:text-zinc-900`
: ''
export const shouldShowVoteColor = (
vote: number,
type: 'upvotes' | 'downvotes',
): string =>
(vote == -1 && type == 'downvotes') || (vote == 1 && type == 'upvotes')
? voteColor(vote)
: ''
</script>
<script lang="ts">
import { profile } from '$lib/app/auth.svelte.js'
import FormattedNumber from '$comp/util/FormattedNumber.svelte'
import { t } from '$lib/app/i18n'
import { site } from '$lib/api/client.svelte'
import { vote as voteItem } from '$lib/lemmy/contentview.js'
import { errorMessage } from '$lib/lemmy/error'
import { settings } from '$lib/settings.svelte'
import type { Post } from '$lib/api/types'
import { buttonColor, toast } from 'mono-svelte'
import { ChevronDown, ChevronUp, Icon } from 'svelte-hero-icons'
import { backOut } from 'svelte/easing'
import { fly } from 'svelte/transition'
interface Props {
post: Post
vote?: number
score: number
upvotes: number
downvotes: number
showCounts?: boolean
children?: import('svelte').Snippet<[{ vote?: number; score?: number }]>
}
let {
post = $bindable(),
vote = $bindable(),
score = $bindable(),
upvotes = $bindable(),
downvotes = $bindable(),
showCounts = true,
children,
}: Props = $props()
const castVote = async (newVote: number) => {
if (!profile.current?.jwt) {
toast({ content: $t('toast.loginVoteGate'), type: 'warning' })
return
}
switch (vote ?? 0) {
case 0:
// nothing was removed
if (newVote == 1) upvotes++
else downvotes++
break
case 1:
// removed an upvote
upvotes--
if (newVote == -1) downvotes++
break
case -1:
// removed a downvote
downvotes--
if (newVote == 1) upvotes++
break
}
vote = newVote
voteItem(post, newVote)
.then((res) => ({ upvotes, downvotes, score } = res))
.catch((e) => {
toast({ content: errorMessage(e), type: 'error' })
})
}
</script>
{#snippet voteButton(
votes: number,
target: 'upvote' | 'downvote',
vote?: number,
)}
{@const targetNum = target == 'upvote' ? 1 : -1}
<button
onclick={() => castVote(vote == targetNum ? 0 : targetNum)}
class={[
'flex items-center gap-0.5 transition-colors relative cursor-pointer h-full p-2',
'first:rounded-l-3xl last:rounded-r-3xl',
'last:flex-row-reverse',
vote == targetNum
? shouldShowVoteColor(
vote,
target == 'upvote' ? 'upvotes' : 'downvotes',
)
: 'hover:bg-slate-100 dark:hover:bg-zinc-800',
]}
aria-pressed={vote == targetNum}
aria-label={$t(
target == 'upvote'
? 'post.actions.vote.upvote'
: 'post.actions.vote.downvote',
)}
>
<Icon src={target == 'upvote' ? ChevronUp : ChevronDown} size="20" micro />
{#if showCounts}
<div class="grid text-sm z-20">
{#key votes}
<span
style="grid-column: 1; grid-row: 1;"
in:fly={{ duration: 400, y: -10, easing: backOut }}
out:fly={{ duration: 400, y: 10, easing: backOut }}
aria-label={$t(
target == 'upvote' ? 'aria.vote.upvotes' : 'aria.vote.downvotes',
{ default: votes },
)}
>
<FormattedNumber number={votes ?? 0} />
</span>
{/key}
</div>
{/if}
</button>
{/snippet}
{#if children}{@render children({ vote, score })}{:else}
{@const voteRatio = Math.floor(
((upvotes ?? 0) / ((upvotes ?? 0) + (downvotes ?? 0))) * 100,
)}
<div
class={[
buttonColor.ghost,
'rounded-3xl h-full font-medium flex relative hover:bg-transparent!',
voteRatio < 85 && settings.voteRatioBar && 'vote-ratio',
]}
aria-label={$t('aria.vote.group')}
style="--vote-ratio: {voteRatio}%;"
>
{@render voteButton(upvotes, 'upvote', vote)}
<div
class="h-full p-0! border-l border-slate-200 dark:border-zinc-800"
></div>
{#if site.data?.site_view.local_site.enable_downvotes ?? true}
{@render voteButton(downvotes, 'downvote', vote)}
{/if}
</div>
{/if}
<style>
.vote-ratio {
z-index: 0;
}
.vote-ratio::before {
border-radius: var(--radius-3xl);
content: '';
position: absolute;
height: 100%;
opacity: 10%;
width: 100%;
left: 0;
bottom: 0px;
z-index: -10;
background: linear-gradient(
to right,
var(--color-indigo-500) calc(var(--vote-ratio) - 4%),
var(--color-red-500) calc(var(--vote-ratio) + 4%)
);
}
</style>
@@ -0,0 +1,198 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte.js'
import { amMod, isAdmin } from '$comp/lemmy/moderation/moderation.js'
import { publishedToDate } from '$comp/util/date'
import FormattedNumber from '$comp/util/FormattedNumber.svelte'
import { t } from '$lib/app/i18n'
import { save } from '$lib/lemmy/contentview.js'
import { settings, type View } from '$lib/settings.svelte.js'
import type { PostView } from '$lib/api/types'
import { Button, Menu, Modal, Spinner } from 'mono-svelte'
import {
Bookmark,
BookmarkSlash,
BugAnt,
ChatBubbleOvalLeft,
ChatBubbleOvalLeftEllipsis,
EllipsisHorizontal,
Icon,
ShieldCheck,
} from 'svelte-hero-icons'
import { postLink } from '../helpers'
import { PostVote } from '..'
let saving = $state(false)
let editing = $state(false)
interface Props {
post: PostView
view?: View
debug?: boolean
style?: string
onedit?: (post: PostView) => void
onhide?: (hide: boolean) => void
}
let {
post = $bindable(),
view = 'cozy',
debug = $bindable(false),
style = '',
onedit,
onhide,
}: Props = $props()
let buttonHeight = $derived(view == 'compact' ? 'h-7.5' : 'h-8')
let buttonSquare = $derived(view == 'compact' ? 'w-7.5 h-7.5' : 'w-8 h-8')
</script>
{#if editing}
<Modal bind:open={editing}>
{#snippet customTitle()}
<h1 class="text-2xl font-bold">{$t('form.edit')}</h1>
{/snippet}
{#await import('../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}
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,
}}
>
{#snippet formtitle()}
<!-- Have the title not exist at all -->
{/snippet}
</PostForm>
{/await}
</Modal>
{/if}
<footer
class={[
'flex flex-row gap-2 items-center shrink-0 text-slate-600 dark:text-zinc-400',
buttonHeight,
]}
class:flex-row-reverse={settings.posts.reverseActions}
{style}
>
<PostVote
post={post.post}
bind:vote={post.my_vote}
bind:score={post.counts.score}
bind:upvotes={post.counts.upvotes}
bind:downvotes={post.counts.downvotes}
/>
<Button
size="custom"
href="{postLink(post.post)}#comments"
class="text-inherit! h-full px-3 relative"
color="ghost"
rounding="pill"
target={settings.openLinksInNewTab ? '_blank' : ''}
aria-label={$t('post.actions.comments')}
>
{@const newComment =
publishedToDate(post.counts.newest_comment_time).getTime() >
new Date().getTime() - 5 * 60 * 1000}
<Icon
src={newComment ? ChatBubbleOvalLeftEllipsis : ChatBubbleOvalLeft}
size="16"
mini
/>
<FormattedNumber number={post.counts.comments} />
</Button>
<div class="flex-1"></div>
{#if settings.debugInfo}
{#if debug}
{#await import('$lib/ui/util/debug/DebugObject.svelte') then { default: DebugObject }}
<DebugObject object={post} bind:open={debug} />
{/await}
{/if}
<Button
onclick={() => (debug = true)}
title="Debug"
size="custom"
color="ghost"
rounding="pill"
class={buttonSquare}
icon={BugAnt}
></Button>
{/if}
{#if profile.current?.user && (amMod(profile.current.user, post.community) || isAdmin(profile.current.user))}
{#await import('$comp/lemmy/moderation/ModerationMenu.svelte') then { default: ModerationMenu }}
<ModerationMenu bind:item={post}>
{#snippet target(attachment, acting)}
<Button
{@attach attachment}
size="custom"
color="ghost"
rounding="pill"
loading={acting}
class={buttonSquare}
>
<Icon src={ShieldCheck} size="18" mini />
</Button>
{/snippet}
</ModerationMenu>
{/await}
{/if}
{#if profile.current?.jwt}
<Button
onclick={async () => {
if (!profile.current?.jwt) return
saving = true
post.saved = await save(post, !post.saved)
saving = false
}}
size="custom"
class={buttonSquare}
color="ghost"
rounding="pill"
loading={saving}
disabled={saving}
title={post.saved ? $t('post.actions.unsave') : $t('post.actions.save')}
icon={post.saved ? BookmarkSlash : Bookmark}
></Button>
{/if}
<Menu placement="bottom-end">
{#snippet target(popover)}
<Button
{@attach popover}
title={$t('post.actions.more.label')}
color="ghost"
rounding="pill"
size="custom"
class={buttonSquare}
icon={EllipsisHorizontal}
></Button>
{/snippet}
{#snippet children(open)}
{#if open}
{#await import ('./PostActionsMenu.svelte')}
<div class="p-8 w-full h-full grid place-items-center">
<Spinner width={20} />
</div>
{:then { default: PostActionsMenu }}
<PostActionsMenu bind:post {onhide} bind:editing />
{/await}
{/if}
{/snippet}
</Menu>
</footer>
@@ -0,0 +1,165 @@
<script lang="ts">
import { goto } from '$app/navigation'
import { profile } from '$lib/app/auth.svelte'
import { client } from '$lib/api/client.svelte'
import { PiefedClient } from '$lib/api/piefed/adapter'
import type { PostView } from '$lib/api/types'
import { t } from '$lib/app/i18n'
import { deleteItem, markAsRead } from '$lib/lemmy/contentview'
import { setSessionStorage } from '$lib/session'
import { settings } from '$lib/settings.svelte'
import { instanceToURL } from '$lib/util.svelte'
import { Button, Menu, MenuButton, toast } from 'mono-svelte'
import {
ArrowTopRightOnSquare,
EllipsisHorizontal,
Eye,
EyeSlash,
Flag,
GlobeAlt,
MapPin,
PencilSquare,
Share,
Trash,
XMark,
} from 'svelte-hero-icons'
import { report } from '../../moderation/moderation'
import { hidePost } from '../helpers'
interface Props {
post: PostView
onhide?: (hide: boolean) => void
editing: boolean
}
let { post = $bindable(), onhide, editing = $bindable() }: Props = $props()
function share(global: boolean = true) {
const link = global
? post.post.ap_id
: `${instanceToURL(profile.current.instance)}/post/${post.post.id}`
if (navigator.share)
navigator.share?.({
url: link,
})
else {
navigator.clipboard.writeText(link)
toast({ content: $t('toast.copied') })
}
}
</script>
{#if profile.current?.user && profile.current?.jwt && profile.current.user.local_user_view.person.id == post.creator.id}
<MenuButton onclick={() => (editing = true)} icon={PencilSquare}>
{$t('post.actions.more.edit')}
</MenuButton>
{/if}
{#if profile.current?.jwt}
<MenuButton
onclick={async () => {
if (profile.current?.jwt)
post.read = await markAsRead(post.post, !post.read)
}}
icon={post.read ? EyeSlash : Eye}
>
{post.read
? $t('post.actions.more.markUnread')
: $t('post.actions.more.markRead')}
</MenuButton>
{/if}
<div class="flex flex-row">
<MenuButton
onclick={() => share()}
class={['flex-1', !post.post.local && 'rounded-r-lg']}
icon={Share}
>
{$t('post.actions.more.share')}
</MenuButton>
{#if !post.post.local}
<Menu>
{#snippet target(attachment)}
<Button
{@attach attachment}
aria-label={$t('post.actions.more.label')}
color="tertiary"
size="custom"
class="w-6 h-6 self-center"
data-autoclose="false"
icon={EllipsisHorizontal}
></Button>
{/snippet}
<MenuButton onclick={() => share(true)} icon={GlobeAlt}>
{$t('filter.location.global')}
</MenuButton>
<MenuButton onclick={() => share(false)} icon={MapPin}>
{$t('filter.location.local')}
</MenuButton>
</Menu>
{/if}
</div>
{#if profile.current?.jwt}
<MenuButton
onclick={() => {
setSessionStorage('postDraft', {
body: `${
settings.crosspostOriginalLink
? `cross-posted from: ${post.post.ap_id}`
: ``
}\n${
post.post.body ? '>' + post.post.body.split('\n').join('\n> ') : ''
}`,
url: post.post.url,
title: post.post.name,
loading: false,
nsfw: post.post.nsfw,
community: null,
image: null,
})
goto('/create/post?crosspost=true')
}}
icon={ArrowTopRightOnSquare}
>
{$t('post.actions.more.crosspost')}
</MenuButton>
{#if profile.current.user && post.creator.id == profile.current.user.local_user_view.person.id}
<MenuButton
onclick={async () => {
if (profile.current?.jwt)
post.post.deleted = await deleteItem(post, !post.post.deleted)
}}
color="danger-subtle"
icon={Trash}
>
{post.post.deleted
? $t('post.actions.more.restore')
: $t('post.actions.more.delete')}
</MenuButton>
{/if}
{#if profile.current.user?.local_user_view.person.id != post.creator.id}
{#if !(client() instanceof PiefedClient)}
<MenuButton
onclick={async () => {
if (!profile.current?.jwt) return
const hidden = await hidePost(
post.post.id,
!post.hidden,
profile.current?.jwt,
)
post.hidden = hidden
if (hidden) onhide?.(hidden)
}}
color="danger-subtle"
icon={XMark}
>
{post.hidden
? $t('post.actions.more.unhide')
: $t('post.actions.more.hide')}
</MenuButton>
{/if}
<MenuButton onclick={() => report(post)} color="danger-subtle" icon={Flag}>
{$t('moderation.report')}
</MenuButton>
{/if}
{/if}
+53
View File
@@ -0,0 +1,53 @@
<script lang="ts">
import type { PostView } from '$lib/api/types'
import Placeholder from '$lib/ui/info/Placeholder.svelte'
import { settings } from '$lib/settings.svelte.js'
import { Button } from 'mono-svelte'
import type { Snippet } from 'svelte'
import { ArchiveBox, Plus } from 'svelte-hero-icons'
import { Post } from '..'
interface Props {
posts: PostView[]
community?: boolean
children?: Snippet
}
let { posts = $bindable(), community = false, children }: Props = $props()
</script>
<ul
class="flex flex-col list-none divide-y divide-slate-200 dark:divide-zinc-800"
>
{#if posts?.length == 0}
<div class="h-full grid place-items-center">
<Placeholder
icon={ArchiveBox}
title="No posts"
description="There are no posts that match this filter."
>
<Button href="/communities" icon={Plus}>
<span>Follow some communities</span>
</Button>
</Placeholder>
</div>
{:else}
{#each posts as post, index (post.post.id)}
<li class="relative post-container">
<Post
hideCommunity={community}
view={(post.post.featured_community || post.post.featured_local) &&
settings.posts.compactFeatured
? 'compact'
: settings.view}
{post}
class="transition-all duration-250"
onhide={() => {
posts = posts.toSpliced(index, 1)
}}
/>
</li>
{/each}
{/if}
{@render children?.()}
</ul>
@@ -0,0 +1,263 @@
<script lang="ts">
import { browser } from '$app/environment'
import { client } from '$lib/api/client.svelte'
import type { GetPosts } from '$lib/api/types'
import VirtualList from '$lib/app/render/VirtualList.svelte'
import EndPlaceholder from '$lib/ui/layout/EndPlaceholder.svelte'
import Placeholder from '$lib/ui/info/Placeholder.svelte'
import { t } from '$lib/app/i18n'
import { settings } from '$lib/settings.svelte.js'
import type { PostView } from 'lemmy-js-client'
import { Button } from 'mono-svelte'
import { onDestroy, onMount, untrack } from 'svelte'
import {
ArchiveBox,
ArrowTopRightOnSquare,
ChevronDoubleUp,
ExclamationTriangle,
Icon,
} from 'svelte-hero-icons'
import InfiniteScroll from 'svelte-infinite-scroll'
import { expoOut } from 'svelte/easing'
import { SvelteSet } from 'svelte/reactivity'
import { fly } from 'svelte/transition'
import { Post } from '..'
interface Props {
posts: PostView[]
params: GetPosts
virtualList?: { itemHeights: (number | null)[] }
lastSeen?: number
community?: boolean
children?: import('svelte').Snippet
}
let {
posts = $bindable(),
params = $bindable(),
virtualList = $bindable(),
lastSeen = $bindable(0),
community = false,
children,
}: Props = $props()
let listEl = $state<HTMLUListElement>()
let listComp = $state<{
scrollToIndex: (index: number, window?: boolean) => void
}>()
let error = $state()
let loading = $state(false)
let hasMore = $state(true)
const abortLoad = new AbortController()
let seenIds = new SvelteSet<number>(posts.map((post) => post.post.id))
async function loadMore() {
if (!hasMore || loading) return
try {
loading = true
const newPosts = await client({
func: (input, init) =>
fetch(input, { ...init, signal: abortLoad.signal }),
})
.getPosts(params)
.catch((e) => {
throw new Error(e)
})
error = null
hasMore = newPosts.posts.length != 0
params.page_cursor = newPosts.next_page
posts.push(
...newPosts.posts.filter((post) => {
if (seenIds.has(post.post.id)) return false
seenIds.add(post.post.id)
return true
}),
)
loading = false
} catch (e) {
error = e
loading = false
}
}
const callback: IntersectionObserverCallback = (entries, observer) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) return
const element = entry.target as HTMLElement
const id = element.getAttribute('data-index')
if (!id) return
lastSeen = Number(id)
observer.unobserve(element)
})
}
onMount(() => {
const observer = new IntersectionObserver(callback, {
threshold: 0.5,
})
const observePost = (node: Node) => {
if (
node instanceof HTMLElement &&
node.classList.contains('post-container')
)
observer.observe(node)
}
const unobservePost = (node: Node) => {
if (
node instanceof HTMLElement &&
node.classList.contains('post-container')
)
observer.unobserve(node)
}
document.querySelectorAll('.post-container').forEach(observePost)
const feed = document.getElementById('feed')
if (!feed) return
new MutationObserver((mutations) => {
mutations.forEach(({ addedNodes, removedNodes }) => {
addedNodes.forEach(observePost)
removedNodes.forEach(unobservePost)
})
}).observe(feed, { childList: true, subtree: false })
})
$effect(() => {
if (listComp) {
untrack(() => {
if (lastSeen != 0) {
listComp?.scrollToIndex(lastSeen, true)
}
})
}
})
let initialOffset = $derived(listEl?.offsetTop)
onDestroy(() => {
abortLoad?.abort()
})
</script>
<ul class="flex flex-col list-none" bind:this={listEl}>
{#key posts}
{#if posts?.length == 0}
<div class="h-full grid place-items-center my-8">
<Placeholder
icon={ArchiveBox}
title={$t('routes.frontpage.empty.title')}
description={$t('routes.frontpage.empty.description')}
>
<Button
href="/communities"
rounding="pill"
color="primary"
icon={ArrowTopRightOnSquare}
>
{$t('nav.communities')}
</Button>
</Placeholder>
</div>
{:else}
<VirtualList
id="feed"
class="divide-y-2 -mx-3 sm:-mx-6 divide-slate-100 dark:divide-zinc-900"
items={posts}
{initialOffset}
overscan={3}
estimatedHeight={settings.view == 'cozy' ? 500 : 150}
bind:restore={virtualList}
bind:this={listComp}
>
{#snippet item(row)}
<li
in:fly={row < 7
? { duration: 800, easing: expoOut, y: 24, delay: row * 50 }
: { opacity: 1, duration: 0 }}
data-index={row}
class={['relative post-container', row < 7 && '']}
>
<Post
bind:post={posts[row]}
hideCommunity={community}
view={(posts[row]?.post.featured_community ||
posts[row]?.post.featured_local) &&
settings.posts.compactFeatured
? 'compact'
: settings.view}
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"
></Post>
</li>
{/snippet}
</VirtualList>
{/if}
{/key}
{#if settings.infiniteScroll && browser && posts.length > 0}
{#if error}
<div
class="flex flex-col justify-center items-center
rounded-xl gap-2 py-8 mt-6
border border-b! border-red-500! bg-red-500/5 px-4"
>
<div class="bg-red-500/30 rounded-full p-3 text-red-500">
<Icon src={ExclamationTriangle} size="24" solid></Icon>
</div>
<pre class="py-0.5">{error}</pre>
<Button
color="primary"
{loading}
disabled={loading}
onclick={() => loadMore()}
>
{$t('message.retry')}
</Button>
</div>
{:else if hasMore}
<div class="w-full flex flex-col gap-2 animate-pulse pt-6">
<div
class="w-96 max-w-full h-8 bg-slate-100 dark:bg-zinc-800 rounded-md"
></div>
<div class="w-full h-48 bg-slate-100 dark:bg-zinc-800 rounded-md"></div>
<div class="bg-transparent! h-8 flex justify-between">
<div class="w-48 h-8 bg-slate-100 dark:bg-zinc-800 rounded-md"></div>
<div class="w-24 h-8 bg-slate-100 dark:bg-zinc-800 rounded-md"></div>
</div>
</div>
{:else}
<div style="border-top-width: 0">
<EndPlaceholder>
{$t('routes.frontpage.endFeed', {
community_name: params.community_name ?? 'undefined',
})}
{#snippet action()}
<Button color="tertiary" icon={ChevronDoubleUp}>
{$t('routes.post.scrollToTop')}
</Button>
{/snippet}
</EndPlaceholder>
</div>
{/if}
<InfiniteScroll window threshold={600} on:loadMore={loadMore} />
{/if}
{@render children?.()}
</ul>
+97
View File
@@ -0,0 +1,97 @@
import { profile } from '$lib/app/auth.svelte'
import { client } from '$lib/api/client.svelte'
import type { CommentView, PersonView, Post } from '$lib/api/types'
import {
canParseUrl,
findClosestNumber,
isImage,
isVideo,
} from '$lib/util.svelte'
export const isCommentMutable = (comment: CommentView, me: PersonView) =>
me.person.id == comment.creator.id
// Algorithm to determine the best image URL to use
export const bestImageURL = (
post: Post,
thumbnail: boolean = true,
width: number = 1024,
format: 'avif' | 'webp' | null = 'webp',
) => {
if (post.thumbnail_url && (thumbnail || !post.url))
return optimizeImageURL(post.thumbnail_url, width, format)
else if (post.url) return optimizeImageURL(post.url, width, format)
return post.url ?? ''
}
export const optimizeImageURL = (
urlStr: string,
width: number = 1024,
format: 'avif' | 'webp' | null = 'webp',
): string => {
try {
const url = new URL(urlStr)
if (format) url.searchParams.set('format', format)
if (width > 0 && !url.searchParams.has('thumbnail')) {
url.searchParams.set(
'thumbnail',
findClosestNumber(
[128, 196, 256, 512, 728, 1024, 1536],
width,
).toString(),
)
}
return url.toString()
} catch (e) {
console.error(e)
return urlStr
}
}
const YOUTUBE_REGEX =
/^(?:https?:\/\/)?(?:www\.|m\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|shorts\/|live\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/
export const isYoutubeLink = (url?: string): RegExpMatchArray | null => {
if (!url) return null
return url?.match?.(YOUTUBE_REGEX)
}
export function postLink(post: Post) {
return `/post/${encodeURIComponent(profile.current.instance)}/${post.id}`
}
export type MediaType = 'video' | 'image' | 'iframe' | 'embed' | 'none'
export type IframeType = 'youtube' | 'video' | 'none'
export function mediaType(url?: string): MediaType {
if (!url) return 'none'
if (isImage(url)) return 'image'
if (isVideo(url)) return 'iframe'
if (isYoutubeLink(url)) return 'iframe'
if (canParseUrl(url)) return 'embed'
return 'none'
}
export function iframeType(url: string): IframeType {
if (isVideo(url)) return 'video'
if (isYoutubeLink(url)) return 'youtube'
return 'none'
}
export async function hidePost(
id: number,
hide: boolean,
jwt: string,
): Promise<boolean> {
await client({ auth: jwt }).hidePost({
hide: hide,
post_ids: [id],
})
return hide
}
+20
View File
@@ -0,0 +1,20 @@
export { default as Post } from './Post.svelte'
export { default as PostBody } from './PostBody.svelte'
export { default as PostItem } from './PostItem.svelte'
export { default as PostMeta } from './PostMeta.svelte'
export { default as PostVote } from './PostVote.svelte'
export { default as PostMedia } from './media/PostMedia.svelte'
export { default as PostMediaCompact } from './media/PostMediaCompact.svelte'
export { default as PostImage } from './media/PostImage.svelte'
export { default as PostIframe } from './media/PostIframe.svelte'
export { default as PostLink } from './PostLink.svelte'
export { default as PostActions } from './actions/PostActions.svelte'
export {
type Tag,
parseTags,
textToTag,
default as PostsMeta,
} from './PostMeta.svelte'
export * from './helpers'
@@ -0,0 +1,159 @@
<script lang="ts" module>
const youtubeDomain = (place: 'youtube' | 'invidious' | 'piped') => {
switch (place) {
case 'youtube': {
return 'www.youtube-nocookie.com'
}
case 'invidious': {
return settings.embeds.invidious || 'yewtu.be'
}
case 'piped': {
return settings.embeds.piped || 'piped.video'
}
}
}
function youtubeVideoID(url: string): string | null {
const regex =
/^(?:https?:\/\/)?(?:www\.|m\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|shorts\/|live\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/
const match = url.match(regex)
if (match && match[1]) {
return match[1]
}
return null
}
</script>
<script lang="ts">
import { settings } from '$lib/settings.svelte'
import {
Icon,
PuzzlePiece,
VideoCamera,
type IconSource,
} from 'svelte-hero-icons'
import { optimizeImageURL, type IframeType } from '../helpers'
const urlToEmbed = (inputUrl: string) => {
if (type == 'video') {
return inputUrl
}
if (type == 'youtube') {
const url = new URL(inputUrl)
const videoID = youtubeVideoID(inputUrl)
if (videoID) {
const embedUrl = new URL(
`https://${youtubeDomain(settings.embeds.youtube)}/embed/${videoID}`,
)
embedUrl.searchParams.set('start', url.searchParams.get('t') ?? '')
url.searchParams.forEach((value, key) => {
embedUrl.searchParams.set(key, value)
})
if (autoplay) embedUrl.searchParams.set('autoplay', '1')
return embedUrl.toString()
}
}
return ''
}
const typeData = (
type: IframeType,
): {
icon: IconSource
text: string
} => {
switch (type) {
case 'youtube': {
return {
icon: VideoCamera,
text: 'YouTube Video',
}
}
case 'video': {
return {
icon: VideoCamera,
text: 'Video',
}
}
default: {
return {
icon: PuzzlePiece,
text: 'Embed',
}
}
}
}
interface Props {
type?: IframeType
thumbnail?: string | undefined
url: string
opened?: boolean
autoplay?: boolean
class?: string
}
let {
type = 'none',
thumbnail = undefined,
url,
opened = $bindable(!settings.embeds.clickToView),
autoplay = settings.embeds.clickToView,
class: clazz = '',
}: Props = $props()
let data = $derived(typeData(type))
let embedUrl = $derived(urlToEmbed(url))
</script>
<!--
@component
Displays a video file or embedded video iframe.
-->
{#if opened}
{#if type == 'video'}
<!-- svelte-ignore a11y_media_has_caption -->
<video {autoplay} controls class="rounded-xl aspect-video {clazz}">
<source src={url} />
</video>
{:else}
<iframe
src={embedUrl}
title="Embed player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
class="aspect-video rounded-xl dark:bg-zinc-900 {clazz ?? ''}"
></iframe>
{/if}
{:else}
<button
onclick={() => (opened = true)}
class="aspect-video w-full h-full z-0 overflow-hidden relative rounded-xl flex flex-col gap-2 items-center justify-center text-white"
>
{#if thumbnail}
<img
src={optimizeImageURL(thumbnail, 512)}
class="absolute top-0 left-0 -z-10 brightness-25 w-full object-cover h-full"
alt=""
/>
{:else}
<div
class="absolute blur-3xl -z-10 top-0 left-0 w-full h-full bg-linear-to-br from-green-800 via-blue-900 via-20% to-red-700"
></div>
{/if}
<Icon src={data.icon} solid size="48" />
<h1 class="font-bold text-xl">{data.text}</h1>
<p>Click to view this content.</p>
</button>
{/if}
+109
View File
@@ -0,0 +1,109 @@
<script lang="ts">
import { showImage } from '$lib/ui/generic/ExpandableImage.svelte'
import { settings } from '$lib/settings.svelte'
import type { Post } from '$lib/api/types'
import { Button, modal } from 'mono-svelte'
import { onMount } from 'svelte'
import { bestImageURL, postLink } from '../helpers'
interface Props {
post: Post
blur?: boolean
}
let { post, blur = false }: Props = $props()
let imageLoaded: boolean | null = $state(null)
onMount(() => {
imageLoaded = false
})
</script>
<!--disabled preloads here since most people will hover over every image while scrolling-->
<svelte:element
this={settings.expandImages ? 'button' : 'a'}
href={postLink(post)}
class={[
'container/a z-10 rounded-2xl cursor-pointer relative overflow-hidden',
'bg-slate-100 dark:bg-zinc-900 transition-colors',
'border border-slate-200 dark:border-zinc-800 group',
]}
data-sveltekit-preload-data="off"
aria-label={post.name}
onclick={() => showImage(bestImageURL(post, false, -1, null))}
role="button"
tabindex="0"
>
<!-- svelte-ignore a11y_missing_attribute -->
<div class="inset-0 absolute -z-10 rounded-xl overflow-hidden">
<img
loading="lazy"
fetchpriority="auto"
src={bestImageURL(post, false, 64)}
class=" object-cover w-full h-full opacity-50 blur-lg"
/>
</div>
<picture class="max-h-[60vh]">
{#each ['webp'] as format}
<source
srcset="{bestImageURL(
post,
false,
512,
format as 'avif' | 'webp',
)} 512w, {bestImageURL(
post,
false,
768,
format as 'avif' | 'webp',
)} 768w, {bestImageURL(
post,
false,
1024,
format as 'avif' | 'webp',
)} 1024w"
media="(min-width: 0px)"
type="image/{format}"
/>
{/each}
<img
src={blur ? '' : bestImageURL(post, false, -1, null)}
loading="lazy"
class={[
'max-w-full rounded-xl z-30 transition-all max-h-[60vh] duration-500 object-contain mx-auto group-hover:scale-98 group-active:scale-95',
'duration-200 ease-cubic',
imageLoaded === false ? 'opacity-0' : 'opacity-100',
blur && 'blur-3xl',
]}
width={512}
height={300}
alt={post.alt_text ?? ''}
onload={() => (imageLoaded = true)}
/>
</picture>
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute bottom-0 left-0 right-0 flex justify-between items-center
rounded-full ml-auto w-max m-2 p-0 gap-1
*:bg-white *:border *:border-slate-200 dark:*:border-zinc-800 dark:*:bg-zinc-900"
onclick={(e) => e.stopPropagation()}
>
{#if post.alt_text}
<Button
onclick={(e) => {
e.stopPropagation()
modal({
title: 'Alt',
body: post.alt_text ?? '',
})
}}
color="tertiary"
size="md"
rounding="pill"
>
ALT
</Button>
{/if}
</div>
</svelte:element>
@@ -0,0 +1,52 @@
<script lang="ts">
import { settings, type View } from '$lib/settings.svelte.js'
import type { Post } from '$lib/api/types'
import {
PostImage,
PostIframe,
PostLink,
type MediaType,
iframeType,
} from '..'
interface Props {
view?: View
post: Post
type?: MediaType
opened?: boolean | undefined
blur?: boolean
}
let {
view = 'cozy',
post,
type = 'none',
opened = undefined,
blur = post.nsfw && settings.nsfwBlur,
}: Props = $props()
</script>
<!--
@component
This component will show either
- A media item (pictures, videos) (large form factor posts only)
- Embed link/card.
-->
{#if type == 'image' && view == 'cozy'}
<PostImage {post} {blur} />
{:else if (type == 'iframe' || type == 'video') && view == 'cozy' && post.url}
<PostIframe
thumbnail={post.thumbnail_url}
type={iframeType(post.url)}
url={post.url}
{opened}
/>
{:else if type == 'embed' && post.url}
<PostLink
url={post.url}
thumbnail_url={post.thumbnail_url}
nsfw={post.nsfw}
embed_title={post.embed_title}
{view}
/>
{/if}
@@ -0,0 +1,170 @@
<script lang="ts">
import { bestImageURL, postLink, type MediaType } from '..'
import { showImage } from '$lib/ui/generic/ExpandableImage.svelte'
import { t } from '$lib/app/i18n'
import { settings, type View } from '$lib/settings.svelte.js'
import type { Post } from '$lib/api/types'
import { modal, Button } from 'mono-svelte'
import {
DocumentText,
ExclamationTriangle,
Icon,
Link,
Photo,
VideoCamera,
} from 'svelte-hero-icons'
const thumbnailSize = (view: View) =>
view == 'compact' ? 'w-22 h-22 sm:w-28' : 'w-24 h-24 sm:w-32'
interface Props {
post: Post
type?: MediaType
view?: View
blur?: boolean
style?: string
class?: string
}
let {
post,
type = 'none',
view = 'cozy',
blur = post.nsfw && settings.nsfwBlur,
style = '',
class: clazz = '',
}: Props = $props()
let size = $derived(thumbnailSize(view))
</script>
<!--
@component
Thumbnails for compact and list view posts.
-->
<div class={[size, 'relative group/media', clazz]} {style} role="presentation">
<svelte:element
this={!settings.expandImages || type != 'image' ? 'a' : 'button'}
href={post.url ?? postLink(post)}
aria-label={type == 'image'
? $t('aria.postDecor.openImage', { default: post.name })
: type == 'embed'
? $t('aria.postDecor.openLink', {
default: post.embed_title ?? post.name,
})
: $t('aria.postDecor.openPost', { default: post.name })}
target={post.url ? '_blank' : undefined}
onclick={() => {
if (type == 'image') showImage(bestImageURL(post, false, -1))
}}
role={type == 'image' ? 'button' : 'link'}
tabindex="0"
class="cursor-pointer h-full block"
>
<div
class={[
'relative overflow-hidden rounded-2xl max-h-full h-full',
'border border-slate-200 dark:border-zinc-800 hover-scale-effect bg-slate-200 dark:bg-zinc-800',
]}
>
{#if post.thumbnail_url || type == 'image'}
{@const thumbnail = post.thumbnail_url != undefined && type != 'image'}
<picture>
<!--I would add AVIF, but lemmy.world's AVIF is broken as of currently-->
{#each ['webp'] as format}
<source
srcset="{bestImageURL(
post,
thumbnail,
128,
format as 'avif' | 'webp',
)} 1x, {bestImageURL(
post,
thumbnail,
256,
format as 'avif' | 'webp',
)} 2x, {bestImageURL(
post,
thumbnail,
512,
format as 'avif' | 'webp',
)} 3x"
media="(min-width: 0px)"
type="image/{format}"
/>
{/each}
<img
src={blur ? '' : bestImageURL(post, thumbnail, -1, null)}
loading="lazy"
class={[
'object-cover relative overflow-hidden rounded-xl h-full',
size,
]}
alt={post.alt_text ?? ' '}
class:blur-xl={blur}
/>
</picture>
{#if type != 'image'}
<div
class={[
'absolute w-8 h-8 bottom-1 left-1 rounded-xl bg-slate-25 dark:bg-zinc-900 grid place-items-center',
]}
>
<Icon src={type == 'iframe' ? VideoCamera : Link} micro size="16" />
</div>
{/if}
{:else}
<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"
/>
</div>
{/if}
</div>
{#if blur}
<Icon
src={ExclamationTriangle}
solid
size="32"
class="absolute w-8 h-8 mx-auto my-auto z-30 inset-0 opacity-30"
/>
{/if}
</svelte:element>
{#if post.alt_text}
<Button
onclick={() => modal({ title: 'Alt text', body: post.alt_text })}
aria-label="Alt text"
class="absolute bottom-0 left-0 z-20 m-1"
size="square-md"
rounding="xl"
>
<Icon src={Photo} size="16" micro />
</Button>
{/if}
</div>
<style>
.hover-scale-effect > *,
.hover-scale-effect > picture > img {
transition: transform 200ms var(--ease-cubic);
}
.hover-scale-effect:hover > *,
.hover-scale-effect:hover > picture > img {
transform: scale(95%);
}
.hover-scale-effect:active > *,
.hover-scale-effect:active > picture > img {
transform: scale(90%);
}
</style>