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

+323
View File
@@ -0,0 +1,323 @@
<script lang="ts">
import { page } from '$app/state'
import { profile } from '$lib/app/auth.svelte.js'
import UserLink from '$comp/lemmy/user/UserLink.svelte'
import Markdown from '$lib/app/markdown/Markdown.svelte'
import { publishedToDate } from '$comp/util/date.js'
import RelativeDate, {
formatRelativeDate,
} from '$comp/util/RelativeDate.svelte'
import { t } from '$lib/app/i18n'
import { getClient } from '$lib/api/client.svelte'
import { errorMessage } from '$lib/lemmy/error'
import { settings } from '$lib/settings.svelte'
import { Button, Modal, toast } from 'mono-svelte'
import {
Bookmark,
Icon,
Microphone,
Minus,
Pencil,
Plus,
ShieldCheck,
Trash,
} from 'svelte-hero-icons'
import { expoOut } from 'svelte/easing'
import type { ClassValue } from 'svelte/elements'
import { slide } from 'svelte/transition'
import type { CommentNodeI } from './comments.svelte'
import CommentForm from './CommentForm.svelte'
import CommentActions from './CommentActions.svelte'
interface Props {
node: CommentNodeI
postId: number
op?: boolean
actions?: boolean
meta?: boolean
open?: boolean
replying?: boolean
contentClass?: ClassValue
class?: ClassValue
metaSuffix?: import('svelte').Snippet
children?: import('svelte').Snippet
}
let {
node = $bindable(),
postId,
op = false,
actions = true,
meta = true,
replying = $bindable(false),
open = $bindable(true),
contentClass = '',
class: clazz = '',
metaSuffix,
children,
}: Props = $props()
let editing = $state(false)
let newComment = $state(node.comment_view.comment.content)
let editingLoad = $state(false)
async function save(type: 'reply' | 'edit') {
if (!profile.current?.jwt || newComment.length <= 0) return
editingLoad = true
try {
if (type == 'edit') {
await getClient().editComment({
comment_id: node.comment_view.comment.id,
content: newComment,
})
node.comment_view.comment.content = newComment
editing = false
}
} catch (err) {
toast({
content: errorMessage(err as string),
type: 'error',
})
}
editingLoad = false
}
</script>
{#if editing}
<Modal bind:open={editing}>
{#snippet customTitle()}
<div>{$t('form.edit')}</div>
{/snippet}
<form
onsubmit={(e) => {
e.preventDefault()
save(replying ? 'reply' : 'edit')
}}
class="contents"
>
<CommentForm
bind:value={newComment}
postId={node.comment_view.comment.id}
actions={false}
preview={true}
/>
<Button
submit
color="primary"
size="lg"
loading={editingLoad}
disabled={editingLoad}
class="w-full"
>
{$t('form.submit')}
</Button>
</form>
</Modal>
{/if}
<li
class={['py-3 relative', clazz]}
id={node.comment_view.comment.id.toString()}
>
{#if meta}
<label
for="comment-expand-{node.comment_view.comment.id}"
class="flex flex-row cursor-pointer gap-2 items-center group text-sm flex-wrap w-full z-0 group relative"
>
<div
class={[
'absolute -inset-0.5 right-1 group-hover:right-0 group-hover:-inset-1.5 opacity-0 group-hover:opacity-100 transition-all',
'bg-slate-100 dark:bg-zinc-900 -z-10 rounded-full inline-flex items-center justify-end',
]}
>
{#if node.comment_view.counts.child_count > 0}
{@const children = node.comment_view.counts.child_count}
<div
aria-label={$t('aria.comments.children', { childCount: children })}
class="font-medium"
>
{children}
</div>
{/if}
<div
class={[
!open && 'rotate-90',
'transition-all duration-500 ease-out my-auto h-full w-8 grid place-items-center',
]}
>
<Icon src={open ? Minus : Plus} size="16" micro />
</div>
</div>
{@render metaSuffix?.()}
<span class:font-bold={op} class="flex flex-row gap-1 items-center">
<UserLink
inComment
avatarSize={20}
avatar
user={node.comment_view.creator}
>
{#snippet extraBadges()}
{#if node.comment_view.creator_is_moderator}
<Icon
src={ShieldCheck}
size="14"
micro
class="text-green-500"
aria-label={$t('class.moderator')}
/>
{/if}
{#if node.comment_view.creator_is_admin}
<Icon
src={ShieldCheck}
size="16"
micro
class="text-red-500"
aria-label={$t('class.admin')}
/>
{/if}
{/snippet}
</UserLink>
{#if op}
<Icon mini size="16" src={Microphone} class="text-sky-600" />
{/if}
</span>
<RelativeDate
class="text-slate-600 dark:text-zinc-400"
date={publishedToDate(node.comment_view.comment.published)}
/>
<span class="text-slate-600 dark:text-zinc-400 flex flex-row gap-2 ml-1">
{#if node.comment_view.comment.updated}{@const edited = $t(
'post.meta.lastEdited',
{
default: formatRelativeDate(
publishedToDate(node.comment_view.comment.updated),
{
style: 'long',
},
),
},
)}
<div title={edited}>
<Icon src={Pencil} micro size="14" />
</div>
{/if}
{#if node.comment_view.comment.deleted}
<Icon
src={Trash}
solid
size="12"
aria-label={$t('post.badges.deleted')}
class="text-red-600 dark:text-red-500"
/>
{/if}
{#if node.comment_view.comment.removed}
<Icon
src={Trash}
solid
size="12"
aria-label={$t('post.badges.removed')}
class="text-green-600 dark:text-green-500"
/>
{/if}
{#if node.comment_view.saved}
<Icon
src={Bookmark}
solid
size="12"
aria-label={$t('post.badges.saved')}
class="text-yellow-600 dark:text-yellow-500"
/>
{/if}
</span>
{#if settings.debugInfo}
<span class="text-slate-600 dark:text-zinc-400 font-mono ml-auto">
#{node.comment_view.comment.id}
</span>
{/if}
</label>
{/if}
<input
class="hidden comment-expand"
type="checkbox"
id="comment-expand-{node.comment_view.comment.id}"
bind:checked={open}
/>
<div class={['expand max-w-full', contentClass]}>
<div id="comment-content">
<div
class={[
'flex flex-col whitespace-pre-wrap max-w-full gap-1 mt-1 relative w-full',
]}
>
<Markdown
source={node.comment_view.comment.content}
noStyle
class={[
'text-[15px] sm:text-base text-slate-700 dark:text-zinc-300 *:leading-[1.6] break-words space-y-3',
node.comment_view.comment.distinguished
? 'bg-green-400/10 p-2 rounded-xl max-w-max font-medium'
: page.url.hash.slice(1) ==
node.comment_view.comment.id.toString() &&
'bg-slate-100 dark:bg-zinc-900 p-2 rounded-xl max-w-max',
]}
/>
{#if actions}
<CommentActions
comment={node.comment_view}
bind:replying
onedit={() => (editing = true)}
disabled={node.comment_view.banned_from_community ||
node.comment_view.post.locked}
/>
{/if}
</div>
{#if replying}
<div transition:slide={{ duration: 600, easing: expoOut }}>
<CommentForm
label={$t('comment.reply')}
{postId}
parentId={node.comment_view.comment.id}
oncomment={(e) => {
node.children = [
{
children: [],
comment_view: e.comment_view,
depth: node.depth + 1,
expanded: true,
},
...node.children,
]
replying = false
}}
oncancel={() => (replying = false)}
/>
</div>
{/if}
{@render children?.()}
</div>
</div>
</li>
<style>
.expand {
display: grid;
grid-template-rows: 0fr;
grid-template-columns: 100%;
overflow: hidden;
transition: grid-template-rows 0.5s cubic-bezier(0.19, 1, 0.22, 1);
}
.comment-expand:checked + .expand {
grid-template-rows: 1fr;
}
.expand > * {
min-height: 0;
}
</style>
@@ -0,0 +1,131 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte.js'
import type { CommentView } from '$lib/api/types'
import CommentModerationMenu from '$comp/lemmy/moderation/CommentModerationMenu.svelte'
import { amMod, isAdmin, report } from '$comp/lemmy/moderation/moderation.js'
import { t } from '$lib/app/i18n'
import { deleteItem, save } from '$lib/lemmy/contentview.js'
import { settings } from '$lib/settings.svelte'
import { Button, Menu, MenuButton } from 'mono-svelte'
import {
Bookmark,
BookmarkSlash,
ChatBubbleOvalLeft,
EllipsisHorizontal,
Flag,
PencilSquare,
Share,
Trash,
} from 'svelte-hero-icons'
import CommentVote from './CommentVote.svelte'
interface Props {
comment: CommentView
replying?: boolean
disabled?: boolean
onedit?: (comment: CommentView) => void
}
let {
comment = $bindable(),
replying = $bindable(false),
disabled = false,
onedit,
}: Props = $props()
</script>
<div
class={[
'flex flex-row items-center gap-0.5 h-7 w-full',
settings.posts.reverseActions && 'flex-row-reverse',
]}
>
<CommentVote
upvotes={comment.counts.upvotes}
downvotes={comment.counts.downvotes}
vote={comment.my_vote}
comment={comment.comment}
/>
<Button
color="tertiary"
rounding="pill"
size="sm"
class="text-slate-500 dark:text-zinc-400 gap-1!"
onclick={() => (replying = !replying)}
disabled={comment.post.locked || disabled || !profile.current.jwt}
icon={ChatBubbleOvalLeft}
>
{$t('comment.reply')}
</Button>
{#if profile.current?.user && (amMod(profile.current?.user, comment.community) || isAdmin(profile.current.user))}
<CommentModerationMenu bind:item={comment} />
{/if}
<Menu placement="bottom">
{#snippet target(attachment)}
<Button
{@attach attachment}
title={$t('comment.actions.label')}
color="tertiary"
rounding="pill"
size="square-md"
class="text-slate-600 dark:text-zinc-400"
icon={EllipsisHorizontal}
></Button>
{/snippet}
<MenuButton
onclick={() => {
if (navigator.share)
navigator.share?.({
url: comment.comment.ap_id,
})
else navigator.clipboard.writeText(comment.comment.ap_id)
}}
icon={Share}
>
{$t('post.actions.more.share')}
</MenuButton>
{#if profile.current?.jwt}
{#if comment.creator.id == profile.current.user?.local_user_view.person.id}
<MenuButton onclick={() => onedit?.(comment)} icon={PencilSquare}>
{$t('post.actions.more.edit')}
</MenuButton>
{/if}
<MenuButton
onclick={async () => {
if (profile.current?.jwt)
comment.saved = await save(comment, !comment.saved)
}}
icon={comment.saved ? BookmarkSlash : Bookmark}
>
{comment.saved ? $t('post.actions.unsave') : $t('post.actions.save')}
</MenuButton>
{#if profile.current?.user && profile.current.jwt && profile.current.user.local_user_view.person.id == comment.creator.id}
<MenuButton
color="danger-subtle"
onclick={async () => {
if (profile.current?.jwt)
comment.comment.deleted = await deleteItem(
comment,
!comment.comment.deleted,
)
}}
icon={Trash}
>
{comment.comment.deleted
? $t('post.actions.more.restore')
: $t('post.actions.more.delete')}
</MenuButton>
{/if}
{#if profile.current.jwt && profile.current.user?.local_user_view.person.id != comment.creator.id}
<MenuButton
onclick={() => report(comment)}
color="danger-subtle"
icon={Flag}
>
{$t('moderation.report')}
</MenuButton>
{/if}
{/if}
</Menu>
<div class="flex-1 w-full"></div>
</div>
+177
View File
@@ -0,0 +1,177 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte.js'
import Markdown from '$lib/app/markdown/Markdown.svelte'
import MarkdownEditor from '$lib/app/markdown/MarkdownEditor.svelte'
import { t } from '$lib/app/i18n'
import { client, site } from '$lib/api/client.svelte'
import { errorMessage } from '$lib/lemmy/error'
import { placeholders } from '$lib/util.svelte.js'
import type { CommentResponse } from '$lib/api/types'
import { Button, Menu, MenuButton, toast } from 'mono-svelte'
import { Icon, Language, XMark } from 'svelte-hero-icons'
import type { ClassValue, HTMLTextareaAttributes } from 'svelte/elements'
interface Props extends Omit<HTMLTextareaAttributes, 'oncancel'> {
postId: number
parentId?: number | undefined
locked?: boolean
banned?: boolean
rows?: number
placeholder?: string | undefined
value?: string
actions?: boolean
tools?: boolean
preview?: boolean
class?: ClassValue
required?: boolean
id?: string
label?: string
editing?: boolean
oncomment?: (comment: CommentResponse) => void
onconfirm?: (value: string) => void
oncancel?: (cancel: boolean) => void
}
let {
postId,
parentId = undefined,
locked = false,
banned = false,
rows = 7,
placeholder = undefined,
value = $bindable(''),
actions = true,
preview: previewAction = true,
editing = false,
oncancel,
oncomment,
...rest
}: Props = $props()
let loading = $state(false)
let preview = false
let language: number | undefined = $state()
async function submit() {
if (
!profile.current?.user ||
!profile.current?.jwt ||
value == '' ||
editing
)
return
loading = true
try {
const response = await client().createComment({
content: value,
post_id: postId,
parent_id: parentId,
})
oncomment?.(response)
value = ''
} catch (err) {
console.error(err)
toast({
content: errorMessage(err as string),
type: 'error',
})
}
loading = false
}
</script>
<form
onsubmit={(e) => {
e.preventDefault()
submit()
}}
class="flex flex-col gap-2 relative"
>
{#if preview}
<div
class="bg-slate-100 dark:bg-zinc-900 px-3 py-2.5 h-64 border
border-slate-300 dark:border-zinc-700 rounded-md overflow-auto text-sm resize-y"
>
<Markdown source={value} />
</div>
{:else}
<MarkdownEditor
{...rest}
{rows}
placeholder={locked
? $t('comment.locked')
: banned
? $t('comment.banned')
: (placeholder ?? placeholders.get('comment'))}
bind:value
disabled={locked || loading || banned}
previewButton={previewAction}
>
<Menu>
{#snippet target(attachment)}
<Button
{@attach attachment}
size="custom"
rounding="xl"
class="w-7.5 h-7.5"
color={language != undefined ? 'primary' : 'ghost'}
title={$t('form.profile.languages.title')}
>
<Icon src={Language} size="14" micro />
</Button>
{/snippet}
{#if site.data}
<MenuButton
class="min-h-[16px] py-0"
onclick={() => (language = undefined)}
>
<Icon src={XMark} size="16" micro />
{$t('form.post.unset')}
</MenuButton>
{#each site.data?.all_languages as languageOption}
<MenuButton
class="min-h-[16px] py-0"
onclick={() => {
language = languageOption.id
}}
>
{languageOption.name}
</MenuButton>
{/each}
{/if}
</Menu>
<div class="flex-1"></div>
{#if actions}
<Button
size="custom"
title={$t('common.cancel')}
onclick={() => oncancel?.(true)}
color="tertiary"
class="w-8 h-8"
rounding="xl"
>
<Icon
src={XMark}
size="16"
micro
class="text-slate-600 dark:text-zinc-400"
/>
</Button>
<Button
submit
color="primary"
rounding="xl"
{loading}
disabled={locked || loading || banned}
>
{$t('form.submit')}
</Button>
{/if}
</MarkdownEditor>
{/if}
</form>
@@ -0,0 +1,79 @@
<script lang="ts">
import { publishedToDate } from '$comp/util/date.js'
import { t } from '$lib/app/i18n'
import type { CommentView } from '$lib/api/types'
import { Button, Material } from 'mono-svelte'
import { ArrowUturnUp, Icon } from 'svelte-hero-icons'
import type { ClassValue } from 'svelte/elements'
import { PostMeta } from '../post'
import Comment from './Comment.svelte'
interface Props {
comment: CommentView
community?: boolean
meta?: boolean
class?: string
commentClass?: ClassValue
actions?: boolean
}
let {
comment,
community = false,
meta = true,
class: clazz = '',
commentClass = '',
actions = true,
...rest
}: Props = $props()
</script>
<Material
class={['flex flex-col flex-1 rounded-none list-none', clazz]}
color="none"
padding="none"
>
{#if meta}
<div class="flex flex-row justify-between items-center gap-2">
<div class="flex flex-col gap-2">
<PostMeta
badges={{
nsfw: comment.post.nsfw,
removed: comment.post.removed,
admin: false,
moderator: false,
saved: false,
deleted: comment.post.deleted,
featured:
comment.post.featured_community || comment.post.featured_local,
locked: comment.post.locked,
}}
published={publishedToDate(comment.comment.published)}
community={community ? comment.community : undefined}
title={comment.post.name}
id={comment.post.id}
titleClass="text-sm text-slate-500 dark:text-zinc-400"
/>
</div>
<Button
color="primary"
rounding="pill"
size="sm"
href="/comment/{comment.comment.id}"
class="self-start"
>
{$t('common.jump')}
<Icon src={ArrowUturnUp} size="14" micro />
</Button>
</div>
{/if}
<Comment
postId={comment.post.id}
node={{ children: [], comment_view: comment, depth: 1, expanded: true }}
replying={false}
{meta}
{actions}
{...rest}
class={commentClass}
/>
</Material>
@@ -0,0 +1,60 @@
<script lang="ts">
import VirtualList from '$lib/app/render/VirtualList.svelte'
import type { Post } from '$lib/api/types'
import type { CommentNodeI } from './comments.svelte'
import Comments from './CommentTree.svelte'
import { onMount } from 'svelte'
interface Props {
nodes: CommentNodeI[]
post: Post
scrollTo?: string
}
onMount(() => {
if (scrollTo) {
const element = document?.getElementById(scrollTo)
setTimeout(() => {
element?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}, 100)
}
const observer = new ResizeObserver((entries) => {
entries.forEach((entry) => {
if (offsetEl) {
initialOffset =
entry.target.getBoundingClientRect().top + window.scrollY
}
})
})
if (offsetEl) observer.observe(offsetEl)
return () => observer.disconnect()
})
let { nodes, post, scrollTo }: Props = $props()
let offsetEl = $state<HTMLElement>()
let initialOffset = $derived(offsetEl?.offsetTop)
</script>
<div bind:this={offsetEl}>
{#if offsetEl}
<VirtualList
class="divide-y-2 divide-slate-100 dark:divide-zinc-900 -mx-3 sm:-mx-6"
overscan={5}
estimatedHeight={500}
items={nodes}
{initialOffset}
>
{#snippet item(index)}
<div class={['px-3 sm:px-6', index % 2 == 1 && '']}>
<Comments
bind:nodes={() => [nodes[index]], (v) => (nodes[index] = v[0])}
{post}
/>
</div>
{/snippet}
</VirtualList>
{/if}
</div>
+141
View File
@@ -0,0 +1,141 @@
<script lang="ts">
import { browser } from '$app/environment'
import { goto } from '$app/navigation'
import { client } from '$lib/api/client.svelte'
import type { Post } from '$lib/api/types'
import { t } from '$lib/app/i18n'
import { errorMessage } from '$lib/lemmy/error'
import { Button, toast } from 'mono-svelte'
import { ArrowDownCircle } from 'svelte-hero-icons'
import Comment from './Comment.svelte'
import Comments from './CommentTree.svelte'
import { buildCommentsTree, type CommentNodeI } from './comments.svelte'
interface Props {
nodes: CommentNodeI[]
post: Post
}
let { nodes = $bindable(), post }: Props = $props()
let childrenPage = 0
async function fetchChildren(parent: CommentNodeI) {
if (
!(
parent.comment_view.counts.child_count > 0 &&
parent.children.length == 0
)
) {
return
}
try {
parent.loading = true
const newComments = await client().getComments({
max_depth: 5,
parent_id: parent.comment_view.comment.id,
type_: 'All',
page: childrenPage,
})
if (newComments.comments.length == 0) {
toast({
content: $t('toast.noComments'),
type: 'error',
})
return
}
const tree = buildCommentsTree(newComments.comments, parent.depth)
// 0.18.2 -> 0.18.3 broke this
// so i'm adding this check
const treeParent = tree.find(
(c) => c.comment_view.comment.id == parent.comment_view.comment.id,
)
if (treeParent) {
// < 0.18.3
parent.children = treeParent.children
if (treeParent.children.length == 0) {
toast({
content: $t('toast.noComments'),
type: 'warning',
})
}
} else {
// 0.18.3+
parent.children = tree
if (tree.length == 0) {
toast({
content: $t('toast.noComments'),
type: 'warning',
})
}
}
childrenPage++
} catch (err) {
console.error(err)
toast({
content: errorMessage(err as string),
type: 'error',
})
}
}
</script>
<ul class="animate-pop-in">
{#each nodes as node, index (node.comment_view.comment.id)}
<Comment
bind:node={nodes[index]}
postId={post.id}
op={post.creator_id == node.comment_view.creator.id}
contentClass={[
(node.children.length > 0 ||
node.comment_view.counts.child_count > 0) &&
'border-l',
'ml-2.5 pl-3 sm:pl-4 lg:pl-5',
'border-slate-200 dark:border-zinc-800',
]}
bind:open={nodes[index].expanded}
>
{#if node.children?.length > 0}
<Comments {post} bind:nodes={nodes[index].children} />
{/if}
</Comment>
{#if node.comment_view.counts.child_count > 0 && node.children.length == 0}
<svelte:element
this={browser ? 'div' : 'a'}
class="w-full h-10 -mt-2 -ml-2.5"
href="/comment/{node.comment_view.comment.id}"
>
<Button
loading={nodes[index].loading}
disabled={nodes[index].loading}
rounding="pill"
color="tertiary"
class="font-normal text-slate-600 dark:text-zinc-400"
shadow="none"
loaderWidth={16}
onclick={() => {
if (nodes[index].depth > 4) {
goto(`/comment/${nodes[index].comment_view.comment.id}#comments`)
} else {
nodes[index].loading = true
fetchChildren(nodes[index]).then(
() => (nodes[index].loading = false),
)
}
}}
icon={ArrowDownCircle}
>
{$t('comment.more', {
comments: node.comment_view.counts.child_count,
})}
</Button>
</svelte:element>
{/if}
{/each}
</ul>
+148
View File
@@ -0,0 +1,148 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte.js'
import { site } from '$lib/api/client.svelte'
import FormattedNumber from '$comp/util/FormattedNumber.svelte'
import { t } from '$lib/app/i18n'
import { errorMessage } from '$lib/lemmy/error'
import { settings } from '$lib/settings.svelte'
import { buttonColor, toast } from 'mono-svelte'
import { ChevronDown, ChevronUp, Icon } from 'svelte-hero-icons'
import { backOut } from 'svelte/easing'
import { fly } from 'svelte/transition'
import { shouldShowVoteColor } from '../post/PostVote.svelte'
import { vote as voteItem } from '$lib/lemmy/contentview'
import type { Comment } from '$lib/api/types'
interface Props {
vote?: number
upvotes: number
downvotes: number
comment: Comment
}
let {
vote = $bindable(0),
upvotes = $bindable(),
downvotes = $bindable(),
comment,
}: 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(comment, newVote)
.then((res) => ({ upvotes, downvotes } = res))
.catch((e) => {
toast({ content: errorMessage(e), type: 'error' })
})
}
let voteRatio = $derived(
Math.floor(((upvotes ?? 0) / ((upvotes ?? 0) + (downvotes ?? 0))) * 100),
)
</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-1.5',
'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="18" micro />
<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>
</button>
{/snippet}
<div
class={[
'h-full relative flex items-center overflow-hidden rounded-full hover:bg-transparent font-medium hover:dark:bg-transparent',
buttonColor.ghost,
voteRatio < 85 && settings.voteRatioBar && 'vote-ratio',
]}
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>
<style>
.vote-ratio {
z-index: 0;
}
.vote-ratio::before {
content: '';
position: absolute;
height: 100%;
width: 100%;
opacity: 10%;
z-index: -10;
left: 0;
bottom: 0px;
background: linear-gradient(
to right,
var(--color-indigo-500) calc(var(--vote-ratio) - 5%),
var(--color-red-500) calc(var(--vote-ratio) + 5%)
);
}
</style>
+123
View File
@@ -0,0 +1,123 @@
import { t } from '$lib/app/i18n/translations'
import type { Comment, CommentView } from '$lib/client/types'
import { SvelteMap } from 'svelte/reactivity'
export interface CommentNodeI {
comment_view: CommentView
children: Array<CommentNodeI>
depth: number
loading?: boolean
expanded?: boolean
}
function getCommentParentId(comment?: Comment): number | undefined {
const split = comment?.path.split('.')
// remove the 0
split?.shift()
return split && split.length > 1
? Number(split.at(split.length - 2))
: undefined
}
function getDepthFromComment(comment?: Comment): number | undefined {
const len = comment?.path.split('.').length
return len ? len - 2 : undefined
}
export function buildCommentsTree(
comments: CommentView[],
baseDepth: number = 0,
filter: (c: CommentView) => boolean = () => true,
): CommentNodeI[] {
const map = new SvelteMap<number, CommentNodeI>()
let min_depth = Number.MAX_VALUE
for (const comment_view of comments) {
const depthI = getDepthFromComment(comment_view.comment) ?? 0
const depth = depthI + baseDepth
if (comment_view.comment.content == '' && comment_view.comment.removed) {
comment_view.comment.content = `*Removed by Moderator — [${t.get('routes.modlog.title')}](/modlog?comment=${comment_view.comment.id})*`
}
const node: CommentNodeI = {
comment_view,
children: [],
depth: depth,
expanded: true,
}
min_depth = Math.min(min_depth, depth)
if (filter(comment_view)) {
map.set(comment_view.comment.id, { ...node })
}
}
const tree: CommentNodeI[] = []
// push all nodes at the minimum depth to the top of the tree
for (const comment_view of comments) {
const cNode = map.get(comment_view.comment.id)
if (cNode && cNode.depth == min_depth) {
tree.push(cNode)
}
}
for (const comment_view of comments) {
const child = map.get(comment_view.comment.id)
if (child) {
const parent_id = getCommentParentId(comment_view.comment)
if (parent_id) {
const parent = map.get(parent_id)
// Necessary because blocked comment might not exist
if (parent) {
parent.children.push(child)
}
}
}
}
return tree
}
export function searchCommentTree(
tree: CommentNodeI[],
id: number,
): CommentNodeI | undefined {
for (const node of tree) {
if (node.comment_view.comment.id === id) {
return node
}
for (const child of node.children) {
const res = searchCommentTree([child], id)
if (res) {
return res
}
}
}
return undefined
}
export function insertCommentIntoTree(
tree: CommentNodeI[],
cv: CommentView,
parentComment: boolean,
) {
// Building a fake node to be used for later
const node: CommentNodeI = {
comment_view: cv,
children: [],
depth: 0,
}
const parentId = getCommentParentId(cv.comment)
if (parentId) {
const parent_comment = searchCommentTree(tree, parentId)
if (parent_comment) {
node.depth = parent_comment.depth + 1
parent_comment.children.unshift(node)
}
} else if (!parentComment) {
tree.unshift(node)
}
}
@@ -0,0 +1,365 @@
<script lang="ts" module>
export async function block(id: number, block: boolean) {
try {
const loading = toast({
content: ``,
loading: true,
})
await getClient().blockCommunity({
community_id: id,
block: block,
})
removeToast(loading)
toast({
content: !block
? t.get('toast.unblockedCommunity')
: t.get('toast.blockedCommunity'),
type: 'success',
})
return block
} catch (err) {
toast({ content: errorMessage(err as string), type: 'error' })
return !block
}
}
export async function purgeCommunity(id: number) {
const purgeToast = toast({ content: '', loading: true })
try {
await client().purgeCommunity({
community_id: id,
})
removeToast(purgeToast)
toast({ content: t.get('toast.purgedCommunity'), type: 'success' })
} catch (err) {
toast({ content: errorMessage(err as string), type: 'error' })
}
}
export async function blockInstance(id: number) {
try {
const loading = toast({
content: ``,
loading: true,
})
await getClient().blockInstance({
instance_id: id,
block: true,
})
removeToast(loading)
toast({
content: `Successfully blocked that instance.`,
type: 'success',
})
} catch (err) {
toast({ content: errorMessage(err as string), type: 'error' })
}
}
</script>
<script lang="ts">
import { profile } from '$lib/app/auth.svelte.js'
import { client, getClient } from '$lib/api/client.svelte'
import type { CommunityModeratorView, CommunityView } from '$lib/api/types'
import { amMod, isAdmin } from '$comp/lemmy/moderation/moderation.js'
import Markdown from '$lib/app/markdown/Markdown.svelte'
import Avatar from '$lib/ui/generic/Avatar.svelte'
import EndPlaceholder from '$lib/ui/layout/EndPlaceholder.svelte'
import Entity from '$lib/ui/generic/Entity.svelte'
import Expandable from 'mono-svelte/disclosure/Expandable.svelte'
import LabelStat from '$lib/ui/info/LabelStat.svelte'
import SidebarButton from '$comp/ui/sidebar/SidebarButton.svelte'
import { t } from '$lib/app/i18n'
import { errorMessage } from '$lib/lemmy/error'
import { userLink } from '$lib/util.svelte'
import { addSubscription } from '$lib/lemmy/user.js'
import { settings } from '$lib/settings.svelte'
import { fullCommunityName } from '$lib/util.svelte.js'
import {
action,
Button,
Menu,
MenuButton,
Modal,
modal,
removeToast,
Spinner,
toast,
} from 'mono-svelte'
import {
BuildingOffice2,
Check,
Cog6Tooth,
EllipsisHorizontal,
Fire,
Icon,
Newspaper,
NoSymbol,
Plus,
ShieldCheck,
Tag,
} from 'svelte-hero-icons'
import ItemList from '../generic/ItemList.svelte'
import CommunityFlair from './CommunityFlair.svelte'
let loading = $state({
blocking: false,
subscribing: false,
})
async function subscribe(community: CommunityView) {
if (!profile.current?.jwt) return
loading.subscribing = true
const subscribed =
community.subscribed == 'Subscribed' || community.subscribed == 'Pending'
try {
await getClient().followCommunity({
community_id: community.community.id,
follow: !subscribed,
})
} catch (err) {
toast({ content: errorMessage(err as string), type: 'error' })
}
community.subscribed = subscribed ? 'NotSubscribed' : 'Subscribed'
addSubscription(community.community, !subscribed)
loading.subscribing = false
}
let setFlair = $state(false)
interface Props {
community_view: CommunityView | Promise<CommunityView>
moderators?: CommunityModeratorView[]
class?: string
}
let {
community_view = $bindable(),
moderators = [],
class: clazz = '',
}: Props = $props()
</script>
{#await community_view}
<div
class="w-full h-full grid place-items-center"
role="status"
aria-label={$t('aria.loading')}
>
<Spinner width={24} />
</div>
{:then community_view}
<Modal title={$t('cards.community.flair')} bind:open={setFlair}>
<CommunityFlair
community={community_view.community.id}
onsubmit={() => (setFlair = !setFlair)}
/>
</Modal>
<aside
class={[
'min-w-full pt-0 text-slate-600 dark:text-zinc-400 flex flex-col gap-1',
clazz,
]}
>
<div class="px-3 overflow-hidden">
<Entity
name={community_view.community.title}
label="!{fullCommunityName(
community_view.community.name,
community_view.community.actor_id,
)}"
>
{#snippet customIcon()}
<Avatar
width={32}
url={community_view.community.icon}
alt={community_view.community.name}
circle={false}
/>
{/snippet}
</Entity>
</div>
<EndPlaceholder size="xs" margin="sm">
{$t('form.post.community')}
</EndPlaceholder>
{#if profile.current?.jwt}
{@const subscribed = profile.current.user?.follows.some(
(i) => i.community.id == community_view.community.id,
)}
<Button
disabled={loading.subscribing}
loading={loading.subscribing}
size="md"
rounding="xl"
color={subscribed ? 'secondary' : 'primary'}
onclick={() => subscribe(community_view)}
class="px-4 relative z-[inherit]"
alignment="left"
icon={community_view.subscribed == 'Subscribed' ? Check : Plus}
>
{subscribed
? $t('cards.community.subscribed')
: $t('cards.community.subscribe')}
</Button>
{#if client().setFlair}
<SidebarButton
onclick={() => (setFlair = !setFlair)}
rounding="xl"
icon={Tag}
label={$t('cards.community.flair')}
/>
{/if}
{/if}
{#if profile.current?.user && amMod(profile.current.user, community_view.community)}
<SidebarButton
href="/c/{fullCommunityName(
community_view.community.name,
community_view.community.actor_id,
)}/settings"
rounding="xl"
icon={Cog6Tooth}
label={$t('routes.profile.edit')}
/>
{/if}
<Menu placement="bottom-start">
{#snippet target(attachment)}
<SidebarButton
{@attach attachment}
label={$t('post.actions.more.label')}
rounding="xl"
icon={EllipsisHorizontal}
/>
{/snippet}
<MenuButton href="/modlog?community={community_view.community.id}">
<Icon src={Newspaper} size="16" mini />
{$t('cards.community.modlog')}
</MenuButton>
{#if profile.current?.jwt}
{#if profile.current.user && amMod(profile.current.user, community_view.community)}
<MenuButton
color="success-subtle"
href="/moderation?community={community_view.community.id}"
>
<Icon src={ShieldCheck} size="16" micro />
{$t('routes.moderation.feed')}
</MenuButton>
{/if}
<MenuButton
color="danger-subtle"
size="lg"
onclick={() =>
block(community_view.community.id, !community_view.blocked)}
icon={NoSymbol}
>
{community_view.blocked
? $t('cards.community.unblock')
: $t('cards.community.block')}
</MenuButton>
{#if profile.current?.user}
<MenuButton
color="danger-subtle"
size="lg"
onclick={() => blockInstance(community_view.community.instance_id)}
icon={BuildingOffice2}
>
{$t('cards.community.blockInstance')}
</MenuButton>
{/if}
{#if profile.current?.user && isAdmin(profile.current.user)}
<MenuButton
color="danger-subtle"
onclick={() =>
modal({
title: $t('admin.purgeCommunity.title'),
body: `${community_view.community.title}: ${$t('admin.purgeCommunity.warning')}`,
actions: [
action({
close: true,
content: $t('common.cancel'),
}),
action({
action: () => purgeCommunity(community_view.community.id),
close: true,
content: $t('admin.purge'),
type: 'danger',
icon: Fire,
}),
],
dismissable: true,
type: 'error',
})}
icon={Fire}
>
{$t('admin.purge')}
</MenuButton>
{/if}
{/if}
</Menu>
<EndPlaceholder size="xs" margin="sm">
{$t('cards.site.stats')}
</EndPlaceholder>
<div class="flex flex-row gap-4 flex-wrap px-3">
<LabelStat
label={$t('cards.community.members')}
content={community_view.counts.subscribers.toString()}
formatted
/>
<LabelStat
label={$t('content.posts')}
content={community_view.counts.posts.toString()}
formatted
/>
<LabelStat
label={$t('cards.community.activeDay')}
content={community_view.counts.users_active_day.toString()}
formatted
/>
</div>
<EndPlaceholder size="xs" margin="sm">
{$t('common.info')}
</EndPlaceholder>
<div class="space-y-3 px-1.5 text-sm">
<Expandable bind:open={settings.expand.about}>
{#snippet title()}
<span class="px-2 py-1 w-full">
{$t('cards.site.about')}
</span>
{/snippet}
<Markdown source={community_view.community.description} />
</Expandable>
{#if moderators && moderators.length > 0}
<Expandable bind:open={settings.expand.team}>
{#snippet title()}
<span class="px-2 py-1 w-full">
{$t('cards.community.moderators')}
</span>
{/snippet}
<ItemList
items={moderators.map((i) => ({
id: i.moderator.id,
name: i.moderator.display_name || i.moderator.name,
url: userLink(i.moderator),
avatar: i.moderator.avatar,
instance: new URL(i.moderator.actor_id).hostname,
}))}
/>
</Expandable>
{/if}
</div>
</aside>
{/await}
@@ -0,0 +1,46 @@
<script lang="ts">
import { client } from '$lib/api/client.svelte'
import { t } from '$lib/app/i18n'
import { errorMessage } from '$lib/lemmy/error'
import { Button, TextInput, toast } from 'mono-svelte'
interface Props {
flair?: string
community: number
onsubmit?: (flair: string) => void
}
let { flair: passedFlair = '', community, onsubmit }: Props = $props()
let flair = $state(passedFlair)
let loading = $state(false)
async function submit() {
try {
loading = true
if (!client().setFlair) throw new Error('unsupported')
await client().setFlair!({ community_id: community, flair_text: flair })
onsubmit?.(flair)
} catch (err) {
toast({
content: errorMessage(err as string),
type: 'error',
})
}
loading = false
}
</script>
<form
onsubmit={(e) => {
e.preventDefault()
submit()
}}
class="contents"
>
<TextInput bind:value={flair} label={$t('nav.commands.content')} required />
<Button {loading} submit color="primary" size="lg">
{$t('form.submit')}
</Button>
</form>
@@ -0,0 +1,247 @@
<script lang="ts">
import { goto } from '$app/navigation'
import { profile } from '$lib/app/auth.svelte.js'
import ImageInputUpload from '$comp/form/ImageInputUpload.svelte'
import MarkdownEditor from '$lib/app/markdown/MarkdownEditor.svelte'
import { t } from '$lib/app/i18n'
import { client, site } from '$lib/api/client.svelte'
import { errorMessage } from '$lib/lemmy/error'
import { addSubscription } from '$lib/lemmy/user.js'
import {
Badge,
Button,
Label,
MenuButton,
Switch,
TextInput,
toast,
Option,
Select,
Material,
Menu,
} from 'mono-svelte'
import { GlobeAlt, Icon, MapPin, Plus } from 'svelte-hero-icons'
import { Header } from '$comp/ui/layout'
interface Props {
/**
* The community ID to edit.
*/
edit?: number
formData?: {
name: string
displayName: string
icon?: string
banner?: string
sidebar?: string
nsfw: boolean
postsLockedToModerators: boolean
submitting: boolean
visibility: 'Public' | 'LocalOnly'
languages?: number[]
}
formtitle?: import('svelte').Snippet
}
let {
edit = undefined,
formData: passedFormData = $bindable({
name: '',
displayName: '',
sidebar: '',
nsfw: false,
postsLockedToModerators: false,
submitting: false,
visibility: 'Public',
languages: undefined,
}),
formtitle,
}: Props = $props()
let formData = $state(passedFormData)
async function submit() {
if (!profile.current?.jwt) return
if ((!edit && formData.name == '') || formData.displayName == '') return
formData.submitting = true
try {
const res = edit
? await client().editCommunity({
title: formData.displayName,
description: formData.sidebar,
nsfw: formData.nsfw,
posting_restricted_to_mods: formData.postsLockedToModerators,
icon: formData.icon,
banner: formData.banner,
community_id: edit,
visibility: formData.visibility,
discussion_languages: formData.languages,
})
: await client().createCommunity({
name: formData.name,
title: formData.displayName,
description: formData.sidebar,
nsfw: formData.nsfw,
posting_restricted_to_mods: formData.postsLockedToModerators,
icon: formData.icon,
banner: formData.banner,
visibility: formData.visibility,
discussion_languages: formData.languages,
})
toast({
content: $t('toast.updatedCommunity'),
type: 'success',
})
if (profile.current.user) {
const c = profile.current.user.moderates
.map((m) => m.community.id)
.indexOf(res.community_view.community.id)
if (c != -1) {
profile.current.user.moderates[c] = {
community: res.community_view.community,
moderator: profile.current.user.local_user_view.person,
}
} else {
profile.current.user = {
...profile.current.user,
moderates: [
...profile.current.user.moderates,
{
community: res.community_view.community,
moderator: profile.current.user.local_user_view.person,
},
],
}
}
addSubscription(res.community_view.community, true)
}
if (!edit)
goto(
`/c/${res.community_view.community.name}@${
new URL(res.community_view.community.actor_id).hostname
}`,
)
} catch (err) {
toast({
content: errorMessage(err as string),
type: 'error',
})
}
formData.submitting = false
}
</script>
<form
onsubmit={(e) => {
e.preventDefault()
submit()
}}
class="flex flex-col gap-4 h-full w-full"
>
{#if formtitle}{@render formtitle()}{:else}
<Header>{$t('form.post.community')}</Header>
{/if}
<TextInput
required
label={$t('form.name')}
bind:value={formData.name}
oninput={() => {
formData.name = formData.name.toLowerCase().replaceAll(' ', '_')
}}
disabled={edit != undefined}
/>
<TextInput
required
label={$t('form.profile.displayName')}
bind:value={formData.displayName}
/>
<div class="flex flex-row gap-4 flex-wrap *:flex-1">
<ImageInputUpload
bind:imageUrl={formData.icon}
label={$t('routes.admin.config.icon')}
/>
<ImageInputUpload
bind:imageUrl={formData.banner}
label={$t('routes.admin.config.banner')}
/>
</div>
<MarkdownEditor
previewButton
label={$t('routes.admin.config.sidebar')}
bind:value={formData.sidebar}
/>
<Switch bind:checked={formData.nsfw}>{$t('post.badges.nsfw')}</Switch>
<Switch bind:checked={formData.postsLockedToModerators}>
Only moderators can post
</Switch>
<Select label="Visibility" class="w-max" bind:value={formData.visibility}>
<Option icon={GlobeAlt} value="Public">Public</Option>
<Option icon={MapPin} value="LocalOnly">Local Only</Option>
</Select>
<div class="space-y-1">
<Label>{$t('form.profile.languages.title')}</Label>
<Material rounding="xl" color="uniform" class="dark:bg-zinc-950">
{#if site.data}
<div class="flex gap-2 flex-wrap flex-row">
<Menu class="gap-px">
{#snippet target(attachment)}
<button {@attach attachment} type="button">
<Badge color="blue-subtle">
<Icon src={Plus} micro size="14" />
{$t('common.add')}
</Badge>
</button>
{/snippet}
{#each site.data.all_languages.filter((l) => !formData.languages?.includes(l.id)) as language (language.id)}
<MenuButton
class="min-h-[16px] py-0"
onclick={() => {
formData.languages = [
...(formData.languages ?? []),
language.id,
]
}}
>
{language.name}
</MenuButton>
{/each}
</Menu>
{#each formData.languages ?? [] as languageId, index (languageId)}
{@const language = site.data.all_languages.find(
(l) => l.id == languageId,
)}
<button
type="button"
class="hover:brightness-150 transition-all"
onclick={() => {
formData.languages?.splice(index, 1)
}}
>
<Badge class="cursor-pointer">{language?.name}</Badge>
</button>
{/each}
</div>
{/if}
</Material>
</div>
<Button
submit
color="primary"
size="lg"
class="mt-auto"
loading={formData.submitting}
disabled={formData.submitting}
>
{edit ? $t('common.save') : $t('form.submit')}
</Button>
</form>
@@ -0,0 +1,284 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte'
import EntityHeader from '$lib/ui/generic/EntityHeader.svelte'
import Expandable from 'mono-svelte/disclosure/Expandable.svelte'
import { formatRelativeDate } from '$comp/util/RelativeDate.svelte'
import { publishedToDate } from '$comp/util/date'
import { t } from '$lib/app/i18n'
import { userLink } from '$lib/util.svelte'
import { settings } from '$lib/settings.svelte'
import { fullCommunityName } from '$lib/util.svelte'
import type {
Community,
CommunityAggregates,
CommunityModeratorView,
SubscribedType,
} from '$lib/api/types'
import {
action,
Button,
Menu,
MenuButton,
Modal,
modal,
toast,
} from 'mono-svelte'
import {
BuildingOffice2,
Check,
Cog6Tooth,
EllipsisHorizontal,
Fire,
Icon,
Newspaper,
NoSymbol,
Plus,
ShieldCheck,
Tag,
} from 'svelte-hero-icons'
import Subscribe from '../../../../routes/communities/Subscribe.svelte'
import ItemList from '../generic/ItemList.svelte'
import { amMod, isAdmin } from '../moderation/moderation'
import { block, blockInstance, purgeCommunity } from './CommunityCard.svelte'
import CommunityFlair from './CommunityFlair.svelte'
import { client } from '$lib/api/client.svelte'
interface Props {
community: Community
subscribed: SubscribedType
counts?: CommunityAggregates | undefined
moderators?: CommunityModeratorView[]
blocked?: boolean
banner?: boolean
class?: string
compact?: 'always' | 'lg'
avatarCircle?: boolean
}
let {
community = $bindable(),
subscribed = $bindable(),
counts = undefined,
moderators = [],
blocked = false,
banner = !(settings.nsfwBlur && community.nsfw),
class: clazz = '',
compact,
...rest
}: Props = $props()
let setFlair = $state(false)
</script>
<Modal title={$t('cards.community.flair')} bind:open={setFlair}>
<CommunityFlair
community={community.id}
onsubmit={() => (setFlair = !setFlair)}
/>
</Modal>
<EntityHeader
{...rest}
{compact}
banner={banner ? community.banner : undefined}
avatar={community.icon}
name={community.title}
url="/c/{fullCommunityName(community.name, community.actor_id)}"
stats={counts
? [
{
name: $t('cards.community.members'),
value: counts.subscribers.toString(),
},
{
name: $t('content.posts'),
value: counts.posts.toString(),
},
{
name: $t('cards.community.activeDay'),
value: counts.users_active_day.toString(),
},
{
name: $t('stats.created'),
format: false,
value: formatRelativeDate(publishedToDate(community.published), {
style: 'short',
}).toString(),
},
]
: []}
bio={community.description}
class={['tracking-normal', clazz]}
>
{#snippet nameDetail()}
<button
onclick={() => {
navigator?.clipboard?.writeText?.(
`!${fullCommunityName(community.name, community.actor_id)}`,
)
toast({ content: $t('toast.copied') })
}}
class="text-sm flex gap-0 items-center"
>
!{fullCommunityName(community.name, community.actor_id)}
</button>
{/snippet}
{#if moderators.length > 0}
<Expandable class={[compact == 'lg' && 'lg:hidden']}>
{#snippet title()}
{$t('cards.community.moderators')}
<hr class="flex-1 border-slate-200 dark:border-zinc-800 mx-3" />
{/snippet}
<ItemList
items={moderators.map((m) => ({
id: m.moderator.id,
name: m.moderator.name,
url: userLink(m.moderator),
avatar: m.moderator.avatar,
instance: new URL(m.moderator.actor_id).hostname,
}))}
/>
</Expandable>
{/if}
<div
class={[
'flex items-center gap-2 h-max w-max',
compact == 'lg' && 'lg:hidden',
]}
>
{#if profile.current?.jwt}
<Subscribe
community={{
community: community,
banned_from_community: false,
blocked: false,
counts: counts!,
subscribed: subscribed,
}}
>
{#snippet children({ subscribe, subscribing })}
<Button
disabled={subscribing}
loading={subscribing}
color={subscribed == 'NotSubscribed' ? 'primary' : 'secondary'}
onclick={async () => {
subscribed =
(await subscribe())?.community_view.subscribed ??
'NotSubscribed'
}}
class="relative z-[inherit]"
rounding="pill"
icon={subscribed != 'NotSubscribed' ? Check : Plus}
>
{subscribed == 'Subscribed' || subscribed == 'Pending'
? $t('cards.community.subscribed')
: $t('cards.community.subscribe')}
</Button>
{/snippet}
</Subscribe>
{#if client().setFlair}
<Button
size="custom"
class="h-9 aspect-square"
rounding="pill"
onclick={() => (setFlair = !setFlair)}
aria-label={$t('cards.community.flair')}
>
<Icon src={Tag} size="16" micro />
</Button>
{/if}
{/if}
{#if profile.current?.user && profile.current.user.moderates
.map((c) => c.community.id)
.includes(community.id)}
<Button
color="secondary"
size="custom"
rounding="pill"
class="h-9 aspect-square"
href="/c/{fullCommunityName(
community.name,
community.actor_id,
)}/settings"
>
<Icon src={Cog6Tooth} size="16" mini />
</Button>
{/if}
<Menu placement="top-end">
{#snippet target(attachment)}
<Button
{@attach attachment}
size="custom"
rounding="pill"
class="h-8.5 aspect-square"
icon={EllipsisHorizontal}
></Button>
{/snippet}
<MenuButton href="/modlog?community={community.id}">
<Icon src={Newspaper} size="16" mini />
{$t('cards.community.modlog')}
</MenuButton>
{#if profile.current.user && amMod(profile.current.user, community)}
<MenuButton
color="success-subtle"
href="/moderation?community={community.id}"
>
<Icon src={ShieldCheck} size="16" micro />
{$t('routes.moderation.feed')}
</MenuButton>
{/if}
{#if profile.current?.jwt}
<MenuButton
color="danger-subtle"
size="lg"
onclick={() => block(community.id, !blocked)}
icon={NoSymbol}
>
{blocked
? $t('cards.community.unblock')
: $t('cards.community.block')}
</MenuButton>
{#if profile.current?.user}
<MenuButton
color="danger-subtle"
size="lg"
onclick={() => blockInstance(community.instance_id)}
icon={BuildingOffice2}
>
{$t('cards.community.blockInstance')}
</MenuButton>
{/if}
{#if profile.current?.user && isAdmin(profile.current.user)}
<MenuButton
color="danger-subtle"
onclick={() =>
modal({
title: $t('admin.purgeCommunity.title'),
body: `${community.title}: ${$t('admin.purgeCommunity.warning')}`,
actions: [
action({
close: true,
content: $t('common.cancel'),
}),
action({
action: () => purgeCommunity(community.id),
close: true,
content: $t('admin.purge'),
type: 'danger',
icon: Fire,
}),
],
dismissable: true,
type: 'error',
})}
icon={Fire}
>
{$t('admin.purge')}
</MenuButton>
{/if}
{/if}
</Menu>
</div>
</EntityHeader>
@@ -0,0 +1,165 @@
<script lang="ts">
import CommonItem from '$comp/ui/layout/CommonItem.svelte'
import { profile } from '$lib/app/auth.svelte.js'
import { client } from '$lib/api/client.svelte'
import type { CommunityView } from '$lib/api/types'
import { locale, t } from '$lib/app/i18n'
import { addSubscription } from '$lib/lemmy/user.js'
import { fullCommunityName } from '$lib/util.svelte.js'
import { Button, modal } from 'mono-svelte'
import {
Check,
ExclamationTriangle,
Icon,
InformationCircle,
MapPin,
NoSymbol,
Plus,
Trash,
} from 'svelte-hero-icons'
import { SvelteURL } from 'svelte/reactivity'
import Subscribe from '../../../../routes/communities/Subscribe.svelte'
import CommunityCard from './CommunityCard.svelte'
import type { Snippet } from 'svelte'
interface Props {
community: CommunityView
view?: 'cozy' | 'compact'
showCounts?: boolean
resolveObject?: boolean
children?: Snippet
}
let {
community = $bindable(),
view = 'compact',
showCounts = true,
resolveObject,
children,
}: Props = $props()
</script>
{#snippet communityInfo()}
<CommunityCard community_view={community} />
{/snippet}
<CommonItem
icon={community.community.icon}
href="/c/{fullCommunityName(
community.community.name,
community.community.actor_id,
)}"
title={community.community.title}
detail="{new SvelteURL(community.community.actor_id).hostname}{!showCounts
? ` • ${Intl.NumberFormat($locale, { notation: 'compact' }).format(community.counts.subscribers)}`
: ''}"
orientation={view == 'cozy' ? 'vertical' : 'horizontal'}
>
{#if !children}
{#if community.community.deleted}
<Icon
src={Trash}
class="text-red-500 inline"
micro
size="14"
title={$t('post.badges.deleted')}
/>
{/if}
{#if community.community.nsfw}
<Icon
src={ExclamationTriangle}
class="text-red-500 inline"
micro
size="14"
title={$t('post.badges.nsfw')}
/>
{/if}
{#if community.banned_from_community}
<Icon
src={NoSymbol}
class="text-red-500 inline"
micro
size="14"
title={$t('comment.banned')}
/>
{/if}
{#if community.community.visibility == 'LocalOnly'}
<Icon
src={MapPin}
class="text-green-500 inline"
micro
size="14"
title={$t('routes.admin.config.listingType.local')}
/>
{/if}
<Button
rounding="xl"
color="ghost"
onclick={() =>
modal({ title: $t('form.post.community'), snippet: communityInfo })}
aria-label={$t('common.info')}
size="square-md"
>
<Icon src={InformationCircle} size="16" mini />
</Button>
<Subscribe {community}>
{#snippet children({ subscribe, subscribing })}
{@const subscribed =
community.subscribed == 'Subscribed' ||
community.subscribed == 'Pending'}
<Button
disabled={subscribing || !profile.current?.jwt}
loading={subscribing}
onclick={async () => {
const object =
resolveObject &&
(await client().resolveObject({
q: community.community.actor_id,
}))
const res = object
? await subscribe(object.community?.community.id)
: await subscribe()
if (res) {
const newSubscribed =
res.community_view.subscribed != 'NotSubscribed'
? 'Subscribed'
: 'NotSubscribed'
community.subscribed = newSubscribed
addSubscription(
community.community,
newSubscribed == 'Subscribed',
)
}
}}
size="custom"
title={subscribed
? $t('cards.community.subscribed')
: $t('cards.community.subscribe')}
color={subscribed ? 'secondary' : 'primary'}
rounding="xl"
class={[
subscribed && 'text-slate-600 dark:text-zinc-400',
' h-8.5 rounded-full',
view == 'compact'
? 'aspect-square @md:px-2 @md:min-w-30 @md:aspect-auto'
: 'px-3',
]}
icon={subscribed ? Check : Plus}
>
<span class={[view == 'compact' && 'hidden', '@md:block']}>
{#if subscribed}
{$t('cards.community.subscribed')}
{:else}
{$t('cards.community.subscribe')}
{/if}
</span>
</Button>
{/snippet}
</Subscribe>
{:else}
{@render children?.()}
{/if}
</CommonItem>
@@ -0,0 +1,95 @@
<script lang="ts">
import type { Community } from '$lib/api/types'
import Avatar from '$lib/ui/generic/Avatar.svelte'
import { t } from '$lib/app/i18n'
import { settings } from '$lib/settings.svelte.js'
import { communityLink } from '$lib/util.svelte'
import { ExclamationTriangle, Icon } from 'svelte-hero-icons'
import type { HTMLAnchorAttributes } from 'svelte/elements'
interface Props extends HTMLAnchorAttributes {
community: Community
avatar?: boolean
name?: boolean
avatarSize?: number
showInstance?: boolean
displayName?: boolean
badges?: {
nsfw: boolean
}
class?: string
instanceClass?: string
}
let {
community,
avatar = false,
name = true,
avatarSize = 24,
showInstance = settings.showInstances.community,
displayName = true,
badges = {
nsfw: false,
},
class: clazz = '',
instanceClass = '',
...rest
}: Props = $props()
</script>
<a
{...rest}
class={[
'items-center inline-flex flex-row gap-2 hover:underline max-w-full min-w-0',
clazz,
]}
href={communityLink(community)}
data-sveltekit-preload-data="tap"
>
{#if avatar && !badges.nsfw}
<Avatar url={community.icon} alt={community.name} width={avatarSize} />
{/if}
{#if name}
<span class="flex gap-0 items-center max-w-full min-w-0 shrink">
<span class="font-medium username-text">
{displayName ? community.title : community.name}
</span>
{#if showInstance}
<span
class="text-slate-500 dark:text-zinc-500 font-normal
instance-text shrink {instanceClass || ''}"
>
@{new URL(community.actor_id).hostname}
</span>
{/if}
</span>
{/if}
{#if badges}
{#if badges.nsfw}
<Icon
src={ExclamationTriangle}
size="14"
micro
title={$t('post.badges.nsfw')}
class="text-red-600 dark:text-red-400"
/>
{/if}
{/if}
</a>
<style>
.instance-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
flex: 1;
}
.username-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
@@ -0,0 +1,79 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte'
import Avatar from '$lib/ui/generic/Avatar.svelte'
import SidebarButton from '$comp/ui/sidebar/SidebarButton.svelte'
import { addFavorite } from '$lib/lemmy/item'
import { hasFavorite } from '$lib/lemmy/user'
import type { Community } from '$lib/api/types'
import { Button } from 'mono-svelte'
import { Icon, Star, Trash } from 'svelte-hero-icons'
import { flip } from 'svelte/animate'
import { expoOut } from 'svelte/easing'
interface Props {
items: Community[]
isFavorites?: boolean
}
let { items, isFavorites = false }: Props = $props()
</script>
{#each items.toSorted( (a, b) => a.title.localeCompare(b.title), ) as follow (follow.id)}
<div
class="inline-flex w-full items-center pl-3
transition-colors rounded-lg"
animate:flip={{ duration: 500, easing: expoOut }}
>
<div class="flex-none grid group">
{#if profile && !hasFavorite(profile.current, follow.id)}
<Button
rounding="pill"
size="custom"
class="hidden group-hover:inline-flex opacity-0 group-hover:opacity-100 transition-all z-20
items-center justify-center box-border w-7 h-7"
style="grid-column: 1; grid-row: 1;"
onclick={() => addFavorite(follow)}
>
<Icon src={Star} size="16" mini />
</Button>
{:else if isFavorites && profile && hasFavorite(profile.current, follow.id)}
<Button
rounding="pill"
size="custom"
class="hidden group-hover:inline-flex opacity-0 group-hover:opacity-100 transition-all z-20
items-center justify-center box-border w-7 h-7"
style="grid-column: 1; grid-row: 1;"
onclick={() => addFavorite(follow, false)}
>
<Icon src={Trash} size="16" mini />
</Button>
{/if}
<Avatar
url={follow.icon}
alt={follow.name}
title={follow.title}
width={28}
class={!isFavorites &&
profile &&
hasFavorite(profile.current, follow.id)
? ''
: 'group-hover:hidden'}
/>
</div>
<SidebarButton
class="font-normal w-full h-max"
color="none"
alignment="left"
href="/c/{follow.name}@{new URL(follow.actor_id).hostname}"
>
{#snippet label()}
<div class="flex flex-col max-w-full break-words">
<span>{follow.title}</span>
<span class="text-xs text-slate-600 dark:text-zinc-400">
{new URL(follow.actor_id).hostname}
</span>
</div>
{/snippet}
</SidebarButton>
</div>
{/each}
@@ -0,0 +1,20 @@
<script lang="ts">
import Avatar from '$lib/ui/generic/Avatar.svelte'
import type { Community } from '$lib/api/types'
interface Props {
community: Community
}
let { community }: Props = $props()
</script>
<div class="flex flex-row gap-3 items-center">
<Avatar width={48} url={community.icon} alt={community.name} />
<div class="flex flex-col gap-0">
<h1 class="font-bold text-xl">{community.title}</h1>
<span class="dark:text-zinc-400 text-slate-600 text-sm">
!{community.name}@{new URL(community.actor_id).hostname}
</span>
</div>
</div>
+157
View File
@@ -0,0 +1,157 @@
import { browser } from '$app/environment'
import { profile } from '$lib/app/auth.svelte'
import type {
CommentView,
CommunityView,
FeedView,
GetComments,
GetCommunityResponse,
GetPersonDetails,
GetPersonDetailsResponse,
GetPost,
GetPosts,
PostView,
TopicView,
} from '$lib/client/types'
import { recursiveEqual } from '$lib/util.svelte'
import { SvelteMap } from 'svelte/reactivity'
type FetchFn<P, R> = (params: P) => R
export class Feed<Params, Response> {
#data = $state<Response>()
#fetch: FetchFn<Params, Response>
#lastParams?: Params
constructor(fetch: FetchFn<Params, Response>) {
this.#fetch = fetch
}
async load(params: Params) {
if (
this.#lastParams &&
params &&
!recursiveEqual<Params>(params, this.#lastParams)
) {
this.#data = undefined
}
this.#lastParams = params
if (this.#data == null) this.#data = await this.#fetch(params)
return this.#data
}
peek() {
return this.#data
}
update(value: Response) {
this.#data = value
}
}
export interface FeedTypes {
'/': [
GetPosts,
{
posts: PostView[]
next_page?: string
params: GetPosts & { page_cursor: string }
client: {
itemHeights?: (number | null)[]
lastSeen?: number
}
},
]
'/c/[name]': [
GetPosts,
{
posts: PostView[]
community: GetCommunityResponse
next_page?: string
params: GetPosts & { page_cursor: string }
client: { itemHeights?: (number | null)[]; lastSeen?: number }
},
]
'/u/[name]': [GetPersonDetails, { data: GetPersonDetailsResponse }]
'/post/[instance]/[id=integer]': [
{
posts: GetPost
comments: GetComments
preload?: PostView
thread: {
showContext?: boolean
singleThread?: boolean
focus?: string
}
},
{
post: PostView
comments: Promise<CommentView[]>
meta: Promise<{
community_view: CommunityView
cross_posts: PostView[]
post_view: PostView
}>
params: {
posts: GetPost
comments: GetComments
thread: {
showContext?: boolean
singleThread?: boolean
focus?: string
}
}
},
]
'/f/[id]': [
GetPosts,
{
posts: PostView[]
next_page?: string
params: GetPosts & { page_cursor: string }
feed: Promise<FeedView | undefined>
client: {
itemHeights?: (number | null)[]
lastSeen?: number
}
},
]
'/topic/[id]': [
GetPosts,
{
posts: PostView[]
next_page?: string
params: GetPosts & { page_cursor: string }
topic: Promise<TopicView | undefined>
client: {
itemHeights?: (number | null)[]
lastSeen?: number
}
},
]
}
const feeds = new SvelteMap<keyof FeedTypes, Feed<any, any>>()
export function feed<Type extends keyof FeedTypes>(
id: Type,
init: (params: FeedTypes[Type][0]) => Promise<FeedTypes[Type][1]>,
): Feed<FeedTypes[Type][0], FeedTypes[Type][1]> {
const feed = feeds.get(id)
if (browser && feed) return feed
const feedData = new Feed<any, any>(init)
feeds.set(id, feedData)
return feedData
}
// feed hooks
$effect.root(() => {
$effect(() => {
if (profile.meta.profile) feeds.clear()
})
})
+76
View File
@@ -0,0 +1,76 @@
<script lang="ts">
import { page } from '$app/state'
import { profile } from '$lib/app/auth.svelte'
import { searchParam } from '$lib/util.svelte'
import { Select } from 'mono-svelte'
import {
ChartBar,
GlobeAmericas,
Icon,
MapPin,
Newspaper,
ShieldCheck,
} from 'svelte-hero-icons'
import { amModOfAny } from '../moderation/moderation'
import { t } from '$lib/app/i18n'
import Option from 'mono-svelte/forms/select/Option.svelte'
import type { SelectProps } from 'mono-svelte/forms/select/Select.svelte'
import { client } from '$lib/api/client.svelte'
import { PiefedClient } from '$lib/api/piefed/adapter'
interface Props extends SelectProps<string> {
selected: string
navigate?: boolean
changeDefault?: boolean
showLabel?: boolean
}
let {
selected = $bindable(),
navigate = true,
showLabel = true,
children,
...rest
}: Props = $props()
</script>
<Select
{...rest}
bind:value={selected}
onchange={() => {
if (navigate) searchParam(page.url, 'type', selected, 'page', 'cursor')
}}
>
{#snippet customLabel()}
{#if showLabel}
<span class="flex items-center gap-1">
<Icon src={GlobeAmericas} size="16" micro />
{$t('filter.location.label')}
</span>
{/if}
{/snippet}
<Option value="All" icon={GlobeAmericas}>
{$t('filter.location.all')}
</Option>
{#if client() instanceof PiefedClient}
<Option value="Popular" icon={ChartBar}>
{$t('filter.location.popular')}
</Option>
{/if}
<Option value="Local" icon={MapPin}>{$t('filter.location.local')}</Option>
<Option
value="Subscribed"
disabled={profile.current?.jwt == undefined}
icon={Newspaper}
>
{$t('filter.location.subscribed')}
</Option>
<Option
value="ModeratorView"
disabled={!profile.current?.jwt || !amModOfAny(profile.current?.user)}
icon={ShieldCheck}
>
{$t('filter.location.moderator')}
</Option>
{@render children?.()}
</Select>
+139
View File
@@ -0,0 +1,139 @@
<script lang="ts">
import { page } from '$app/state'
import { client } from '$lib/api/client.svelte'
import { LemmyClient } from '$lib/api/lemmy/adapter'
import { t } from '$lib/app/i18n'
import { searchParam } from '$lib/util.svelte.js'
import { Select } from 'mono-svelte'
import Option from 'mono-svelte/forms/select/Option.svelte'
import type { SelectProps } from 'mono-svelte/forms/select/Select.svelte'
import {
ArrowTrendingDown,
ArrowTrendingUp,
Calendar,
CalendarDays,
ChartBar,
ChatBubbleLeftRight,
ChatBubbleOvalLeft,
Clock,
Fire,
Icon,
PlusCircle,
Scale,
Star,
Sun,
Trophy,
} from 'svelte-hero-icons'
interface Props extends SelectProps<string> {
selected: string
navigate?: boolean
changeDefault?: boolean
class?: string
}
let {
selected = $bindable(),
navigate = true,
class: clazz = '',
...rest
}: Props = $props()
let sort: string = $state(selected?.startsWith('Top') ? 'TopAll' : selected)
const setSelected = () => (selected = sort)
</script>
<div class="flex flex-row {clazz}">
<Select
{...rest}
class={selected?.startsWith('Top') ? 'rounded-r-none' : ''}
bind:value={sort}
onchange={() => {
setSelected()
if (navigate) searchParam(page.url, 'sort', selected, 'page', 'cursor')
}}
>
{#snippet customLabel()}
<span class="flex items-center gap-1">
<Icon src={ChartBar} size="13" micro />
{$t('filter.sort.label')}
</span>
{/snippet}
<Option value="Active" icon={ArrowTrendingUp}>
{$t('filter.sort.active')}
</Option>
<Option value="Hot" icon={Fire}>
{$t('filter.sort.hot')}
</Option>
<Option value="Scaled" icon={Scale}>
{$t('filter.sort.scaled')}
</Option>
<Option value="TopAll" icon={Trophy}>
{$t('filter.sort.top.label')}
</Option>
<Option value="New" icon={Star}>
{$t('filter.sort.new')}
</Option>
{#if client() instanceof LemmyClient}
<Option value="Old" icon={Clock}>
{$t('filter.sort.old')}
</Option>
<Option value="Controversial" icon={ArrowTrendingDown}>
{$t('filter.sort.controversial')}
</Option>
<Option value="MostComments" icon={ChatBubbleOvalLeft}>
{$t('filter.sort.mostcomments')}
</Option>
<Option value="NewComments" icon={ChatBubbleLeftRight}>
{$t('filter.sort.newcomments')}
</Option>
{/if}
</Select>
{#if selected?.startsWith('Top')}
<Select
class="border-l-0 rounded-l-none"
bind:value={selected}
onchange={() => {
sort = 'TopAll'
if (navigate) searchParam(page.url, 'sort', selected, 'page', 'cursor')
}}
>
{#snippet customLabel()}
<span class="flex items-center gap-1">
<Icon src={Clock} size="15" micro />
{$t('filter.sort.top.time.label')}
</span>
{/snippet}
<Option value="TopAll" icon={PlusCircle}>
{$t('filter.sort.top.time.all')}
</Option>
<Option value="TopNineMonths" icon={Calendar}>
{$t('filter.sort.top.time.9months')}
</Option>
<Option value="TopSixMonths" icon={Calendar}>
{$t('filter.sort.top.time.6months')}
</Option>
<Option value="TopThreeMonths" icon={Calendar}>
{$t('filter.sort.top.time.3months')}
</Option>
<Option value="TopMonth" icon={CalendarDays}>
{$t('filter.sort.top.time.month')}
</Option>
<Option value="TopWeek" icon={CalendarDays}>
{$t('filter.sort.top.time.week')}
</Option>
<Option value="TopDay" icon={Sun}>
{$t('filter.sort.top.time.day')}
</Option>
<Option value="TopTwelveHour" icon={Clock}>
{$t('filter.sort.top.time.12hours')}
</Option>
<Option value="TopSixHour" icon={Clock}>
{$t('filter.sort.top.time.6hours')}
</Option>
<Option value="TopHour" icon={Clock}>
{$t('filter.sort.top.time.hour')}
</Option>
</Select>
{/if}
</div>
+31
View File
@@ -0,0 +1,31 @@
<script lang="ts">
import { t } from '$lib/app/i18n'
import { settings } from '$lib/settings.svelte.js'
import { Select } from 'mono-svelte'
import Option from 'mono-svelte/forms/select/Option.svelte'
import type { SelectProps } from 'mono-svelte/forms/select/Select.svelte'
import { Bars3, Icon, RectangleGroup, ViewColumns } from 'svelte-hero-icons'
interface Props extends SelectProps<string> {
showLabel?: boolean
}
let { showLabel = true, ...rest }: Props = $props()
</script>
<Select {...rest} bind:value={settings.view}>
{#snippet customLabel()}
{#if showLabel}
<span class="flex items-center gap-1">
<Icon src={ViewColumns} size="14" micro />
{$t('filter.view.label')}
</span>
{/if}
{/snippet}
<Option value="cozy" icon={RectangleGroup}>
{$t('filter.view.cozy')}
</Option>
<Option value="compact" icon={Bars3}>
{$t('filter.view.compact')}
</Option>
</Select>
@@ -0,0 +1,41 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte.js'
import UserLink from '$comp/lemmy/user/UserLink.svelte'
import Markdown from '$lib/app/markdown/Markdown.svelte'
import type { PrivateMessageView } from '$lib/api/types'
interface Props {
message: PrivateMessageView
meta?: boolean
style?: string
}
let { message, meta = true, style = '' }: Props = $props()
</script>
<div class="flex flex-col gap-2 text-sm" {style}>
{#if meta}
<div class="flex flex-row gap-2 items-center flex-wrap">
<span class="font-medium text-xs">From</span>
<UserLink
showInstance={false}
user={message.creator}
avatar
avatarSize={20}
/>
{#if profile.current?.user?.local_user_view.person.id != message.recipient.id}
to
<UserLink
showInstance={false}
user={message.recipient}
avatar
avatarSize={20}
/>
{/if}
</div>
{/if}
<Markdown
rendererOptions={{ autoloadImages: false }}
source={message.private_message.content}
/>
</div>
+68
View File
@@ -0,0 +1,68 @@
import type {
CommentReplyView,
CommentView,
Person,
PersonMentionView,
PrivateMessageView,
} from '$lib/client/types'
export type InboxItemView =
| PersonMentionView
| CommentReplyView
| PrivateMessageView
export const generalizeCommentReply = (item: CommentReplyView): InboxItem => ({
type: 'comment_reply',
id: item.comment_reply.id,
published: item.comment_reply.published,
item: { ...item },
creator: item.creator,
read: item.comment_reply.read,
})
export const generalizePersonMention = (
item: PersonMentionView,
): InboxItem => ({
type: 'person_mention',
id: item.person_mention.id,
published: item.person_mention.published,
item: {
...item,
},
creator: item.creator,
read: item.person_mention.read,
})
export const generalizePrivateMessage = (
item: PrivateMessageView,
): InboxItem => ({
type: 'private_message',
id: item.private_message.id,
published: item.private_message.published,
item: item,
creator: item.creator,
read: item.private_message.read,
})
interface PrivateMessage {
type: 'private_message'
item: PrivateMessageView
}
interface CommentReply {
type: 'comment_reply'
item: CommentView
}
interface PersonMention {
type: 'person_mention'
item: CommentView
}
interface BaseInboxItem {
creator: Person
published: string
read: boolean
id: number
}
export type InboxItem = BaseInboxItem &
(PrivateMessage | CommentReply | PersonMention)
@@ -0,0 +1,162 @@
<script lang="ts">
import Markdown from '$lib/app/markdown/Markdown.svelte'
import Avatar from '$lib/ui/generic/Avatar.svelte'
import { t } from '$lib/app/i18n'
import { userLink } from '$lib/util.svelte'
import { settings } from '$lib/settings.svelte'
import type { PersonView, SiteView, Tagline } from '$lib/api/types'
import { Badge } from 'mono-svelte'
import {
BuildingOffice,
Icon,
Newspaper,
ServerStack,
} from 'svelte-hero-icons'
import type { ClassValue, HTMLAttributes } from 'svelte/elements'
import EndPlaceholder from '../../ui/EndPlaceholder.svelte'
import Expandable from '../../ui/Expandable.svelte'
import LabelStat from '../../ui/LabelStat.svelte'
import SidebarButton from '../../ui/sidebar/SidebarButton.svelte'
import ItemList from '../generic/ItemList.svelte'
import { optimizeImageURL } from '../post/helpers'
interface Props extends HTMLAttributes<HTMLDivElement> {
site: SiteView
taglines?: Tagline[]
admins?: PersonView[]
version?: string
class?: ClassValue
}
let {
site,
taglines = undefined,
admins = undefined,
version = undefined,
class: clazz = '',
}: Props = $props()
</script>
<aside
class={[
'w-full text-slate-600 dark:text-zinc-400 flex flex-col gap-4 text-sm',
clazz,
]}
>
{#if site.site.banner}
<div class="rounded-xl bg-slate-100 dark:bg-zinc-925">
<img
src={optimizeImageURL(site.site.banner, 512)}
alt="Site banner"
class="h-32 object-cover w-full"
style="border-radius: inherit;"
/>
</div>
{/if}
<div class="mx-3 space-y-3">
<Avatar width={32} url={site.site.icon} alt="" circle={false} />
<h2 class="font-medium text-lg -my-2">{site.site.name}</h2>
</div>
<div class="flex flex-col gap-1">
{#if taglines && taglines.length > 0}
<Markdown
class="px-3"
source={taglines[Math.floor(Math.random() * taglines.length)].content}
/>
{/if}
<EndPlaceholder size="xs" margin="sm">
{$t('nav.menu.instance')}
</EndPlaceholder>
<SidebarButton
href="/modlog"
label={$t('routes.modlog.title')}
icon={Newspaper}
/>
<SidebarButton
href="/legal"
label={$t('routes.legal.title')}
icon={BuildingOffice}
/>
<SidebarButton
href="/instances"
label={$t('routes.instances')}
icon={ServerStack}
/>
<EndPlaceholder size="xs" margin="sm">
{$t('cards.site.stats')}
</EndPlaceholder>
<div class="flex flex-row gap-4 flex-wrap px-3">
<LabelStat
label={$t('content.users')}
content={site.counts.users.toString()}
formatted
/>
<LabelStat
label={$t('content.posts')}
content={site.counts.posts.toString()}
formatted
/>
<LabelStat
label={$t('content.comments')}
content={site.counts.comments.toString()}
formatted
/>
<LabelStat
label={$t('cards.community.activeDay')}
content={site.counts.users_active_day.toString()}
formatted
/>
<LabelStat
label={$t('content.communities')}
content={site.counts.communities.toString()}
formatted
/>
</div>
<EndPlaceholder size="xs" margin="sm">
{$t('common.info')}
</EndPlaceholder>
<div class="space-y-3 px-1.5 text-sm">
<Expandable bind:open={settings.expand.about}>
{#snippet title()}
<span class="flex items-center gap-1 py-1 px-2 w-full">
{$t('cards.site.about')}
</span>
{/snippet}
<Markdown source={site.site.description} />
<div class="my-4"></div>
<Markdown source={site.site.sidebar} />
{#if version}
<div class="w-max">
<Badge label="Lemmy version">
<Icon src={ServerStack} micro size="14" />
{version}
</Badge>
</div>
{/if}
</Expandable>
{#if admins}
<Expandable bind:open={settings.expand.team}>
{#snippet title()}
<span class="flex items-center gap-1 py-1 px-2 w-full">
{$t('cards.site.admins')}
</span>
{/snippet}
<ItemList
items={admins.map((i) => ({
id: i.person.id,
name: i.person.display_name || i.person.name,
url: userLink(i.person),
avatar: i.person.avatar,
instance: new URL(i.person.actor_id).hostname,
}))}
/>
</Expandable>
{/if}
</div>
</div>
</aside>
@@ -0,0 +1,54 @@
<script lang="ts">
import type { Profile } from '$lib/app/auth.svelte.js'
import Avatar from '$lib/ui/generic/Avatar.svelte'
import { Icon, UserCircle } from 'svelte-hero-icons'
interface Props {
profile?: Profile | undefined
selected?: boolean
index?: number
size?: number
guest?: boolean
}
let {
profile = undefined,
selected = false,
index = 0,
size = 22,
guest = false,
}: Props = $props()
</script>
{#if profile}
<div
style="width: {size}px; height: {size}px;"
class={[profile.avatar && 'bg-slate-200 rounded-full dark:bg-zinc-700']}
>
{#if profile.avatar}
<Avatar
url={profile.avatar}
width={size}
alt=""
class={[
'shrink-0 rounded-full',
selected && 'scale-75',
'transition-transform',
]}
/>
{:else}
<Icon
src={UserCircle}
mini={selected}
size={size?.toString()}
title={profile.username}
class="text-blue-500 shrink-0"
style={guest
? `color: gray`
: profile.color
? `color: ${profile.color}`
: `filter: hue-rotate(${index * 50}deg)`}
/>
{/if}
</div>
{/if}
+149
View File
@@ -0,0 +1,149 @@
import { getClient } from '$lib/api/client.svelte'
import { isComment, isCommentView } from '$lib/lemmy/item.js'
import type {
CommentView,
Person,
PostView,
Comment,
Post,
} from '$lib/api/types'
export type SubmissionView = PostView | CommentView
export type Submission = Post | Comment
export interface ContentView {
type: 'post' | 'comment'
title?: string
body: string
creator?: Person
id: number
}
const isSubmissionView = (
item: SubmissionView | ContentView,
): item is SubmissionView => !('type' in item)
const isSubmission = (item: Submission | ContentView): item is Submission =>
!('type' in item)
export const contentView = (item: SubmissionView): ContentView => {
if (isCommentView(item))
return {
type: 'comment',
body: item.comment.content,
creator: item.creator,
id: item.comment.id,
}
else
return {
type: 'post',
body: item.post.body ?? item.post.name,
title: item.post.name,
creator: item.creator,
id: item.post.id,
}
}
export const contentItem = (item: Submission): ContentView => {
if (isComment(item))
return {
type: 'comment',
body: item.content,
id: item.id,
}
else
return {
type: 'post',
body: item.body ?? item.name,
title: item.name,
id: item.id,
}
}
export async function save(
item: ContentView | SubmissionView,
save: boolean,
): Promise<boolean> {
if (isSubmissionView(item)) item = contentView(item)
if (item.type == 'post') {
return (
await getClient().savePost({
post_id: item.id,
save: save,
})
).post_view.saved
} else if (item.type == 'comment') {
return (
await getClient().saveComment({
comment_id: item.id,
save: save,
})
).comment_view.saved
}
return save
}
export async function deleteItem(
item: ContentView | SubmissionView,
deleted: boolean,
): Promise<boolean> {
if (isSubmissionView(item)) item = contentView(item)
if (item.type == 'post') {
return (
await getClient().deletePost({
post_id: item.id,
deleted: deleted,
})
).post_view.post.deleted
} else if (item.type == 'comment') {
return (
await getClient().deleteComment({
comment_id: item.id,
deleted: deleted,
})
).comment_view.comment.deleted
}
return deleted
}
export async function vote(
item: ContentView | Submission,
vote: number,
): Promise<{ upvotes: number; downvotes: number; score: number }> {
if (isSubmission(item)) item = contentItem(item)
if (item.type == 'post') {
return (
await getClient().likePost({
post_id: item.id,
score: vote,
})
).post_view.counts
} else if (item.type == 'comment') {
return (
await getClient().likeComment({
comment_id: item.id,
score: vote,
})
).comment_view.counts
}
return { upvotes: 0, downvotes: 0, score: 0 }
}
export async function markAsRead(
item: ContentView | Submission,
read: boolean,
): Promise<boolean> {
if (isSubmission(item)) item = contentItem(item)
if (item.type == 'post') {
getClient().markPostAsRead({
post_ids: [item.id],
read: read,
})
return read
}
return false
}
+117
View File
@@ -0,0 +1,117 @@
import { profile } from '$lib/app/auth.svelte'
import type {
Comment,
CommentReportView,
CommentView,
Community,
CommunityView,
PersonView,
Post,
PostReportView,
PostView,
PrivateMessage,
PrivateMessageReportView,
PrivateMessageView,
} from '$lib/client/types'
import { writable } from 'svelte/store'
export type Result =
| PostView
| Post
| CommentView
| Comment
| PersonView
| CommunityView
| PrivateMessageView
| PostReportView
| CommentReportView
| PrivateMessageReportView
| PrivateMessage
export function getItemPublished(item: Result) {
// reports... why
if ('post_report' in item) return item.post_report.published
if ('comment_report' in item) return item.comment_report.published
if ('private_message_report' in item)
return item.private_message_report.published
// others
if ('private_message' in item) return item.private_message.published
if ('comment' in item) return item.comment.published
else if ('post' in item) return item.post.published
if ('person' in item) return item.person.published
if ('community' in item) return item.community.published
return ''
}
export const isPostView = (item: Result): item is PostView =>
'post' in item && !('comment' in item)
export const isPost = (item: Result): item is Post =>
'name' in item && !('content' in item)
export const isCommentView = (item: Result): item is CommentView =>
'comment' in item
export const isComment = (item: Result): item is Comment => 'content' in item
export const isCommunityView = (item: Result): item is CommunityView =>
'community' in item
export const isUser = (item: Result): item is PersonView => 'person' in item
export const isPostReport = (item: Result): item is PostReportView =>
'post_report' in item
export const isCommentReport = (item: Result): item is CommentReportView =>
'comment_report' in item
export const isPrivateMessageReport = (
item: Result,
): item is PrivateMessageReportView => 'private_message_report' in item
export interface ResumableItem {
url: string
id?: number
name: string
avatar?: string
type: 'community' | 'post'
subdivision?: {
avatar?: string
name: string
}
}
function resumableStore(limit: number = 10) {
const { subscribe, set, update } = writable<ResumableItem[]>([])
return {
subscribe,
set,
update,
add: (item: ResumableItem) => {
update((resumables) => {
if (resumables.find((i) => JSON.stringify(i) == JSON.stringify(item)))
return resumables
resumables.unshift(item)
if (resumables.length > limit) resumables.pop()
return resumables
})
},
}
}
export const resumables = resumableStore()
export function addFavorite(item: Community, add: boolean = true) {
const favs = profile.current.favorites ?? []
if (favs.map((fav) => fav.id).includes(item.id)) if (add) return
if (!add) {
favs.splice(favs.map((c) => c.id).indexOf(item.id), 1)
} else {
favs.unshift(item)
}
profile.current.favorites = favs
}
@@ -0,0 +1,49 @@
<script lang="ts">
import { preventDefault } from 'svelte/legacy'
import UserLink from '$comp/lemmy/user/UserLink.svelte'
import MarkdownEditor from '$lib/app/markdown/MarkdownEditor.svelte'
import { t } from '$lib/app/i18n'
import type { Person } from '$lib/api/types'
import { Button, Modal } from 'mono-svelte'
interface Props {
open?: boolean
user: Person
denying: boolean
denyReason?: string
}
let {
open = $bindable(false),
user,
denying = $bindable(),
denyReason = $bindable(''),
}: Props = $props()
let loading = false
function deny() {
denying = true
open = false
}
</script>
<Modal bind:open>
{#snippet customTitle()}
<h1 class="text-2xl font-bold">
{$t('routes.admin.applications.modalTitle')}
</h1>
{/snippet}
<form onsubmit={preventDefault(() => deny())} class="flex flex-col gap-4">
<UserLink avatar {user} />
<MarkdownEditor
bind:value={denyReason}
label={$t('routes.admin.applications.reason')}
rows={4}
/>
<Button color="primary" size="lg" submit {loading} disabled={loading}>
{$t('routes.admin.applications.deny')}
</Button>
</form>
</Modal>
+133
View File
@@ -0,0 +1,133 @@
<script lang="ts">
import Avatar from '$lib/ui/generic/Avatar.svelte'
import type { Community, Person } from '$lib/api/types'
import { client } from '$lib/api/client.svelte'
import { Label, toast, Button, Modal, Switch } from 'mono-svelte'
import { profile } from '$lib/app/auth.svelte.js'
import MarkdownEditor from '$lib/app/markdown/MarkdownEditor.svelte'
import { t } from '$lib/app/i18n'
import Duration from '$comp/form/Duration.svelte'
import { errorMessage } from '$lib/lemmy/error'
import CommunityLink from '../community/CommunityLink.svelte'
interface Props {
open?: boolean
user: Person | undefined
community: Community | undefined
banned: boolean
}
let {
open = $bindable(false),
user: item = $bindable(),
community,
banned,
}: Props = $props()
let reason = $state('')
let deleteData = $state(false)
let expires = $state(-1)
let loading = $state(false)
// hack due to svelte's reactive declarations
const resetReason = () => {
reason = ''
deleteData = false
expires = -1
}
$effect(() => {
if (item) resetReason()
})
async function submit() {
if (!item || !profile.current?.user || !profile.current?.jwt) return
loading = true
try {
let date: number | undefined
if (expires > 0) {
date = Math.floor(Date.now() / 1000) + expires
}
if (community) {
await client().banFromCommunity({
ban: !banned,
community_id: community.id,
person_id: item.id,
reason: reason || undefined,
remove_data: deleteData,
expires: date,
})
} else {
await client().banPerson({
ban: !banned,
person_id: item.id,
reason: reason || undefined,
remove_data: deleteData,
expires: date,
})
}
open = false
toast({
content: banned ? $t('toast.unbannedUser') : $t('toast.bannedUser'),
type: 'success',
})
item.banned = !banned
} catch (err) {
toast({
content: errorMessage(err),
type: 'error',
})
}
loading = false
}
</script>
<Modal
bind:open
title={banned ? $t('moderation.ban.unbanning') : $t('moderation.ban.banning')}
>
{#if item}
<form
class="flex flex-col gap-4"
onsubmit={(e) => {
e.preventDefault()
submit()
}}
>
<div class="flex items-center gap-1">
<Avatar url={item.avatar} alt={item.name} width={24} />
<span class="font-bold">{item.name}</span>
</div>
{#if community}
<CommunityLink {community} avatar />
{/if}
<MarkdownEditor
required
bind:value={reason}
label={$t('moderation.reason')}
/>
{#if !banned}
<Switch bind:checked={deleteData}>
{$t('moderation.ban.deleteData')}
{#snippet description()}
{$t('moderation.ban.warning')}
{/snippet}
</Switch>
<Label text={$t('moderation.ban.expires')}>
<Duration bind:value={expires}></Duration>
</Label>
{/if}
<Button submit color="primary" {loading} disabled={loading} size="lg">
{$t('form.submit')}
</Button>
</form>
{/if}
</Modal>
@@ -0,0 +1,111 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte.js'
import ShieldIcon from '$comp/lemmy/moderation/ShieldIcon.svelte'
import { t } from '$lib/app/i18n'
import { isCommentView } from '$lib/lemmy/item.js'
import type { CommentView } from '$lib/api/types'
import { Button, Menu, MenuButton, MenuDivider } from 'mono-svelte'
import {
ArrowsUpDown,
Fire,
Icon,
Megaphone,
Newspaper,
ShieldExclamation,
Trash,
} from 'svelte-hero-icons'
import { amMod, ban, feature, isAdmin, remove, viewVotes } from './moderation'
interface Props {
item: CommentView
}
let { item = $bindable(), ...rest }: Props = $props()
</script>
<Menu placement="bottom" class="top-0 h-[26px] w-[26px] ">
{#snippet target(attachment)}
<Button
{@attach attachment}
class="w-[26px] h-[26px] hover:text-green-500! dark:text-zinc-400 text-slate-600"
size="square-md"
color="tertiary"
{...rest}
>
<ShieldIcon filled width={14} />
</Button>
{/snippet}
{#if (profile.current?.user && amMod(profile.current.user, item.community)) || (profile.current?.user && isAdmin(profile.current.user))}
<MenuDivider showLabel>
{#if !item.community.local && !amMod(profile.current.user, item.community)}
{$t('moderation.labelInstanceOnly')}
{:else}
{$t('moderation.label')}
{/if}
</MenuDivider>
<MenuButton color="danger-subtle" onclick={() => remove(item)} icon={Trash}>
{#if isCommentView(item)}
{item.comment.removed
? $t('moderation.restore')
: $t('moderation.remove')}
{/if}
</MenuButton>
{#if profile.current?.user && profile.current.user?.local_user_view.person.id != item.creator.id}
<!--Comment made by someone else-->
<MenuButton
color="danger-subtle"
onclick={() =>
ban(item.creator_banned_from_community, item.creator, item.community)}
icon={ShieldExclamation}
>
{item.creator_banned_from_community
? $t('moderation.ban.unbanFromCommunity')
: $t('moderation.ban.banFromCommunity')}
</MenuButton>
{:else}
<!--Comment made by self-->
<MenuButton
color="success-subtle"
onclick={async () => {
if (!profile.current.jwt) return
item.comment = (
await feature(
!item.comment.distinguished,
item.comment,
profile.current.jwt,
)
).comment_view.comment
}}
icon={Megaphone}
>
{item.comment.distinguished
? $t('moderation.unfeature')
: $t('moderation.feature')}
</MenuButton>
{/if}
<MenuButton color="success-subtle" href="/modlog?comment={item.comment.id}">
<Icon src={Newspaper} size="16" micro />
{$t('moderation.modlog.comment')}
</MenuButton>
<MenuButton color="success-subtle" href="/modlog?user={item.creator.id}">
<Icon src={Newspaper} size="16" micro />
{$t('moderation.modlog.user')}
</MenuButton>
<MenuButton color="blue-subtle" onclick={() => viewVotes(item)}>
<Icon src={ArrowsUpDown} size="16" micro />
{$t('moderation.votes')}
</MenuButton>
{/if}
{#if profile.current?.user && isAdmin(profile.current.user)}
<MenuDivider showLabel>{$t('admin.label')}</MenuDivider>
<MenuButton
color="danger-subtle"
onclick={() => remove(item, true)}
icon={Fire}
>
{$t('admin.purge')}
</MenuButton>
{/if}
</Menu>
@@ -0,0 +1,38 @@
<script lang="ts">
import { modals } from '$comp/lemmy/moderation/moderation.js'
</script>
<!--These weird await hacks are for lazy loading, better network performance-->
{#if $modals.reporting.open}
{#await import('$comp/lemmy/moderation/ReportModal.svelte') then { default: ReportModal }}
<ReportModal
bind:open={$modals.reporting.open}
bind:item={$modals.reporting.item}
/>
{/await}
{/if}
{#if $modals.removing.open}
{#await import('$comp/lemmy/moderation/RemoveModal.svelte') then { default: RemoveModal }}
<RemoveModal
bind:open={$modals.removing.open}
item={$modals.removing.item}
purge={$modals.removing.purge}
/>
{/await}
{/if}
{#if $modals.banning.open}
{#await import('$comp/lemmy/moderation/BanModal.svelte') then { default: BanModal }}
<BanModal
bind:open={$modals.banning.open}
banned={$modals.banning.banned}
user={$modals.banning.user}
community={$modals.banning.community}
/>
{/await}
{/if}
{#if $modals.votes.open}
{#await import('$comp/lemmy/moderation/ViewVotesModal.svelte') then { default: VotesModal }}
<VotesModal bind:open={$modals.votes.open} item={$modals.votes.item} />
{/await}
{/if}
@@ -0,0 +1,178 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte.js'
import { t } from '$lib/app/i18n'
import { getClient } from '$lib/api/client.svelte'
import { errorMessage } from '$lib/lemmy/error'
import { isCommentView, isPostView } from '$lib/lemmy/item.js'
import type { CommentView, PostView } from '$lib/api/types'
import { Menu, MenuButton, MenuDivider, toast } from 'mono-svelte'
import type { Snippet } from 'svelte'
import {
ArrowsUpDown,
Fire,
Icon,
LockClosed,
LockOpen,
Megaphone,
Newspaper,
ShieldExclamation,
Trash,
} from 'svelte-hero-icons'
import { amMod, ban, isAdmin, remove, viewVotes } from './moderation'
import type { Attachment } from 'svelte/attachments'
interface Props {
item: PostView | CommentView
target: Snippet<[Attachment, boolean]>
}
let { item = $bindable(), target: passedTarget }: Props = $props()
let acting = $state(false)
async function lock(lock: boolean) {
if (!profile.current?.jwt || !isPostView(item)) return
acting = true
try {
await getClient().lockPost({
locked: lock,
post_id: item.post.id,
})
item.post.locked = lock
} catch (err) {
toast({
content: errorMessage(err),
type: 'error',
})
}
acting = false
}
async function pin(pinned: boolean, toInstance: boolean = false) {
if (!profile.current?.jwt || !isPostView(item)) return
acting = true
try {
await getClient().featurePost({
feature_type: toInstance ? 'Local' : 'Community',
featured: pinned,
post_id: item.post.id,
})
item.post.featured_community = pinned
} catch (err) {
toast({
content: errorMessage(err),
type: 'error',
})
}
acting = false
}
</script>
<Menu placement="bottom-end">
{#snippet target(attachment)}
{@render passedTarget(attachment, acting)}
{/snippet}
{#if (profile.current?.user && amMod(profile.current.user, item.community)) || (profile.current?.user && isAdmin(profile.current.user))}
<MenuDivider showLabel>
{#if !item.community.local && !amMod(profile.current.user, item.community)}
{$t('moderation.labelInstanceOnly')}
{:else}
{$t('moderation.label')}
{/if}
</MenuDivider>
<MenuButton
color="warning-subtle"
onclick={() => lock(!item.post.locked)}
loading={acting}
icon={item.post.locked ? LockOpen : LockClosed}
>
{item.post.locked ? $t('moderation.unlock') : $t('moderation.lock')}
</MenuButton>
<MenuButton
color="success-subtle"
onclick={() =>
pin(isPostView(item) ? !item.post.featured_community : false)}
loading={acting}
>
<Icon src={Megaphone} size="16" mini />
<div
class="flex flex-row gap-2 text-left items-center justify-between w-full"
>
<span>
{item.post.featured_community
? $t('moderation.unfeature')
: $t('moderation.feature')}
</span>
{#if isAdmin(profile.current.user)}
<span class="text-xs opacity-80">{$t('form.post.community')}</span>
{/if}
</div>
</MenuButton>
<MenuButton color="danger-subtle" onclick={() => remove(item)}>
<Icon src={Trash} size="16" mini />
{#if isCommentView(item)}
{item.comment.removed
? $t('moderation.restore')
: $t('moderation.remove')}
{:else}
{item.post.removed ? $t('moderation.restore') : $t('moderation.remove')}
{/if}
</MenuButton>
{#if profile.current?.user && profile.current.user.local_user_view.person.id != item.creator.id}
<MenuButton
color="danger-subtle"
onclick={() =>
ban(item.creator_banned_from_community, item.creator, item.community)}
>
<Icon src={ShieldExclamation} size="16" mini />
{item.creator_banned_from_community
? $t('moderation.ban.unbanFromCommunity')
: $t('moderation.ban.banFromCommunity')}
</MenuButton>
{/if}
<MenuButton color="success-subtle" href="/modlog?user={item.creator.id}">
<Icon src={Newspaper} size="16" micro />
{$t('moderation.modlog.user')}
</MenuButton>
<MenuButton color="success-subtle" href="/modlog?post={item.post.id}">
<Icon src={Newspaper} size="16" micro />
{$t('moderation.modlog.post')}
</MenuButton>
<MenuButton color="blue-subtle" onclick={() => viewVotes(item)}>
<Icon src={ArrowsUpDown} size="16" micro />
{$t('moderation.votes')}
</MenuButton>
{/if}
{#if profile.current?.user && isAdmin(profile.current.user)}
<MenuDivider showLabel>{$t('admin.label')}</MenuDivider>
<MenuButton
color="success-subtle"
onclick={() =>
pin(isPostView(item) ? !item.post.featured_local : false, true)}
>
<Icon src={Megaphone} size="16" mini />
<div
class="flex flex-row gap-2 text-left items-center justify-between w-full"
>
<span>
{item.post.featured_local
? $t('moderation.unfeature')
: $t('moderation.feature')}
</span>
<span class="text-xs opacity-80">{$t('admin.instance')}</span>
</div>
</MenuButton>
<MenuButton color="danger-subtle" onclick={() => remove(item, true)}>
<Icon src={Fire} size="16" mini />
{$t('admin.purge')}
</MenuButton>
{/if}
</Menu>
@@ -0,0 +1,270 @@
<script lang="ts">
import { preventDefault, run } from 'svelte/legacy'
import MultiSelect from '$comp/input/Switch.svelte'
import { removalTemplate } from '$comp/lemmy/moderation/moderation.js'
import MarkdownEditor from '$lib/app/markdown/MarkdownEditor.svelte'
import { profile } from '$lib/app/auth.svelte.js'
import { getClient } from '$lib/api/client.svelte'
import type { CommentView, PostView } from '$lib/api/types'
import { t } from '$lib/app/i18n'
import { errorMessage } from '$lib/lemmy/error'
import { isCommentView, isPostView } from '$lib/lemmy/item.js'
import { settings } from '$lib/settings.svelte.js'
import { fullCommunityName } from '$lib/util.svelte.js'
import { Button, Modal, Select, Switch, toast } from 'mono-svelte'
import Option from 'mono-svelte/forms/select/Option.svelte'
import { Fire, Trash } from 'svelte-hero-icons'
import Comment from '../comment/Comment.svelte'
import { Post } from '../post'
import { amMod, isAdmin } from './moderation'
interface Props {
open: boolean
item?: PostView | CommentView | undefined
purge?: boolean
}
let {
open = $bindable(),
item = $bindable(undefined),
purge = false,
}: Props = $props()
let reason = $state('')
let commentReason: boolean = $state(
settings.moderation.defaultRemoveAction != null,
)
let privateMessage: boolean = $state(
settings.moderation.defaultRemoveAction == 'message',
)
let loading = $state(false)
let preset = $state(settings.moderation.presets[0]?.content ?? '')
$effect(() => {
if (!commentReason) settings.moderation.defaultRemoveAction = null
else if (privateMessage) settings.moderation.defaultRemoveAction = 'message'
else settings.moderation.defaultRemoveAction = 'comment'
})
let removed = $derived(
item
? isCommentView(item)
? item.comment.removed
: item.post.removed
: false,
)
const getReplyReason = (reason: string, preset: string) => {
if (!item) return `no template`
return removalTemplate(preset, {
communityLink: `!${fullCommunityName(
item!.community.name,
item!.community.actor_id,
)}`,
postTitle: item.post.name,
reason: reason,
username: item.creator.name,
})
}
let replyReason = $state('')
$effect(() => {
replyReason = commentReason ? getReplyReason(reason, preset) : ''
})
async function remove() {
if (!item) return
if (!profile.current?.jwt) throw new Error('Unauthenticated')
loading = true
try {
if (purge) {
if (isCommentView(item)) {
await getClient(undefined, fetch).purgeComment({
comment_id: item.comment.id,
reason: reason,
})
} else {
await getClient(undefined, fetch).purgePost({
post_id: item.post.id,
reason: reason,
})
}
toast({
content: $t('moderation.removeSubmission.successPurge'),
type: 'success',
})
loading = false
open = false
return
}
if (commentReason) {
if (replyReason == '') {
toast({
content: $t('moderation.removeSubmission.failEmptyReply'),
})
return
}
if (privateMessage) {
await getClient()
.createPrivateMessage({
content: replyReason,
recipient_id: isCommentView(item)
? item.comment.creator_id
: item.post.creator_id,
})
.catch(() => {
toast({
content: $t('moderation.removeSubmission.failMessage'),
type: 'warning',
})
})
} else {
await getClient()
.createComment({
content: replyReason,
post_id: item.post.id,
parent_id: isCommentView(item) ? item.comment.id : undefined,
})
.catch(() => {
toast({
content: $t('moderation.removeSubmission.failReply'),
type: 'warning',
})
})
}
}
if (isCommentView(item)) {
await getClient().removeComment({
comment_id: item.comment.id,
removed: !removed,
reason: reason || undefined,
})
item.comment.removed = !removed
} else if (isPostView(item)) {
await getClient().removePost({
post_id: item.post.id,
removed: !removed,
reason: reason || undefined,
})
item.post.removed = !removed
}
open = false
} catch (err) {
toast({
content: errorMessage(err),
type: 'error',
})
}
loading = false
}
const resetText = () => {
reason = ''
}
run(() => {
if (item) {
resetText()
}
})
</script>
<Modal
bind:open
title={purge
? $t('moderation.removeSubmission.titlePurge')
: removed
? $t('moderation.removeSubmission.titleRestore')
: $t('moderation.removeSubmission.title')}
>
{#if item}
<form
onsubmit={preventDefault(remove)}
class="flex flex-col gap-4 list-none"
>
{#if isCommentView(item)}
<Comment
node={{
children: [],
comment_view: item,
depth: 1,
}}
postId={item.post.id}
actions={false}
/>
{:else if isPostView(item)}
<Post actions={false} post={item} />
{/if}
<MarkdownEditor
rows={3}
label="Reason"
placeholder="Optional"
bind:value={reason}
/>
{#if !removed && profile.current?.user && (amMod(profile.current.user, item.community) || (isAdmin(profile.current.user) && item.community.local))}
<Switch bind:checked={commentReason}>
{$t('moderation.removeSubmission.withReason')}
</Switch>
{#if commentReason}
<MultiSelect
options={[false, true]}
optionNames={[
$t('moderation.removeSubmission.comment'),
$t('moderation.removeSubmission.message'),
]}
bind:selected={privateMessage}
/>
<MarkdownEditor
bind:value={replyReason}
placeholder={replyReason}
rows={3}
>
{#snippet customLabel()}
<div class="flex justify-between items-end mb-1">
{$t('comment.reply')}
<Select bind:value={preset} placeholder="No preset">
{#each settings.moderation.presets as preset}
<Option value={preset.content}>
{preset.title}
</Option>
{/each}
</Select>
</div>
{/snippet}
</MarkdownEditor>
{/if}
{/if}
<Button
color={purge ? 'danger' : 'primary'}
size="lg"
{loading}
disabled={loading}
submit
icon={purge ? Fire : Trash}
>
{#if purge}
{$t('admin.purge')}
{:else}
{removed ? $t('moderation.restore') : $t('moderation.remove')}
{/if}
</Button>
</form>
{/if}
</Modal>
@@ -0,0 +1,115 @@
<script lang="ts">
import { preventDefault, run } from 'svelte/legacy'
import { profile } from '$lib/app/auth.svelte.js'
import MarkdownEditor from '$lib/app/markdown/MarkdownEditor.svelte'
import { t } from '$lib/app/i18n'
import { getClient } from '$lib/api/client.svelte'
import type {
CommentView,
PostView,
PrivateMessageView,
} from '$lib/api/types'
import { Button, Modal, toast } from 'mono-svelte'
import PrivateMessage from '../inbox/PrivateMessage.svelte'
import { errorMessage } from '$lib/lemmy/error'
import { Post } from '../post'
import Comment from '../comment/Comment.svelte'
interface Props {
open: boolean
item?: PostView | CommentView | PrivateMessageView | undefined
}
let { open = $bindable(), item = $bindable() }: Props = $props()
const isComment = (
item: PostView | CommentView | PrivateMessageView,
): item is CommentView => 'comment' in item
const isPost = (
item: PostView | CommentView | PrivateMessageView,
): item is PostView => !isComment(item) && 'post' in item
const isPrivateMessage = (
item: PostView | CommentView | PrivateMessageView,
): item is PrivateMessageView => !isComment(item) && 'private_message' in item
let loading = $state(false)
let reason = $state('')
async function report() {
if (!item || !profile.current?.jwt || reason == '') return
loading = true
try {
if (isComment(item)) {
await getClient().createCommentReport({
comment_id: item.comment.id,
reason: reason,
})
} else if (isPost(item)) {
await getClient().createPostReport({
post_id: item.post.id,
reason: reason,
})
} else if (isPrivateMessage(item)) {
await getClient().createPrivateMessageReport({
private_message_id: item.private_message.id,
reason: reason,
})
}
open = false
toast({
content: $t('moderation.reportModal.success'),
type: 'success',
})
} catch (err) {
toast({ content: errorMessage(err as string), type: 'error' })
}
loading = false
}
const resetText = () => (reason = '')
run(() => {
if (item) {
resetText()
}
})
</script>
<Modal bind:open title={$t('moderation.reportModal.title')}>
<form class="flex flex-col gap-4" onsubmit={preventDefault(report)}>
{#if item}
<div class="pointer-events-none list-none">
{#if isComment(item)}
<Comment
actions={false}
node={{
children: [],
comment_view: item,
depth: 1,
loading: false,
}}
postId={item.post.id}
/>
{:else if isPost(item)}
<Post actions={false} post={item} />
{:else}
<PrivateMessage message={item} />
{/if}
</div>
{/if}
<MarkdownEditor
required
rows={4}
label={$t('moderation.reason')}
bind:value={reason}
/>
<Button submit {loading} disabled={loading} color="primary" size="lg">
{$t('form.submit')}
</Button>
</form>
</Modal>
@@ -0,0 +1,42 @@
<script lang="ts">
interface Props {
width?: number
filled?: boolean
class?: string
}
let { width = 16, filled = false, class: clazz = '' }: Props = $props()
</script>
{#if filled}
<svg
{width}
height={width}
viewBox="0 0 20 22"
fill="none"
xmlns="http://www.w3.org/2000/svg"
class="inline {clazz}"
>
<path
d="M10.516 1.17C10.3767 1.03791 10.192 0.964283 10 0.964283C9.80801 0.964283 9.62333 1.03791 9.484 1.17C7.36127 3.18588 4.53412 4.29133 1.607 4.25C1.44753 4.24793 1.29156 4.29674 1.16172 4.38935C1.03189 4.48196 0.934957 4.61355 0.885 4.765C0.462973 6.05116 0.248618 7.39637 0.25 8.75C0.25 14.692 4.314 19.683 9.813 21.098C9.93566 21.1296 10.0643 21.1296 10.187 21.098C15.686 19.683 19.75 14.692 19.75 8.75C19.75 7.36 19.527 6.02 19.115 4.765C19.0652 4.61336 18.9684 4.48156 18.8385 4.38875C18.7087 4.29595 18.5526 4.247 18.393 4.249L18.25 4.25C15.254 4.25 12.533 3.08 10.516 1.17Z"
fill="currentColor"
/>
</svg>
{:else}
<svg
{width}
height={width}
viewBox="0 0 20 22"
fill="none"
xmlns="http://www.w3.org/2000/svg"
class="inline {clazz}"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M10.516 1.17C10.3767 1.03791 10.192 0.964283 10 0.964283C9.80801 0.964283 9.62333 1.03791 9.484 1.17C7.36127 3.18588 4.53412 4.29133 1.607 4.25C1.44753 4.24793 1.29156 4.29674 1.16172 4.38935C1.03189 4.48196 0.934957 4.61355 0.885 4.765C0.462973 6.05116 0.248618 7.39637 0.25 8.75C0.25 14.692 4.314 19.683 9.813 21.098C9.93566 21.1296 10.0643 21.1296 10.187 21.098C15.686 19.683 19.75 14.692 19.75 8.75C19.75 7.36 19.527 6.02 19.115 4.765C19.0652 4.61336 18.9684 4.48156 18.8385 4.38875C18.7087 4.29595 18.5526 4.247 18.393 4.249L18.25 4.25C15.254 4.25 12.533 3.08 10.516 1.17Z"
stroke="currentColor"
stroke-width="1.5"
/>
</svg>
{/if}
@@ -0,0 +1,130 @@
<script lang="ts">
import { t } from '$lib/app/i18n'
import { client } from '$lib/api/client.svelte'
import { isCommentView, isPostView } from '$lib/lemmy/item'
import type { CommentView, PostView, VoteView } from '$lib/api/types'
import { Button, Modal, Spinner } from 'mono-svelte'
import {
ArrowDownCircle,
ArrowUpCircle,
ChevronLeft,
ChevronRight,
Icon,
Newspaper,
} from 'svelte-hero-icons'
import UserLink from '../user/UserLink.svelte'
interface Props {
open: boolean
item?: PostView | CommentView | undefined
}
let { open = $bindable(), item = $bindable() }: Props = $props()
let page = $state(1)
async function loadVotes(page: number): Promise<VoteView[]> {
if (!item) return []
if (isPostView(item))
return await client()
.listPostLikes({ post_id: item.post.id, limit: 50, page: page })
.then((i) => i.post_likes)
if (isCommentView(item))
return await client()
.listCommentLikes({
comment_id: item.comment.id,
limit: 50,
page: page,
})
.then((i) => i.comment_likes)
return []
}
let votes: Promise<VoteView[]> = $derived(loadVotes(page))
</script>
<Modal bind:open title={$t('moderation.votes')}>
<div class="flex flex-col gap-1">
{#await votes}
<div class="self-center justify-self-center h-48 grid place-items-center">
<Spinner width={24} />
</div>
{:then votes}
<table class="w-full border-collapse overflow-y-auto table-fixed">
<thead>
<tr
class="border divide-x divide-slate-200 dark:divide-zinc-800 border-slate-200 dark:border-zinc-800 *:px-4 *:py-2"
>
<th style="width: 6%;"></th>
<th style="width: 60%;" class="text-left">
{$t('routes.admin.applications.user')}
</th>
<th style="width: 5%;"></th>
</tr>
</thead>
<tbody class="divide-y divide-slate-200 dark:divide-zinc-800">
{#each votes as vote}
<tr>
<td class="py-1 px-1 w-full">
<Icon
src={vote.score == 1 ? ArrowUpCircle : ArrowDownCircle}
mini
size="20"
class={vote.score == 1 ? 'text-blue-400' : 'text-red-400'}
aria-label={vote.score == 1
? $t('routes.profile.upvoted')
: $t('routes.profile.downvoted')}
/>
</td>
<td class="text-sm w-full overflow-hidden">
<UserLink
user={{
...vote.creator,
banned: vote.creator_banned_from_community,
}}
/>
</td>
<td class="text-sm w-full text-right">
<a
href="/modlog?user={vote.creator.id}"
data-sveltekit-preload-data="tap"
class="text-green-400 hover:underline flex flex-row items-center gap-1 font-medium text-xs"
aria-label={$t('moderation.modlog.user')}
>
<Icon src={Newspaper} size="18" micro />
</a>
</td>
</tr>
{/each}
</tbody>
</table>
{#if !(votes.length < 50 && page == 1)}
<div class="flex flex-row justify-center items-center gap-2">
<Button
onclick={() => page--}
color="ghost"
aria-label={$t('common.back')}
rounding="pill"
size="square-md"
disabled={page == 1}
>
<Icon src={ChevronLeft} size="20" mini />
</Button>
{page}
<Button
onclick={() => page++}
color="ghost"
aria-label={$t('common.next')}
rounding="pill"
size="square-md"
disabled={votes.length < 50}
>
<Icon src={ChevronRight} size="20" mini />
</Button>
</div>
{/if}
{/await}
</div>
</Modal>
+133
View File
@@ -0,0 +1,133 @@
import { client } from '$lib/api/client.svelte'
import type {
Comment,
CommentView,
Community,
MyUserInfo,
Person,
PostView,
PrivateMessageView,
} from '$lib/api/types'
import type { SubmissionView } from '$lib/lemmy/contentview.js'
import { writable } from 'svelte/store'
interface Modals {
reporting: {
open: boolean
item: PostView | CommentView | PrivateMessageView | undefined
}
removing: {
open: boolean
item: SubmissionView | undefined
purge: boolean
}
banning: {
open: boolean
banned: boolean
user: Person | undefined
community: Community | undefined
}
votes: {
open: boolean
item: PostView | CommentView | undefined
}
}
export const modals = writable<Modals>({
reporting: {
open: false,
item: undefined,
},
removing: {
open: false,
item: undefined,
purge: false,
},
banning: {
open: false,
banned: false,
user: undefined,
community: undefined,
},
votes: {
open: false,
item: undefined,
},
})
export function report(item: PostView | CommentView | PrivateMessageView) {
modals.update((m) => ({
...m,
reporting: {
open: true,
item: item,
},
}))
}
export function remove(item: SubmissionView, purge: boolean = false) {
modals.update((m) => ({
...m,
removing: {
open: true,
item: item,
purge: purge,
},
}))
}
export function ban(banned: boolean, item: Person, community?: Community) {
modals.update((m) => ({
...m,
banning: {
open: true,
user: item,
banned: banned,
community,
},
}))
}
export async function feature(featured: boolean, item: Comment, jwt: string) {
return await client({ auth: jwt }).distinguishComment({
comment_id: item.id,
distinguished: featured,
})
}
export async function viewVotes(item: PostView | CommentView) {
modals.update((m) => ({
...m,
votes: {
open: true,
item: item,
},
}))
}
export const amMod = (me: MyUserInfo, community: Community) =>
me.moderates.map((c) => c.community.id).includes(community.id) ||
(community.local && isAdmin(me))
export const amModOfAny = (me?: MyUserInfo) =>
me && (me.moderates.length > 0 || isAdmin(me))
export const isAdmin = (me: MyUserInfo) => me.local_user_view.person.admin
export const removalTemplate = (
input: string,
content: {
postTitle?: string
communityLink?: string
username?: string
reason?: string
},
) => {
if (content.postTitle) input = input.replaceAll('{{post}}', content.postTitle)
if (content.communityLink)
input = input.replaceAll('{{community}}', content.communityLink)
if (content.username)
input = input.replaceAll('{{username}}', content.username)
if (content.reason) input = input.replaceAll('{{reason}}', content.reason)
return input
}
+98
View File
@@ -0,0 +1,98 @@
import { publishedToDate } from '$comp/util/date.js'
import type {
CommentReportView,
CommentView,
Person,
PostReportView,
PostView,
PrivateMessage,
PrivateMessageReportView,
} from '$lib/client/types'
interface CommentReport {
type: 'comment'
item: CommentView
}
interface PostReport {
type: 'post'
item: PostView
}
interface PrivateMessageReport {
type: 'message'
item: PrivateMessage
reportee: Person
}
interface BaseReport {
creator: Person
reason: string
reportee?: Person
timestamp: Date
resolved: boolean
id: number
resolver?: Person
}
export const generalizeCommentReport = (
report: CommentReportView,
): ReportView => ({
creator: report.creator,
item: {
...report,
subscribed: 'NotSubscribed',
saved: false,
creator_blocked: false,
creator: report.comment_creator,
banned_from_community: false,
},
reason: report.comment_report.reason,
type: 'comment',
timestamp: publishedToDate(report.comment_report.published),
resolved: report.comment_report.resolved,
id: report.comment_report.id,
resolver: report.resolver,
})
export const generalizePostReport = (report: PostReportView): ReportView => ({
creator: report.creator,
item: {
...report,
unread_comments: 0,
saved: false,
creator_blocked: false,
read: false,
subscribed: 'NotSubscribed',
creator: report.post_creator,
banned_from_community: false,
},
reason: report.post_report.reason,
type: 'post',
timestamp: publishedToDate(report.post_report.published),
resolved: report.post_report.resolved,
id: report.post_report.id,
resolver: report.resolver,
})
export const generalizePrivateMessageReport = (
report: PrivateMessageReportView,
): ReportView => ({
creator: report.creator,
item: report.private_message,
reason: report.private_message_report.reason,
type: 'message',
reportee: report.private_message_creator,
timestamp: publishedToDate(report.private_message_report.published),
resolved: report.private_message_report.resolved,
id: report.private_message_report.id,
resolver: report.resolver,
})
export type Report =
| CommentReportView
| PostReportView
| PrivateMessageReportView
export type ReportView = BaseReport &
(CommentReport | PostReport | PrivateMessageReport)
+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>
+91
View File
@@ -0,0 +1,91 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte'
import { client } from '$lib/api/client.svelte'
import type { LocalImage, Person } from '$lib/api/types'
import UserLink from '$comp/lemmy/user/UserLink.svelte'
import { publishedToDate } from '$comp/util/date'
import RelativeDate from '$comp/util/RelativeDate.svelte'
import { t } from '$lib/app/i18n'
import { instance } from '$lib/app/instance.svelte'
import { instanceToURL } from '$lib/util.svelte'
import { action, Button, modal, toast } from 'mono-svelte'
import { ArrowDownTray, Trash } from 'svelte-hero-icons'
let loading = $state(false)
async function deleteImage(image: LocalImage) {
if (!profile.current?.jwt) return
try {
loading = true
const res = await client().deleteImage({
token: image.pictrs_delete_token,
filename: image.pictrs_alias,
})
ondelete?.(res)
} catch (e) {
toast({ content: e as string, type: 'error' })
}
loading = false
}
interface Props {
image: LocalImage
user?: Person
ondelete?: (res: boolean) => void
}
let { image, user, ondelete }: Props = $props()
</script>
<div class="flex flex-col gap-1">
<img
src="{instanceToURL(instance.data)}/pictrs/image/{image.pictrs_alias}"
width="500"
height="500"
class="aspect-square w-full h-full object-cover rounded-xl"
alt="pictrs"
/>
{#if user}
<UserLink {user} />
{/if}
<div class="flex items-center gap-2">
<RelativeDate
class="text-sm text-slate-700 dark:text-zinc-300"
date={publishedToDate(image.published)}
/>
<Button
title={$t('routes.profile.media.download')}
href="{instanceToURL(instance.data)}/pictrs/image/{image.pictrs_alias}"
size="square-md"
class="ml-auto"
icon={ArrowDownTray}
></Button>
<Button
title={$t('post.actions.more.delete')}
onclick={() => {
modal({
title: $t('routes.theme.preset.delete.confirm'),
body: '',
actions: [
action({
close: true,
content: $t('common.cancel'),
}),
action({
type: 'danger',
action: () => deleteImage(image),
close: true,
content: $t('post.actions.more.delete'),
}),
],
})
}}
size="square-md"
{loading}
disabled={loading}
icon={Trash}
></Button>
</div>
</div>
+64
View File
@@ -0,0 +1,64 @@
<script lang="ts">
import { goto } from '$app/navigation'
import { page } from '$app/state'
import { profile, type ProfileInfo } from '$lib/app/auth.svelte'
import SidebarButton from '$comp/ui/sidebar/SidebarButton.svelte'
import { LINKED_INSTANCE_URL } from '$lib/app/instance.svelte'
import ProfileAvatar from '$lib/feature/legacy/ProfileAvatar.svelte'
import { Icon, QuestionMarkCircle } from 'svelte-hero-icons'
let switching: boolean = $state(false)
interface Props {
prof: ProfileInfo
index: number
guest?: boolean
}
let { prof, index, guest = false }: Props = $props()
</script>
<SidebarButton
alignment="left"
loading={switching}
rounding="lg"
loaderWidth={22}
selected={profile.current?.id == prof.id}
onclick={async () => {
switching = true
if (profile.current?.id != prof.id) {
profile.meta.profile = prof.id
}
await goto(page.url, {
invalidateAll: true,
})
switching = false
}}
class="w-full font-normal"
>
{#snippet customIcon()}
<ProfileAvatar
profile={prof}
{index}
{guest}
selected={profile.current?.id == prof.id}
/>
{/snippet}
<span
class="inline-flex flex-col gap-0 {profile.current?.id == prof.id
? 'font-semibold'
: ''}"
>
{prof.username ?? prof.user?.local_user_view.person.name}
{#if !guest && !LINKED_INSTANCE_URL}
<span class="text-slate-500 dark:text-zinc-400 font-normal text-xs">
{prof.instance}
</span>
{/if}
</span>
{#if !prof.jwt}
<Icon src={QuestionMarkCircle} size="14" micro class="ml-auto opacity-50" />
{/if}
</SidebarButton>
@@ -0,0 +1,107 @@
<script lang="ts">
import { Badge, Button, Menu, MenuButton } from 'mono-svelte'
import {
CheckCircle,
ChevronUpDown,
Icon,
QuestionMarkCircle,
UserGroup,
} from 'svelte-hero-icons'
import Avatar from '../Avatar.svelte'
import { profile, type ProfileInfo } from '$lib/app/auth.svelte'
import { goto } from '$app/navigation'
import { page } from '$app/state'
import { t } from '$lib/app/i18n'
import { DEFAULT_CLIENT_TYPE } from '$lib/api/base'
import { LINKED_INSTANCE_URL } from '$lib/app/instance.svelte'
let { profiles }: { profiles: ProfileInfo[] } = $props()
function switchTo(id: number) {
profile.meta.profile = id
goto(page.url, {
invalidateAll: true,
})
}
</script>
<Menu placement="bottom">
{#snippet target(attachment)}
<Button
{@attach attachment}
color="tertiary"
alignment="left"
size="md"
rounding="xl"
class="flex flex-row gap-2! items-center"
aria-label={$t('aria.sidebar.accounts')}
>
{#snippet prefix()}
<Avatar
url={profile.current.avatar}
alt={profile.current.username}
width={24}
/>
{/snippet}
<div class="flex-1">
<div class="font-medium">{profile.current.username}</div>
{#if !LINKED_INSTANCE_URL}
<div class="text-xs text-slate-500 dark:text-zinc-500">
<span class="capitalize">
{profile.current.client?.name ?? DEFAULT_CLIENT_TYPE.name}
</span>
• {profile.current.instance}
</div>
{/if}
</div>
{#snippet suffix()}
<Icon
src={ChevronUpDown}
size="16"
micro
class="block justify-self-end"
/>
{/snippet}
</Button>
{/snippet}
{#each profiles as p}
{@const selected = profile.meta.profile == p.id}
<MenuButton
onclick={() => switchTo(p.id)}
class={[selected && 'bg-slate-100! dark:bg-zinc-800!', 'gap-2!']}
>
{#snippet prefix()}
<Avatar url={p.avatar} alt={p.username} width={24} />
{/snippet}
<div>
<div class="font-medium text-sm">{p.username}</div>
{#if !LINKED_INSTANCE_URL}
<div class="text-xs text-slate-500 dark:text-zinc-500">
<span class="capitalize">
{p.client?.name ?? DEFAULT_CLIENT_TYPE.name}
</span>
• {p.instance}
</div>
{/if}
</div>
<div class="flex-1"></div>
{#if !p.jwt}
<Badge color="gray-subtle" class="p-1!">
<Icon src={QuestionMarkCircle} size="16" micro />
</Badge>
{/if}
{#if selected}
<Icon
src={CheckCircle}
class="text-primary-900 dark:text-primary-100"
size="16"
micro
/>
{/if}
</MenuButton>
{/each}
<MenuButton href="/accounts" icon={UserGroup}>
{$t('account.accounts')}
</MenuButton>
</Menu>
@@ -0,0 +1,82 @@
<script lang="ts">
import { profile } from '$lib/app/auth.svelte'
import Avatar from '$lib/ui/generic/Avatar.svelte'
import { getClient } from '$lib/api/client.svelte'
import type { ListingType, Person } from '$lib/api/types'
import { MenuButton, Search } from 'mono-svelte'
import { createEventDispatcher } from 'svelte'
import { Icon, XCircle } from 'svelte-hero-icons'
import { fly } from 'svelte/transition'
interface Props {
q?: string
instance?: string | undefined
listing_type?: ListingType
showWhenEmpty?: boolean
hideOwnUser?: boolean
placeholder?: string
onselect?: (e: Person) => void
}
let {
q = $bindable(''),
instance = undefined,
listing_type = 'Subscribed',
showWhenEmpty = false,
hideOwnUser = false,
...rest
}: Props = $props()
const dispatcher = createEventDispatcher<{ select: Person | undefined }>()
</script>
<Search
search={async (q) => {
const users = (
await getClient(instance).search({
q: q || ' ',
type_: 'Users',
limit: 20,
listing_type: listing_type,
sort: 'TopAll',
})
).users.map((c) => c.person)
if (hideOwnUser) {
const myself = profile.current.user?.local_user_view.person.id
return users.filter((c) => c.id != myself)
}
return users
}}
extractName={(c) => `${c.name}@${new URL(c.actor_id).hostname}`}
bind:query={q}
{...rest}
>
{#snippet noresults()}
<div class="w-full h-full">
{#if showWhenEmpty}
<MenuButton onclick={() => dispatcher('select', undefined)}>
<Icon src={XCircle} size="16" mini />
<div class="flex flex-col text-left">
<span>None</span>
</div>
</MenuButton>
{:else}
<span class="mx-auto my-auto">No results.</span>
{/if}
</div>
{/snippet}
{#snippet children({ item, select })}
<div in:fly|global={{ y: -4, opacity: 0 }}>
<MenuButton onclick={() => select(item)}>
<Avatar url={item.avatar} alt={item.name} width={24} />
<div class="flex flex-col text-left">
<span>{item.name}</span>
<span class="text-xs opacity-80">
{new URL(item.actor_id).hostname}
</span>
</div>
</MenuButton>
</div>
{/snippet}
</Search>
+69
View File
@@ -0,0 +1,69 @@
<script lang="ts">
import Avatar from '$lib/ui/generic/Avatar.svelte'
import LabelStat from '$lib/ui/info/LabelStat.svelte'
import { userLink } from '$lib/util.svelte'
import type { PersonView } from '$lib/api/types'
interface Props {
user: PersonView
view?: 'cozy' | 'compact'
showCounts?: boolean
class?: string
icon?: import('svelte').Snippet
}
let {
user,
view = 'compact',
showCounts = true,
class: clazz = 'flex flex-col gap-4 text-sm max-w-full relative',
icon,
}: Props = $props()
</script>
<div class={clazz}>
<div
class="flex
{view == 'cozy'
? 'flex-col gap-2'
: 'flex-row'} items-center max-w-full w-full"
>
<a href={userLink(user.person)} class="flex-1">
<div
class="flex {view == 'cozy'
? 'flex-col gap-2'
: 'flex-row'} gap-2 items-center"
>
{#if icon}{@render icon()}{:else}
<Avatar url={user.person.avatar} width={32} alt={user.person.name} />
{/if}
<div class="flex flex-col">
<div class="font-medium text-base">
{user.person.display_name ?? user.person.name}
</div>
<div class="text-sm text-slate-600 dark:text-zinc-400">
{new URL(user.person.actor_id).hostname}
</div>
</div>
</div>
</a>
</div>
{#if showCounts}
<div class="flex flex-row gap-3 items-center justify-center">
{#if user.counts.post_count}
<LabelStat
content={user.counts.post_count.toString()}
formatted
label="Posts"
/>
{/if}
{#if user.counts.comment_count}
<LabelStat
content={user.counts.comment_count.toString()}
formatted
label="Comments"
/>
{/if}
</div>
{/if}
</div>
+168
View File
@@ -0,0 +1,168 @@
<script lang="ts" module>
import { env } from '$env/dynamic/public'
import type { IconSource } from 'svelte-hero-icons'
function parseBadge() {
try {
if (env.PUBLIC_BADGES) {
return JSON.parse(env.PUBLIC_BADGES)
} else {
return {}
}
} catch {
return {}
}
}
const badges = parseBadge()
const getEnvBadge = (
actor_id: string,
):
| {
classes: string
icon: 'photon' | IconSource
iconClass?: string
}
| false => {
if (badges.photon && badges.photon?.includes?.(actor_id)) {
return {
classes:
'bg-linear-to-r bg-clip-text text-transparent from-pink-500 to-fuchsia-500 dark:from-pink-400 dark:to-purple-400',
icon: 'photon',
}
}
if (badges.translator && badges.translator?.includes?.(actor_id)) {
return {
classes:
'bg-linear-to-r bg-clip-text text-transparent from-sky-500 to-blue-700 dark:from-blue-300 dark:to-indigo-500',
icon: Language,
iconClass: 'text-blue-500 dark:text-blue-400',
}
}
return false
}
</script>
<script lang="ts">
import Avatar from '$lib/ui/generic/Avatar.svelte'
import Logo from '$lib/ui/generic/Logo.svelte'
import { settings } from '$lib/settings.svelte.js'
import type { Person } from '$lib/api/types'
import { Icon, Language, NoSymbol } from 'svelte-hero-icons'
import { Badge } from 'mono-svelte'
interface Props {
user: Person
avatar?: boolean
avatarSize?: number
badges?: boolean
inComment?: boolean
showInstance?: boolean
displayName?: boolean
instanceClass?: string
class?: string
children?: import('svelte').Snippet
extraBadges?: import('svelte').Snippet
}
let {
user,
avatar = false,
avatarSize = 24,
badges = true,
inComment = false,
showInstance = settings.showInstances.user ||
(settings.showInstances.comments && inComment),
displayName = settings.displayNames,
instanceClass = '',
class: clazz = '',
children,
extraBadges,
}: Props = $props()
let envBadge = $derived(getEnvBadge(user.actor_id))
</script>
<a
class="items-center inline-flex flex-row gap-1 hover:underline max-w-full min-w-0 {clazz}"
href="/u/{user.name}@{new URL(user.actor_id).hostname}"
data-sveltekit-preload-data="tap"
>
{@render children?.()}
{#if avatar}
<Avatar
url={user.avatar}
alt={user.name}
width={avatarSize}
class="shrink-0"
/>
{/if}
<span
class="flex gap-0 items-center shrink max-w-full min-w-0"
class:ml-0.5={avatar}
>
<span
class:font-medium={showInstance}
class="username-text {envBadge && envBadge.classes}"
>
{displayName ? user.display_name || user.name : user.name}
</span>
{#if showInstance}
<span
class="text-slate-500 dark:text-zinc-500 font-normal instance-text shrink {instanceClass ??
''}"
>
@{new URL(user.actor_id).hostname}
</span>
{/if}
</span>
{#if badges}
{#if user.banned}
<div class="text-red-500" title="Banned">
<Icon src={NoSymbol} mini size="12" />
</div>
{/if}
{#if user.bot_account}
<div class="text-blue-500 font-bold" title="Bot">BOT</div>
{/if}
{#if envBadge}
{#if envBadge.icon == 'photon'}
<Logo width={16} />
{:else}
<Icon
src={envBadge.icon}
micro
size="16"
class={envBadge.iconClass ?? envBadge.classes}
/>
{/if}
{/if}
{#if user.flair}
<Badge color="blue-subtle" class="px-1.5! py-0.5! whitespace-nowrap">
{user.flair}
</Badge>
{/if}
{@render extraBadges?.()}
{/if}
</a>
<style>
.instance-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-width: 0;
max-width: 100%;
flex: 1;
}
.username-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
+41
View File
@@ -0,0 +1,41 @@
import { profile, type ProfileInfo } from '$lib/app/auth.svelte'
import { client } from '$lib/api/client.svelte'
import type { Community, MyUserInfo } from '$lib/api/types'
// TODO obliterate this file
export async function blockUser(block: boolean, id: number) {
const auth = profile.current?.jwt
if (!auth) throw new Error('Unauthorized')
await client().blockPerson({
block: block,
person_id: id,
})
}
export function isBlocked(me: MyUserInfo, user: number) {
return me.person_blocks.map((b) => b.target.id).includes(user)
}
export function addSubscription(
community: Community,
subscribe: boolean = true,
) {
const index = profile.current.user?.follows
.map((f) => f.community.id)
.indexOf(community.id)
if (subscribe && index == -1) {
profile.current.user?.follows.push({
follower: profile.current.user.follows[0]?.follower,
community: community,
})
} else {
profile.current.user?.follows.splice(index ?? 0, 1)
}
}
export function hasFavorite(profile: ProfileInfo, id: number): boolean {
return profile.favorites?.map((i) => i.id).includes(id) ?? false
}