feat: use state based auth instead of store based (#488)

* misc: switch to state for auth

* fix: class based auth not working
This commit is contained in:
Xylight authored and GitHub committed 2025-02-08 13:49:09 -08:00
1 parent 8c6ff77fac
commit 5651ad475d
83 files changed
+395 -469

No files matched your search

+90 -133
View File
@@ -27,7 +27,7 @@ import { t } from './translations'
const getDefaultProfile = (): Profile => ({
id: -1,
instance: get(profileData)?.defaultInstance ?? get(instance),
instance: profileData.defaultInstance ?? get(instance),
})
function getFromStorage<T>(key: string): T | undefined {
@@ -83,7 +83,7 @@ const getCookie = (key: string): string | undefined => {
?.split('=')?.[1]
}
export let profileData = writable<ProfileData>(
export let profileData = $state<ProfileData>(
getFromStorage<ProfileData>('profileData') ?? {
profiles: [
{
@@ -97,88 +97,55 @@ export let profileData = writable<ProfileData>(
},
)
let fetchUser = {
loading: false,
prevProfile: -1,
}
class CurrentProfile {
#data = $derived(
profileData.profiles.find((i) => i.id == profileData.profile) ??
getDefaultProfile(),
)
function profileStore(
data: Writable<ProfileData>,
fn: (
values: ProfileData,
set: (value: Profile) => void,
update: (fn: Updater<Profile>) => void,
) => any,
) {
const derive: Readable<Profile> = derived(data, fn)
const { subscribe } = derive
return {
subscribe,
set: (value: Profile) => {
data.update((data) => {
let index = data.profiles.findIndex((t) => t.id == value.id)
data.profiles[index] = value
return data
})
},
get data() {
return this.#data
}
set data(value) {
if (!value) return
const index = profileData.profiles.findIndex((i) => i.id == value?.id)
profileData.profiles[index] = value
}
}
export let profile: Readable<Profile> & { set: (v: Profile) => void } =
profileStore(profileData, (pd, set, update) => {
const profile =
pd.profiles.find((p) => p.id == pd.profile) ?? getDefaultProfile()
export let profile = new CurrentProfile()
instance.set(profile.instance)
set(profile)
async function fetchUserData(profile: CurrentProfile) {
instance.set(profile.data.instance)
if (profile.data.jwt) {
site.set(undefined)
notifications.set({ applications: 0, inbox: 0, reports: 0 })
if (profile?.jwt) {
if (profile.id != fetchUser.prevProfile && !fetchUser.loading) {
site.set(undefined)
const res = await userFromJwt(profile.data.jwt, profile.data.instance)
if (!res?.user)
toast({
content:
"Your account's instance did not return your user data. Your login may have expired.",
type: 'error',
})
fetchUser.loading = true
notifications.set({ applications: 0, inbox: 0, reports: 0 })
userFromJwt(profile.jwt, profile.instance)
.then((res) => {
if (!res?.user)
toast({
content:
"Your account's instance did not return your user data. Your login may have expired.",
type: 'error',
})
site.set(res?.site)
profile.user = res?.user
if (profile.user) {
profile.avatar = res?.user?.local_user_view.person.avatar
profile.username = res?.user?.local_user_view.person.name
}
fetchUser.loading = false
fetchUser.prevProfile = profile.id
checkInbox()
update(() => profile)
})
.catch((e) => {
fetchUser.loading = false
toast({ content: e, type: 'error' })
})
}
} else {
if (browser && !fetchUser.loading) {
site.set(undefined)
client({ instanceURL: profile.instance })
.getSite()
.then((res) => site.set(res))
fetchUser.loading = false
}
site.set(res?.site)
profile.data.user = res?.user
if (profile.data.user) {
profile.data.avatar = res?.user?.local_user_view.person.avatar
profile.data.username = res?.user?.local_user_view.person.name
}
})
} else {
if (browser) {
site.set(undefined)
client({ instanceURL: profile.data.instance })
.getSite()
.then((res) => site.set(res))
}
}
return profile
}
export let notifications = writable<Notifications>({
applications: 0,
@@ -186,35 +153,40 @@ export let notifications = writable<Notifications>({
reports: 0,
})
profileData.subscribe(async (pd) => {
const serialized: ProfileData = {
...pd,
profiles: pd.profiles.map((p) => serializeUser(p)),
}
$effect.root(() => {
$effect(() => {
const serialized = {
...profileData,
profiles: profileData.profiles.map((p) => serializeUser(p)),
}
setFromStorage('profileData', serialized)
setFromStorage('profileData', serialized)
if (serialized.profile == -1) {
instance?.set(get(profileData).defaultInstance ?? DEFAULT_INSTANCE_URL)
}
if (serialized.profiles.length == 0) {
profileData.update((pd) => ({
...pd,
profiles: [
if (serialized.profile == -1) {
instance?.set(profileData.defaultInstance ?? DEFAULT_INSTANCE_URL)
}
if (serialized.profiles.length == 0) {
profileData.profiles = [
{
id: 1,
instance: DEFAULT_INSTANCE_URL,
username: t.get('account.guest') || 'Guest',
},
],
profile: 1,
}))
}
]
profileData.profile = 1
}
})
$effect(() => {})
$effect(() => {
if (profile.data.id || profileData) fetchUserData(profile).then((res) => {})
})
})
if (
env.PUBLIC_MIGRATE_COOKIE &&
get(profileData).profiles.length == 0 &&
profileData.profiles.length == 0 &&
env.PUBLIC_INSTANCE_URL
) {
const jwt = getCookie('jwt')
@@ -260,22 +232,14 @@ export async function setUser(jwt: string, inst: string, username?: string) {
instance.set(inst)
profileData.update((pd) => {
// too lazy to make a decent system
const id = Math.max(...pd.profiles.map((p) => p.id)) + 1
const newProfile: Profile = {
id: id,
instance: inst,
jwt: jwt,
username: user?.user?.local_user_view.person.name,
avatar: user?.user?.local_user_view.person.avatar,
}
return {
profile: id,
profiles: [newProfile, ...pd.profiles],
}
const id = Math.max(...profileData.profiles.map((p) => p.id)) + 1
profileData.profile = id
profileData.profiles.push({
id: id,
instance: inst,
jwt: jwt,
username: user?.user?.local_user_view.person.name,
avatar: user?.user?.local_user_view.person.avatar,
})
return user
@@ -326,20 +290,15 @@ async function userFromJwt(
}
export function resetProfile() {
profileData.update((p) => ({ ...p, profile: -1 }))
profileData.profile = -1
}
export function deleteProfile(id: number) {
profileData.update((pd) => {
const index = pd.profiles.findIndex((p) => p.id == id)
if (index <= -1) return pd
pd.profiles.splice(index, 1)
if (id == pd.profile) resetProfile()
return pd
})
profileData.profiles.splice(
profileData.profiles.findIndex((p) => p.id == id),
1,
)
if (id == profileData.profile) resetProfile()
}
function serializeUser(user: Profile): Profile {
@@ -350,19 +309,19 @@ function serializeUser(user: Profile): Profile {
}
export async function setUserID(id: number) {
profileData.update((p) => ({ ...p, profile: id }))
return get(profile)
if (!profileData.profiles.find((p) => p.id == id)) return -1
profileData.profile = id
return profile
}
export function moveProfile(id: number, up: boolean) {
const pd = get(profileData)
try {
const index = pd.profiles.findIndex((i) => i.id == id)
profileData.set({
...pd,
profiles: moveItem(pd.profiles, index, index + (up ? -1 : 1)),
})
const index = profileData.profiles.findIndex((i) => i.id == id)
profileData.profiles = moveItem(
profileData.profiles,
index,
index + (up ? -1 : 1),
)
} catch (err) {
// we dont care
}
@@ -406,9 +365,7 @@ async function getNotificationCount(jwt: string, mod: boolean, admin: boolean) {
}
async function checkInbox() {
if (!get(profile)) return
const { user, jwt } = get(profile)!
const { user, jwt } = profile.data
if (!jwt || !user) return
const notifs = await getNotificationCount(
@@ -66,7 +66,7 @@
let editingLoad = $state(false)
async function save() {
if (!$profile?.jwt || newComment.length <= 0) return
if (!profile.data?.jwt || newComment.length <= 0) return
editingLoad = true
@@ -64,7 +64,7 @@
<Icon src={ChatBubbleOvalLeft} size="14" micro />
<span class="text-xs">{$t('comment.reply')}</span>
</Button>
{#if $profile?.user && (amMod($profile?.user, comment.community) || isAdmin($profile.user))}
{#if profile.data?.user && (amMod(profile.data?.user, comment.community) || isAdmin(profile.data.user))}
<CommentModerationMenu bind:item={comment} />
{/if}
<Menu placement="bottom">
@@ -92,8 +92,8 @@
<Icon src={Square2Stack} mini size="16" />
<div>{$t('comment.actions.link')}</div>
</MenuButton>
{#if $profile?.jwt}
{#if comment.creator.id == $profile.user?.local_user_view.person.id}
{#if profile.data?.jwt}
{#if comment.creator.id == profile.data.user?.local_user_view.person.id}
<MenuButton onclick={() => onedit?.(comment)}>
<Icon src={PencilSquare} mini size="16" />
<span>{$t('post.actions.more.edit')}</span>
@@ -101,8 +101,12 @@
{/if}
<MenuButton
onclick={async () => {
if ($profile?.jwt)
comment.saved = await save(comment, !comment.saved, $profile.jwt)
if (profile.data?.jwt)
comment.saved = await save(
comment,
!comment.saved,
profile.data.jwt,
)
}}
>
<Icon src={comment.saved ? BookmarkSlash : Bookmark} mini size="16" />
@@ -110,15 +114,15 @@
{comment.saved ? $t('post.actions.unsave') : $t('post.actions.save')}
</span>
</MenuButton>
{#if $profile?.user && $profile.jwt && $profile.user.local_user_view.person.id == comment.creator.id}
{#if profile.data?.user && profile.data.jwt && profile.data.user.local_user_view.person.id == comment.creator.id}
<MenuButton
color="danger-subtle"
onclick={async () => {
if ($profile?.jwt)
if (profile.data?.jwt)
comment.comment.deleted = await deleteItem(
comment,
!comment.comment.deleted,
$profile.jwt,
profile.data.jwt,
)
}}
>
@@ -130,7 +134,7 @@
</span>
</MenuButton>
{/if}
{#if $profile.jwt && $profile.user?.local_user_view.person.id != comment.creator.id}
{#if profile.data.jwt && profile.data.user?.local_user_view.person.id != comment.creator.id}
<MenuButton onclick={() => report(comment)} color="danger-subtle">
<Icon src={Flag} mini size="16" />
<span>{$t('moderation.report')}</span>
@@ -49,7 +49,7 @@
let language: number | undefined = $state()
async function submit() {
if (!$profile?.user || !$profile?.jwt || value == '') return
if (!profile.data?.user || !profile.data?.jwt || value == '') return
loading = true
@@ -107,7 +107,7 @@
size="square-md"
rounding="pill"
color={language != undefined ? 'primary' : 'ghost'}
title={$t('form.profile.languages.title')}
title={$t('form.profile.data.languages.title')}
>
<Icon src={Language} size="16" micro />
</Button>
@@ -2,7 +2,6 @@
import Comment from '$lib/components/lemmy/comment/Comment.svelte'
import PostMeta from '$lib/components/lemmy/post/PostMeta.svelte'
import { publishedToDate } from '$lib/components/util/date.js'
import { getInstance } from '$lib/lemmy.js'
import { settings } from '$lib/settings.svelte.js'
import { t } from '$lib/translations'
import type { CommentView } from 'lemmy-js-client'
@@ -33,7 +33,7 @@
}: Props = $props()
const castVote = async (newVote: number) => {
if (!$profile?.jwt) {
if (!profile.data?.jwt) {
toast({ content: $t('toast.loginVoteGate'), type: 'warning' })
return
}
@@ -117,7 +117,7 @@
})
async function subscribe() {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
loading.subscribing = true
const subscribed =
community_view.subscribed == 'Subscribed' ||
@@ -226,7 +226,7 @@
<div
class="flex flex-row items-center gap-1 sticky bottom-0 drop-shadow-xl w-full"
>
{#if $profile?.jwt}
{#if profile.data?.jwt}
<Button
disabled={loading.subscribing}
loading={loading.subscribing}
@@ -250,7 +250,7 @@
: $t('cards.community.subscribe')}
</Button>
{/if}
{#if $profile?.user && amMod($profile.user, community_view.community)}
{#if profile.data?.user && amMod(profile.data.user, community_view.community)}
<Button
href="/c/{fullCommunityName(
community_view.community.name,
@@ -275,7 +275,7 @@
<Icon src={Newspaper} size="16" mini />
{$t('cards.community.modlog')}
</MenuButton>
{#if $profile?.jwt}
{#if profile.data?.jwt}
<MenuButton
color="danger-subtle"
size="lg"
@@ -289,7 +289,7 @@
? $t('cards.community.unblock')
: $t('cards.community.block')}
</MenuButton>
{#if $profile?.user}
{#if profile.data?.user}
<MenuButton
color="danger-subtle"
size="lg"
@@ -301,7 +301,7 @@
{$t('cards.community.blockInstance')}
</MenuButton>
{/if}
{#if $profile?.user && isAdmin($profile.user)}
{#if profile.data?.user && isAdmin(profile.data.user)}
<MenuButton
color="danger-subtle"
onclick={() =>
@@ -59,7 +59,7 @@
let formData = $state(passedFormData)
async function submit() {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
if ((!edit && formData.name == '') || formData.displayName == '') return
formData.submitting = true
@@ -94,23 +94,23 @@
type: 'success',
})
if ($profile.user) {
const c = $profile.user.moderates
if (profile.data.user) {
const c = profile.data.user.moderates
.map((m) => m.community.id)
.indexOf(res.community_view.community.id)
if (c != -1) {
$profile.user.moderates[c] = {
profile.data.user.moderates[c] = {
community: res.community_view.community,
moderator: $profile.user.local_user_view.person,
moderator: profile.data.user.local_user_view.person,
}
} else {
$profile.user = {
...$profile.user,
profile.data.user = {
...profile.data.user,
moderates: [
...$profile.user.moderates,
...profile.data.user.moderates,
{
community: res.community_view.community,
moderator: $profile.user.local_user_view.person,
moderator: profile.data.user.local_user_view.person,
},
],
}
@@ -159,7 +159,7 @@
/>
<TextInput
required
label={$t('form.profile.displayName')}
label={$t('form.profile.data.displayName')}
bind:value={formData.displayName}
/>
<div class="flex flex-row gap-4 flex-wrap *:flex-1">
@@ -236,7 +236,7 @@
</Select>
<div class="space-y-1">
<SectionTitle>{$t('form.profile.languages.title')}</SectionTitle>
<SectionTitle>{$t('form.profile.data.languages.title')}</SectionTitle>
<Material rounding="xl" color="uniform" class="dark:bg-zinc-950">
{#if $site}
<div class="flex gap-2 flex-wrap flex-row">
@@ -112,7 +112,7 @@
</Expandable>
{/if}
<div class="flex items-center gap-2 h-max w-max">
{#if $profile?.jwt}
{#if profile.data?.jwt}
<Subscribe
community={{
community: community,
@@ -151,7 +151,7 @@
</Subscribe>
{/if}
{#if $profile?.user && $profile.user.moderates
{#if profile.data?.user && profile.data.user.moderates
.map((c) => c.community.id)
.includes(community.id)}
<Button
@@ -179,7 +179,7 @@
<Icon src={Newspaper} size="16" mini />
{$t('cards.community.modlog')}
</MenuButton>
{#if $profile?.jwt}
{#if profile.data?.jwt}
<MenuButton
color="danger-subtle"
size="lg"
@@ -192,7 +192,7 @@
? $t('cards.community.unblock')
: $t('cards.community.block')}
</MenuButton>
{#if $profile?.user}
{#if profile.data?.user}
<MenuButton
color="danger-subtle"
size="lg"
@@ -204,7 +204,7 @@
{$t('cards.community.blockInstance')}
</MenuButton>
{/if}
{#if $profile?.user && isAdmin($profile.user)}
{#if profile.data?.user && isAdmin(profile.data.user)}
<MenuButton
color="danger-subtle"
onclick={() =>
@@ -104,7 +104,7 @@
<Subscribe {community}>
{#snippet children({ subscribe, subscribing })}
<Button
disabled={subscribing || !$profile?.jwt}
disabled={subscribing || !profile.data?.jwt}
loading={subscribing}
onclick={async () => {
const res = await subscribe()
@@ -52,14 +52,14 @@
<Option value="Local" icon={MapPin}>{$t('filter.location.local')}</Option>
<Option
value="Subscribed"
disabled={$profile?.jwt == undefined}
disabled={profile.data?.jwt == undefined}
icon={Newspaper}
>
{$t('filter.location.subscribed')}
</Option>
<Option
value="ModeratorView"
disabled={!$profile?.jwt || !amModOfAny($profile?.user)}
disabled={!profile.data?.jwt || !amModOfAny(profile.data?.user)}
icon={ShieldCheck}
>
{$t('filter.location.moderator')}
@@ -24,7 +24,7 @@
avatar
avatarSize={20}
/>
{#if $profile?.user?.local_user_view.person.id != message.recipient.id}
{#if profile.data?.user?.local_user_view.person.id != message.recipient.id}
to
<UserLink
showInstance={false}
@@ -30,7 +30,7 @@
</script>
<Modal bind:open>
{#snippet title()}
{#snippet customTitle()}
<h1 class="text-2xl font-bold">
{$t('routes.admin.applications.modalTitle')}
</h1>
@@ -32,7 +32,7 @@
)
async function upload() {
if (!$profile?.jwt || image == null) return
if (!profile.data?.jwt || image == null) return
progress = 0
@@ -40,7 +40,7 @@
const uploaded = (
await Promise.all(
Array.from(image).map((i) =>
uploadImage(i, $profile.instance, $profile.jwt!)
uploadImage(i, profile.data.instance, profile.data.jwt!)
.then((uploaded) => {
progress += 1 / (image?.length ?? 0)
return uploaded
@@ -22,7 +22,7 @@
let loading = $state(false)
async function sendMessage() {
if (!$profile?.jwt || message == '') return
if (!profile.data?.jwt || message == '') return
loading = true
@@ -50,7 +50,7 @@
</script>
<Modal bind:open>
{#snippet title()}
{#snippet customTitle()}
<h1 class="text-2xl font-bold">Message</h1>
{/snippet}
<form onsubmit={preventDefault(sendMessage)} class="flex flex-col gap-4">
@@ -43,7 +43,7 @@
})
async function submit() {
if (!item || !$profile?.user || !$profile?.jwt) return
if (!item || !profile.data?.user || !profile.data?.jwt) return
loading = true
@@ -33,9 +33,9 @@
<ShieldIcon filled width={14} />
</Button>
{/snippet}
{#if ($profile?.user && amMod($profile.user, item.community)) || ($profile?.user && isAdmin($profile.user))}
{#if (profile.data?.user && amMod(profile.data.user, item.community)) || (profile.data?.user && isAdmin(profile.data.user))}
<MenuDivider>
{#if !item.community.local && !amMod($profile.user, item.community)}
{#if !item.community.local && !amMod(profile.data.user, item.community)}
{$t('moderation.labelInstanceOnly')}
{:else}
{$t('moderation.label')}
@@ -53,7 +53,7 @@
{item.post.removed ? $t('moderation.restore') : $t('moderation.remove')}
{/if}
</MenuButton>
{#if $profile?.user && $profile.user?.local_user_view.person.id != item.creator.id}
{#if profile.data?.user && profile.data.user?.local_user_view.person.id != item.creator.id}
<!--Comment made by someone else-->
<MenuButton
color="danger-subtle"
@@ -72,12 +72,12 @@
<MenuButton
color="success-subtle"
onclick={async () => {
if (!$profile.jwt) return
if (!profile.data.jwt) return
item.comment = (
await feature(
!item.comment.distinguished,
item.comment,
$profile.jwt,
profile.data.jwt,
)
).comment_view.comment
}}
@@ -92,7 +92,7 @@
{/if}
{/if}
{#if $profile?.user && isAdmin($profile.user)}
{#if profile.data?.user && isAdmin(profile.data.user)}
<MenuDivider>{$t('admin.label')}</MenuDivider>
<MenuButton color="danger-subtle" onclick={() => remove(item, true)}>
{#snippet prefix()}
@@ -31,7 +31,7 @@
let acting = $derived(locking || pinning)
async function lock(lock: boolean) {
if (!$profile?.jwt || !isPostView(item)) return
if (!profile.data?.jwt || !isPostView(item)) return
locking = true
try {
@@ -52,7 +52,7 @@
}
async function pin(pinned: boolean, toInstance: boolean = false) {
if (!$profile?.jwt || !isPostView(item)) return
if (!profile.data?.jwt || !isPostView(item)) return
pinning = true
@@ -87,9 +87,9 @@
<ShieldIcon filled width={16} />
</Button>
{/snippet}
{#if ($profile?.user && amMod($profile.user, item.community)) || ($profile?.user && isAdmin($profile.user))}
{#if (profile.data?.user && amMod(profile.data.user, item.community)) || (profile.data?.user && isAdmin(profile.data.user))}
<MenuDivider>
{#if !item.community.local && !amMod($profile.user, item.community)}
{#if !item.community.local && !amMod(profile.data.user, item.community)}
{$t('moderation.labelInstanceOnly')}
{:else}
{$t('moderation.label')}
@@ -123,7 +123,7 @@
? $t('moderation.unfeature')
: $t('moderation.feature')}
</span>
{#if isAdmin($profile.user)}
{#if isAdmin(profile.data.user)}
<span class="text-xs opacity-80">{$t('form.post.community')}</span>
{/if}
</div>
@@ -138,7 +138,7 @@
{item.post.removed ? $t('moderation.restore') : $t('moderation.remove')}
{/if}
</MenuButton>
{#if $profile?.user && $profile.user.local_user_view.person.id != item.creator.id}
{#if profile.data?.user && profile.data.user.local_user_view.person.id != item.creator.id}
<MenuButton
color="danger-subtle"
onclick={() =>
@@ -151,7 +151,7 @@
</MenuButton>
{/if}
{/if}
{#if $profile?.user && isAdmin($profile.user)}
{#if profile.data?.user && isAdmin(profile.data.user)}
<MenuDivider>{$t('admin.label')}</MenuDivider>
<MenuButton
color="success-subtle"
@@ -66,7 +66,7 @@
async function remove() {
if (!item) return
if (!$profile?.jwt) throw new Error('Unauthenticated')
if (!profile.data?.jwt) throw new Error('Unauthenticated')
loading = true
@@ -207,7 +207,7 @@
bind:value={reason}
/>
{#if !removed && $profile?.user && (amMod($profile.user, item.community) || (isAdmin($profile.user) && item.community.local))}
{#if !removed && profile.data?.user && (amMod(profile.data.user, item.community) || (isAdmin(profile.data.user) && item.community.local))}
<Switch bind:checked={commentReason}>
{$t('moderation.removeSubmission.withReason')}
</Switch>
@@ -41,7 +41,7 @@
let reason = $state('')
async function report() {
if (!item || !$profile?.jwt || reason == '') return
if (!item || !profile.data?.jwt || reason == '') return
loading = true
try {
+3 -11
View File
@@ -1,21 +1,13 @@
<script lang="ts">
import type { PostView } from 'lemmy-js-client'
import { isImage, isVideo } from '$lib/ui/image.js'
import { getInstance } from '$lib/lemmy.js'
import PostActions from '$lib/components/lemmy/post/PostActions.svelte'
import { settings, type View } from '$lib/settings.svelte.js'
import PostLink from '$lib/components/lemmy/post/link/PostLink.svelte'
import PostMeta, {
parseTags,
type Tag,
} from '$lib/components/lemmy/post/PostMeta.svelte'
import { Badge, Material, toast } from 'mono-svelte'
import {
bestImageURL,
mediaType,
postLink,
} from '$lib/components/lemmy/post/helpers.js'
import Empty from '$lib/components/helper/Empty.svelte'
import { Badge } from 'mono-svelte'
import { mediaType, postLink } from '$lib/components/lemmy/post/helpers.js'
import { publishedToDate } from '$lib/components/util/date.js'
import { ArrowUp, ChatBubbleOvalLeft, Icon } from 'svelte-hero-icons'
import PostMedia from '$lib/components/lemmy/post/media/PostMedia.svelte'
@@ -128,7 +120,7 @@
admin: post.creator_is_admin,
moderator: post.creator_is_moderator,
}}
subscribed={$profile?.user?.follows
subscribed={profile.data?.user?.follows
.map((c) => c.community.id)
.includes(post.community.id)
? 'Subscribed'
@@ -1,17 +1,15 @@
<script lang="ts">
import type { PostView } from 'lemmy-js-client'
import PostVote from './PostVote.svelte'
import { getInstance, site } from '$lib/lemmy.js'
import { site } from '$lib/lemmy.js'
import {
ArrowsUpDown,
ArrowTopRightOnSquare,
Bookmark,
BookmarkSlash,
BugAnt,
ChatBubbleLeftEllipsis,
ChatBubbleOvalLeft,
ChatBubbleOvalLeftEllipsis,
CheckBadge,
Clock,
EllipsisHorizontal,
Eye,
@@ -19,20 +17,16 @@
Flag,
GlobeAmericas,
Icon,
Language,
MapPin,
Newspaper,
Pencil,
PencilSquare,
ServerStack,
Share,
Star,
Trash,
UserCircle,
XMark,
} from 'svelte-hero-icons'
import FormattedNumber from '$lib/components/util/FormattedNumber.svelte'
import { createEventDispatcher } from 'svelte'
import {
amMod,
isAdmin,
@@ -101,7 +95,7 @@
<div class="mx-auto h-96 flex justify-center items-center">
<Spinner width={32} />
</div>
{:then {default: PostForm }}
{:then { default: PostForm }}
<PostForm
edit
editingPost={post.post}
@@ -131,7 +125,7 @@
score={post.counts.score}
upvotes={post.counts.upvotes}
downvotes={post.counts.downvotes}
showCounts={$profile?.user?.local_user_view?.local_user?.show_scores ??
showCounts={profile.data?.user?.local_user_view?.local_user?.show_scores ??
true}
/>
@@ -176,7 +170,7 @@
{/snippet}
</Button>
{/if}
{#if $profile?.user && (amMod($profile.user, post.community) || isAdmin($profile.user))}
{#if profile.data?.user && (amMod(profile.data.user, post.community) || isAdmin(profile.data.user))}
<ModerationMenu
size="custom"
color="ghost"
@@ -187,12 +181,12 @@
/>
{/if}
{#if $profile?.jwt}
{#if profile.data?.jwt}
<Button
onclick={async () => {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
saving = true
post.saved = await save(post, !post.saved, $profile?.jwt)
post.saved = await save(post, !post.saved, profile.data?.jwt)
saving = false
}}
size="custom"
@@ -304,7 +298,7 @@
<MenuDivider>
{$t('post.actions.more.actions')}
</MenuDivider>
{#if $profile?.user && $profile?.jwt && $profile.user.local_user_view.person.id == post.creator.id}
{#if profile.data?.user && profile.data?.jwt && profile.data.user.local_user_view.person.id == post.creator.id}
<MenuButton onclick={() => (editing = true)}>
{#snippet prefix()}
<Icon src={PencilSquare} size="16" micro />
@@ -312,11 +306,15 @@
{$t('post.actions.more.edit')}
</MenuButton>
{/if}
{#if $profile?.jwt}
{#if profile.data?.jwt}
<MenuButton
onclick={async () => {
if ($profile?.jwt)
post.read = await markAsRead(post.post, !post.read, $profile.jwt)
if (profile.data?.jwt)
post.read = await markAsRead(
post.post,
!post.read,
profile.data.jwt,
)
}}
>
{#snippet prefix()}
@@ -331,12 +329,12 @@
onclick={() => {
navigator.share?.({
url: localShare
? `${instanceToURL(getInstance())}/post/${post.post.id}`
? `${instanceToURL(profile.data.instance)}/post/${post.post.id}`
: post.post.ap_id,
}) ??
navigator.clipboard.writeText(
localShare
? `${instanceToURL(getInstance())}/post/${post.post.id}`
? `${instanceToURL(profile.data.instance)}/post/${post.post.id}`
: post.post.ap_id,
)
toast({ content: $t('toast.copied') })
@@ -371,7 +369,7 @@
</div>
{/if}
</MenuButton>
{#if $profile?.jwt}
{#if profile.data?.jwt}
<MenuButton
onclick={() => {
setSessionStorage('postDraft', {
@@ -400,14 +398,14 @@
{/snippet}
{$t('post.actions.more.crosspost')}
</MenuButton>
{#if $profile.user && post.creator.id == $profile.user.local_user_view.person.id}
{#if profile.data.user && post.creator.id == profile.data.user.local_user_view.person.id}
<MenuButton
onclick={async () => {
if ($profile?.jwt)
if (profile.data?.jwt)
post.post.deleted = await deleteItem(
post,
!post.post.deleted,
$profile.jwt,
profile.data.jwt,
)
}}
color="danger-subtle"
@@ -420,15 +418,15 @@
: $t('post.actions.more.delete')}
</MenuButton>
{/if}
{#if $profile.user?.local_user_view.person.id != post.creator.id}
{#if profile.data.user?.local_user_view.person.id != post.creator.id}
{#if feature('hidePosts', $site?.version)}
<MenuButton
onclick={async () => {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
const hidden = await hidePost(
post.post.id,
!post.hidden,
$profile?.jwt,
profile.data?.jwt,
)
post.hidden = hidden
if (hidden) onhide?.(hidden)
@@ -43,8 +43,6 @@
</script>
<script lang="ts">
import { stopPropagation } from 'svelte/legacy'
import CommunityLink from '$lib/components/lemmy/community/CommunityLink.svelte'
import Avatar from '$lib/components/ui/Avatar.svelte'
import { Badge, Popover } from 'mono-svelte'
@@ -63,7 +61,6 @@
Trash,
PaperAirplane,
} from 'svelte-hero-icons'
import { getInstance } from '$lib/lemmy.js'
import ShieldIcon from '../moderation/ShieldIcon.svelte'
import { settings, type View } from '$lib/settings.svelte'
import Markdown from '$lib/components/markdown/Markdown.svelte'
@@ -71,6 +68,7 @@
import { Pencil, type IconSource } from 'svelte-hero-icons'
import CommunityHeader from '../community/CommunityHeader.svelte'
import { publishedToDate } from '$lib/components/util/date'
import { profile } from '$lib/auth.svelte'
interface Props {
community?: Community | undefined
@@ -287,7 +285,7 @@
</header>
{#if title && id}
<a
href="/post/{getInstance()}/{id}"
href="/post/{profile.data.instance}/{id}"
class="inline hover:underline
hover:text-primary-900 hover:dark:text-primary-100 transition-colors max-[480px]:!mt-0
{settings.font == 'satoshi/nunito'
@@ -54,14 +54,14 @@
let oldScore = score
const castVote = async (newVote: number) => {
if (!$profile?.jwt) {
if (!profile.data?.jwt) {
toast({ content: $t('toast.loginVoteGate'), type: 'warning' })
return
}
loading = true
oldScore = score
vote = newVote
const res = await voteItem(post, newVote, $profile.jwt).catch((e) => {
const res = await voteItem(post, newVote, profile.data.jwt).catch((e) => {
toast({ content: errorMessage(e), type: 'error' })
return { upvotes: 0, downvotes: 0, score: 0 }
})
@@ -133,7 +133,7 @@
})
return
}
if (!data.title || !$profile?.jwt) return
if (!data.title || !profile.data?.jwt) return
if (data.url && data.url != '') {
try {
new URL(data.url)
@@ -278,7 +278,7 @@
<ObjectAutocomplete
bind:q={communitySearch}
items={communities}
jwt={$profile?.jwt}
jwt={profile.data?.jwt}
listing_type="All"
label={$t('form.post.community')}
required
+5 -2
View File
@@ -1,8 +1,10 @@
import { client, getInstance } from '$lib/lemmy.js'
import { profile } from '$lib/auth.svelte'
import { client } from '$lib/lemmy.js'
import type { View } from '$lib/settings.svelte'
import { isImage, isVideo } from '$lib/ui/image'
import { canParseUrl, findClosestNumber } from '$lib/util.svelte'
import type { CommentView, PersonView, Post, PostView } from 'lemmy-js-client'
import { get } from 'svelte/store'
export const isCommentMutable = (comment: CommentView, me: PersonView) =>
me.person.id == comment.creator.id
@@ -57,7 +59,8 @@ export const isYoutubeLink = (url?: string): RegExpMatchArray | null => {
return url?.match?.(YOUTUBE_REGEX)
}
export const postLink = (post: Post) => `/post/${getInstance()}/${post.id}`
export const postLink = (post: Post) =>
`/post/${profile.data.instance}/${post.id}`
export type MediaType = 'video' | 'image' | 'iframe' | 'embed' | 'none'
export type IframeType = 'youtube' | 'video' | 'none'
+3 -11
View File
@@ -29,7 +29,7 @@
let customHref = (href?: string) => {
if (href?.startsWith('?')) {
const current = pageData.url.searchParams
const current = new URLSearchParams(pageData.url.searchParams)
const newParams = new URLSearchParams(href)
current.delete(newParams.keys().toArray()[0])
@@ -56,11 +56,7 @@
<Button
href={customHref(href?.(cursor?.back ?? page - 1))}
color="ghost"
onclick={() => {
invalidateAll()
if (cursor?.back) onchangecursor?.(cursor.back)
else onchange?.(--page)
}}
onclick={() => invalidateAll()}
title={$t('common.back')}
size="square-md"
rounding="pill"
@@ -91,11 +87,7 @@
<Button
href={customHref(href?.(cursor?.next ?? page + 1))}
color="ghost"
onclick={() => {
invalidateAll()
if (cursor?.next) onchangecursor?.(cursor?.next)
else onchange?.(++page)
}}
onclick={() => invalidateAll()}
title={$t('common.next')}
size="square-md"
rounding="pill"
+7 -7
View File
@@ -77,7 +77,7 @@
style="border-radius: inherit;"
>
<div class="ml-auto"></div>
{#if $profile?.user && isAdmin($profile.user)}
{#if profile.data?.user && isAdmin(profile.data.user)}
<NavButton
href="/admin"
label={$t('nav.admin')}
@@ -92,7 +92,7 @@
{/if}
</NavButton>
{/if}
{#if amModOfAny($profile?.user)}
{#if amModOfAny(profile.data?.user)}
<NavButton
href="/moderation"
label={$t('nav.moderation')}
@@ -124,7 +124,7 @@
/>
{/snippet}
<MenuDivider>{$t('nav.create.label')}</MenuDivider>
<MenuButton link href="/create/post" disabled={!$profile?.jwt}>
<MenuButton link href="/create/post" disabled={!profile.data?.jwt}>
{#snippet prefix()}
<Icon src={PencilSquare} size="16" micro />
{/snippet}
@@ -133,17 +133,17 @@
<MenuButton
link
href="/create/community"
disabled={!$profile?.jwt ||
!$profile?.user ||
disabled={!profile.data?.jwt ||
!profile.data?.user ||
($site?.site_view.local_site.community_creation_admin_only &&
!isAdmin($profile.user))}
!isAdmin(profile.data.user))}
>
{#snippet prefix()}
<Icon src={Newspaper} size="16" micro />
{/snippet}
{$t('nav.create.community')}
</MenuButton>
{#if !$profile?.jwt}
{#if !profile.data?.jwt}
<span class="text-sm mx-4 my-1 py-1">
{$t('nav.create.logingate')}
</span>
+6 -6
View File
@@ -74,14 +74,14 @@
hover:border-primary-900 hover:dark:border-primary-100 active:scale-95 {buttonClass}"
title={$t('profile.profile')}
>
{#if $profile?.user}
{#if profile.data?.user}
<div
class="w-full h-full aspect-square object-cover rounded-full grid place-items-center"
>
<Avatar
url={$profile.user.local_user_view.person.avatar}
url={profile.data.user.local_user_view.person.avatar}
width={36}
alt={$profile.user.local_user_view.person.name}
alt={profile.data.user.local_user_view.person.name}
/>
</div>
{#if $notifications.inbox > 0}
@@ -96,9 +96,9 @@
{/if}
</button>
{/snippet}
{#if $profile?.user}
{#if profile.data?.user}
<UserLink
user={$profile?.user.local_user_view.person}
user={profile.data?.user.local_user_view.person}
showInstance={false}
avatar
avatarSize={24}
@@ -108,7 +108,7 @@
{:else}
<MenuDivider>{$t('nav.menu.label')}</MenuDivider>
{/if}
{#if $profile?.jwt}
{#if profile.data?.jwt}
<MenuButton link href="/profile">
{#snippet prefix()}
<Icon src={UserCircle} micro width={16} />
@@ -23,7 +23,6 @@
<Button
href={action.href}
onclick
alignment="left"
color="tertiary"
size="lg"
@@ -229,8 +229,8 @@
$effect(() => {
groups = getGroups(
$resumables,
$profile,
$profileData.profiles,
profile.data,
profileData.profiles,
$themeData,
page.data.contextual?.actions,
)
@@ -92,7 +92,7 @@ export function getGroups(
name: t.get('nav.communities'),
icon: GlobeAlt,
},
...(amModOfAny(profile.user)
...(amModOfAny(profile.data.user)
? [
{
href: '/moderation',
@@ -101,7 +101,7 @@ export function getGroups(
},
]
: []),
...(profile.user && isAdmin(profile.user)
...(profile.data.user && isAdmin(profile.data.user)
? [
{
href: '/admin',
@@ -236,23 +236,23 @@ export function getGroups(
],
},
{
name: t.get('profile.profile'),
actions: profile.jwt
name: t.get('profile.data.profile'),
actions: profile.data.jwt
? [
{
href: '/profile/user',
name: t.get('profile.profile'),
name: t.get('profile.data.profile'),
icon: UserCircle,
},
{
href: '/inbox',
name: t.get('profile.inbox'),
name: t.get('profile.data.inbox'),
icon: Inbox,
shortcut: 'i',
},
{
href: '/saved',
name: t.get('profile.saved'),
name: t.get('profile.data.saved'),
icon: Bookmark,
},
{
@@ -311,7 +311,7 @@ export function getGroups(
icon: p.avatar ?? UserCircle,
detail: p.instance,
handle: async () => {
if (profile.id != p.id) {
if (profile.data.id != p.id) {
await setUserID(p.id)
}
@@ -407,9 +407,9 @@ export function getGroups(
],
},
{
name: t.get('profile.subscribed'),
name: t.get('profile.data.subscribed'),
actions:
profile?.user?.follows.map((f) => ({
profile.data?.user?.follows.map((f) => ({
icon: f.community.icon,
name: f.community.title,
href: `/c/${fullCommunityName(
@@ -25,7 +25,7 @@
animate:flip={{ duration: 500, easing: expoOut }}
>
<div class="flex-none grid group">
{#if $profile && !hasFavorite($profile, follow.id)}
{#if profile && !hasFavorite(profile.data, follow.id)}
<Button
rounding="pill"
size="custom"
@@ -36,7 +36,7 @@
>
<Icon src={Star} size="16" mini />
</Button>
{:else if isFavorites && $profile && hasFavorite($profile, follow.id)}
{:else if isFavorites && profile && hasFavorite(profile.data, follow.id)}
<Button
rounding="pill"
size="custom"
@@ -53,7 +53,7 @@
alt={follow.name}
title={follow.title}
width={28}
class={!isFavorites && $profile && hasFavorite($profile, follow.id)
class={!isFavorites && profile && hasFavorite(profile.data, follow.id)
? ''
: 'group-hover:hidden'}
/>
@@ -23,21 +23,22 @@
alignment="left"
loading={switching}
loaderWidth={20}
selected={$profile?.id == prof.id}
selected={profile.data?.id == prof.id}
onclick={async () => {
switching = true
if ($profile?.id != prof.id) {
if (profile.data?.id != prof.id) {
await setUserID(prof.id)
}
await goto(page.url, {
invalidateAll: true,
})
console.log(page.url)
// await goto(page.url, {
// invalidateAll: true,
// })
switching = false
}}
class="w-full font-normal {$profile?.id == prof.id
class="w-full font-normal {profile.data?.id == prof.id
? '!bg-slate-100 dark:!bg-zinc-900'
: ''}"
>
@@ -46,11 +47,11 @@
profile={prof}
{index}
{guest}
selected={$profile?.id == prof.id}
selected={profile.data?.id == prof.id}
/>
{/snippet}
<span
class="inline-flex flex-col gap-0 {$profile?.id == prof.id
class="inline-flex flex-col gap-0 {profile.data?.id == prof.id
? 'font-semibold'
: ''}"
>
+15 -13
View File
@@ -33,7 +33,7 @@
gap-1 h-fit max-h-screen {clazz}"
{style}
>
{#if $profile?.jwt}
{#if profile.data?.jwt}
<SidebarButton icon={UserCircle} href="/profile">
{#snippet label()}
<span>
@@ -90,7 +90,7 @@
{/snippet}
</SidebarButton>
{/if}
{#if $profileData.profiles.length >= 1}
{#if profileData.profiles.length >= 1}
<hr class="border-slate-200 dark:border-zinc-900 my-1" />
<Expandable
@@ -103,13 +103,13 @@
{$t('account.accounts')}
{#snippet action()}
<span class="dark:text-white text-black">
{$profileData.profiles.length}
{profileData.profiles.length}
</span>
{/snippet}
</EndPlaceholder>
</span>
{/snippet}
{#each [...$profileData.profiles] as prof, index}
{#each [...profileData.profiles] as prof, index}
<div class="w-full">
<ProfileButton {index} {prof} />
</div>
@@ -120,7 +120,7 @@
</Expandable>
{/if}
<hr class="border-slate-200 dark:border-zinc-900 my-1" />
{#if $profile?.favorites && $profile?.favorites.length > 0}
{#if profile.data?.favorites && profile.data?.favorites.length > 0}
<Expandable
class="max-w-full min-w-0 w-full"
bind:open={settings.expand.favorites}
@@ -135,18 +135,18 @@
{$t('routes.profile.favorites')}
{#snippet action()}
<span class="dark:text-white text-black">
{$profile.favorites?.length}
{profile.data.favorites?.length}
</span>
{/snippet}
</EndPlaceholder>
</span>
{/snippet}
<CommunityList isFavorites items={$profile.favorites} />
<CommunityList isFavorites items={profile.data.favorites} />
</Expandable>
<hr class="border-slate-200 dark:border-zinc-900 my-1" />
{/if}
{#if $profile?.user}
{#if $profile?.user.moderates.length > 0}
{#if profile.data?.user}
{#if profile.data?.user.moderates.length > 0}
<Expandable
class="max-w-full min-w-0 w-full"
bind:open={settings.expand.moderates}
@@ -161,14 +161,14 @@
{$t('routes.profile.moderates')}
{#snippet action()}
<span class="dark:text-white text-black">
{$profile.user?.moderates.length}
{profile.data.user?.moderates.length}
</span>
{/snippet}
</EndPlaceholder>
</span>
{/snippet}
<CommunityList
items={$profile.user.moderates.map((i) => i.community)}
items={profile.data.user.moderates.map((i) => i.community)}
/>
</Expandable>
<hr class="border-slate-200 dark:border-zinc-900 my-1" />
@@ -188,13 +188,15 @@
{$t('profile.subscribed')}
{#snippet action()}
<span class="dark:text-white text-black">
{$profile.user?.follows.length}
{profile.data.user?.follows.length}
</span>
{/snippet}
</EndPlaceholder>
</span>
{/snippet}
<CommunityList items={$profile.user.follows.map((i) => i.community)} />
<CommunityList
items={profile.data.user.follows.map((i) => i.community)}
/>
</Expandable>
{/if}
</nav>
@@ -12,7 +12,7 @@
</script>
<Modal bind:open>
{#snippet title()}
{#snippet customTitle()}
<span>
{#if title}{@render title()}{:else}Debug{/if}
</span>
+2 -14
View File
@@ -11,16 +11,6 @@ export const site = writable<GetSiteResponse | undefined>(undefined)
const isURL = (input: RequestInfo | URL): input is URL =>
typeof input == 'object' && 'searchParams' in input
const toURL = (input: RequestInfo | URL): URL | undefined => {
if (isURL(input)) return input
try {
return new URL(input.toString())
} catch (e) {
return
}
}
async function customFetch(
func:
| ((
@@ -67,9 +57,9 @@ export function client({
) => Promise<Response>
auth?: string
} = {}) {
if (!instanceURL) instanceURL = get(profile).instance
if (!instanceURL) instanceURL = profile.data.instance
let jwt = auth ? auth : get(profile)?.jwt
let jwt = auth ? auth : profile.data?.jwt
const headers = jwt ? { authorization: `Bearer ${jwt}` } : {}
@@ -91,8 +81,6 @@ export function getClient(
return client({ instanceURL, func, auth })
}
export const getInstance = () => encodeURIComponent(get(instance))
export async function validateInstance(instance: string): Promise<boolean> {
if (instance == '') return false
+1 -1
View File
@@ -105,7 +105,7 @@ export let resumables = resumableStore()
export function addFavorite(item: Community, add: boolean = true) {
const pd = get(profileData)
const p = pd.profiles.find((p) => p.id == get(profile)?.id)
const p = pd.profiles.find((p) => p.id == profile.data?.id)
if (!p) return
let favs = p.favorites ?? []
+4 -4
View File
@@ -5,7 +5,7 @@ import type { Community, MyUserInfo, PersonView } from 'lemmy-js-client'
import { get } from 'svelte/store'
export const blockUser = async (block: boolean, id: number) => {
const auth = get(profile)?.jwt
const auth = profile.data?.jwt
if (!auth) throw new Error('Unauthorized')
@@ -22,7 +22,7 @@ export const addSubscription = (
community: Community,
subscribe: boolean = true,
) => {
const p = get(profile)
const p = profile
if (!p.user) return
@@ -38,7 +38,7 @@ export const addSubscription = (
p.user.follows.splice(index, 1)
}
profile.set(p)
profile.data.set(p)
}
export const addAdmin = async (handle: string, added: boolean, jwt: string) =>
@@ -56,4 +56,4 @@ export const addAdmin = async (handle: string, added: boolean, jwt: string) =>
})
export const hasFavorite = (profile: Profile, id: number): boolean =>
profile?.favorites?.map((i) => i.id).includes(id) ?? false
profile.data?.favorites?.map((i) => i.id).includes(id) ?? false
-2
View File
@@ -2,8 +2,6 @@
import { browser } from '$app/environment'
type AnyFunction = (...args: any[]) => any
export const awaitIfServer = async <T>(
promise: Promise<T>,
): Promise<{
-7
View File
@@ -1,6 +1,5 @@
import { browser } from '$app/environment'
import type { Community } from 'lemmy-js-client'
import { writable } from 'svelte/store'
interface SessionStorage {
lastSeenCommunity: Community | undefined
@@ -35,9 +34,3 @@ export const getSessionStorage = (
if (!browser) return
return JSON.parse(sessionStorage.getItem(key)!)
}
interface Route {
title: string
}
export const route = writable<Route | undefined>(undefined)
+8 -9
View File
@@ -52,7 +52,7 @@
{#if debugging}
<DebugObject
object={debugProfile?.id == $profile?.id ? $profile : debugProfile}
object={debugProfile?.id == profile.data?.id ? profile : debugProfile}
bind:open={debugging}
>
{#snippet title()}
@@ -101,7 +101,7 @@
</Modal>
{/if}
{#if $profileData.profiles.length == 0}
{#if profileData.profiles.length == 0}
<div class="h-max flex items-center justify-center my-auto">
<div
class="flex flex-col justify-center items-center py-8 gap-4
@@ -158,29 +158,28 @@
{/snippet}
</Header>
<div>
{#each $profileData.profiles as profile, index (profile.id)}
{#each profileData.profiles as profile, index}
<div
class="flex flex-row gap-2 items-center py-3"
transition:fly={{ duration: 500, y: -12, easing: expoOut }}
animate:flip={{ duration: 500, easing: expoOut }}
>
<Button
title={profile.id == $currentProfile?.id ? 'Switch' : 'Current'}
title={profile.id == currentProfile?.data.id ? 'Switch' : 'Current'}
onclick={async () => {
if (profile.id != $currentProfile?.id) {
if (profile.id != currentProfile?.data.id) {
switching = profile.id
await setUserID(profile.id)
switching = -69
}
}}
size="square-md"
color={profile.id == $currentProfile?.id ? 'primary' : 'ghost'}
color={profile.id == currentProfile?.data.id ? 'primary' : 'ghost'}
loading={switching == profile.id}
disabled={switching == profile.id}
rounding="pill"
>
{#snippet prefix()}
{#if profile.id == $currentProfile?.id}
{#if profile.id == currentProfile?.data.id}
<Icon src={Check} mini size="16" />
{:else}
<Icon src={ArrowsRightLeft} size="16" mini />
@@ -191,7 +190,7 @@
<ProfileAvatar
{profile}
{index}
selected={$currentProfile?.id == profile.id}
selected={currentProfile?.data.id == profile.id}
size={24}
/>
<div class="flex flex-col">
+2 -2
View File
@@ -4,8 +4,8 @@ import { getClient } from '$lib/lemmy.js'
import { site as siteStore } from '$lib/lemmy'
export async function load({ fetch }) {
if (!get(profile)) return
let { jwt } = get(profile)!
if (!profile) return
let { jwt } = profile!
let site = get(siteStore)
if (!site) {
+2 -2
View File
@@ -3,9 +3,9 @@ import { getClient } from '$lib/lemmy.js'
import { get } from 'svelte/store'
export async function load({ data, fetch, url }) {
if (!get(profile)) return
if (!profile) return
const { jwt } = get(profile)!
const { jwt } = profile.data!
if (!jwt) return
const page = Number(url.searchParams.get('page')) || 1
@@ -27,7 +27,7 @@
let reviewing = $state(false)
async function review(approve: boolean) {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
let registrationApplicationAnswer: ApproveRegistrationApplication = {
approve: approve,
@@ -61,7 +61,7 @@
type: 'success',
})
application.creator_local_user.accepted_application = approve
application.admin = $profile.user!.local_user_view.person
application.admin = profile.data.user!.local_user_view.person
application.registration_application.deny_reason = denyReason
$notifications.applications -= 1
+4 -4
View File
@@ -38,10 +38,10 @@
)
async function save() {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
saving = true
const { jwt } = $profile
const { jwt } = profile.data
try {
await getClient().editSite({
@@ -242,8 +242,8 @@
</Switch>
<div class="space-y-1">
<SectionTitle>{$t('form.profile.languages.title')}</SectionTitle>
<p>{$t('form.profile.languages.description')}</p>
<SectionTitle>{$t('form.profile.data.languages.title')}</SectionTitle>
<p>{$t('form.profile.data.languages.description')}</p>
<Material rounding="xl" color="uniform" class="dark:bg-zinc-950">
{#if $site && formData.discussion_languages}
<div class="flex gap-2 flex-wrap flex-row">
+2 -2
View File
@@ -46,7 +46,7 @@
if (instance == '') return
await trycatch(async () => {
if (
!$profile?.jwt ||
!profile.data?.jwt ||
!data.federated_instances?.federated_instances?.blocked ||
!data.federated_instances?.federated_instances?.allowed
)
@@ -87,7 +87,7 @@
const save = async () => {
const res = await trycatch(async () => {
if (
!$profile?.jwt ||
!profile.data?.jwt ||
!data.federated_instances?.federated_instances?.blocked
)
return
+1 -1
View File
@@ -23,7 +23,7 @@
let saving = $state(false)
async function save() {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
saving = true
+7 -3
View File
@@ -27,7 +27,7 @@
action: () => removeAdmin(id, true),
})
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
const result = await trycatch(() =>
getClient().addAdmin({
@@ -75,10 +75,14 @@
class="flex flex-row items-center gap-2 mt-auto w-full"
onsubmit={preventDefault(() => {
trycatch(async () => {
if (!$profile?.jwt || newAdmin == '') return
if (!profile.data?.jwt || newAdmin == '') return
adding = true
const r = await addAdmin(`${newAdmin}@${$instance}`, true, $profile.jwt)
const r = await addAdmin(
`${newAdmin}@${$instance}`,
true,
profile.data.jwt,
)
if (!r) return
toast({
@@ -24,7 +24,7 @@
})
async function addModerator() {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
formData.addingModerator = true
@@ -81,7 +81,7 @@
}
async function removeMod(id: number) {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
try {
const res = await getClient().addModToCommunity({
+3 -2
View File
@@ -1,7 +1,8 @@
import { getInstance } from '$lib/lemmy.js'
import { profile } from '$lib/auth.svelte.js'
import { redirect } from '@sveltejs/kit'
import { get } from 'svelte/store'
export function load({ params }) {
// If you somehow got to /comment/instance, it likely means you passed in an ID, not an instance.
redirect(302, `/comment/${getInstance()}/${params.instance}`)
redirect(302, `/comment/${profile.data.instance}/${params.instance}`)
}
+1 -1
View File
@@ -17,7 +17,7 @@
id: number | undefined = community?.community.id,
subscribed: SubscribedType | undefined = community?.subscribed,
) {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
if (!id || !subscribed) return
subscribing = true
+1 -1
View File
@@ -14,7 +14,7 @@
} = $props()
onMount(() => {
if (!$profile?.jwt) {
if (!profile.data?.jwt) {
goto('/login')
}
})
+1 -1
View File
@@ -35,7 +35,7 @@
let markingAsRead = $state(false)
async function markAllAsRead() {
if (!$profile?.user) {
if (!profile.data?.user) {
goto('/login')
return
}
+1 -1
View File
@@ -11,7 +11,7 @@ import { get } from 'svelte/store'
type InboxFeedType = 'replies' | 'mentions' | 'messages' | 'all'
export async function load({ url, fetch }) {
const auth = get(profile)
const auth = profile
if (!auth?.jwt) return
const type: InboxFeedType =
+2 -2
View File
@@ -39,7 +39,7 @@
let loading = $state(false)
async function markAsRead(isRead: boolean) {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
loading = true
@@ -67,7 +67,7 @@
}
item.read = isRead
if ($profile.user) $notifications.inbox += isRead ? -1 : 1
if (profile.data.user) $notifications.inbox += isRead ? -1 : 1
loading = false
}
+1 -1
View File
@@ -64,7 +64,7 @@
{:then data}
{@const conversations = data.private_messages}
{@const previews = conversationPreviews(conversations).filter(
(c) => c.user.id != $profile?.user?.local_user_view.person.id,
(c) => c.user.id != profile.data?.user?.local_user_view.person.id,
)}
<ul
-3
View File
@@ -51,9 +51,6 @@
try {
data.instance = data.instance.trim()
// if (!(await validateInstance(data.instance))) {
// throw new Error('Failed to contact that instance. Is it down?')
// }
const response = await getClient(data.instance).login({
username_or_email: data.username.trim(),
+7 -15
View File
@@ -21,7 +21,7 @@
let form = $state({
instance: '',
username: `${$t('account.guest')} ${$profileData.profiles.filter((p) => p.jwt == undefined).length + 1}`,
username: `${$t('account.guest')} ${profileData.profiles.filter((p) => p.jwt == undefined).length + 1}`,
loading: false,
})
@@ -33,21 +33,13 @@
return
}
profileData.update((pd) => {
// too lazy to make a decent system
const id = Math.floor(Math.random() * 100000)
const newProfile: Profile = {
id: id,
instance: form.instance,
username: form.username,
}
return {
profile: id,
profiles: [...pd.profiles, newProfile],
}
const id = Math.max(...profileData.profiles.map((i) => i.id)) + 1
profileData.profiles.push({
id: id,
instance: form.instance,
username: form.username,
})
profileData.profile = id
toast({ content: $t('toast.addAccount'), type: 'success' })
+2 -2
View File
@@ -18,7 +18,7 @@ export async function load({ url, fetch }) {
const filter: ReportFilter =
(url.searchParams.get('filter') as ReportFilter) || 'all'
const jwt = get(profile)?.jwt
const jwt = profile.data?.jwt
if (!jwt) return { type: type, page: page }
@@ -37,7 +37,7 @@ export async function load({ url, fetch }) {
unresolved_only: type == 'unread',
}
const admin = get(profile)?.user ? isAdmin(get(profile)!.user!) : false
const admin = profile.data?.user ? isAdmin(profile!.user!) : false
const [posts, comments, messages] = await Promise.all([
client.listPostReports({
+1 -1
View File
@@ -26,7 +26,7 @@
let resolving = $state(false)
async function resolve() {
if (!$profile?.jwt || !$profile.user) return
if (!profile.data?.jwt || !profile.data.user) return
resolving = true
try {
+5 -5
View File
@@ -91,7 +91,7 @@
<ObjectAutocomplete
type="instance"
placeholder="Filter by instance"
jwt={$profile?.jwt}
jwt={profile.data?.jwt}
showWhenEmpty={true}
label="Instance"
class="flex-1"
@@ -109,7 +109,7 @@
/>
<ObjectAutocomplete
placeholder="Filter by community"
jwt={$profile?.jwt}
jwt={profile.data?.jwt}
listing_type="All"
showWhenEmpty={true}
label="Community"
@@ -121,7 +121,7 @@
<UserAutocomplete
instance={page.url.searchParams.get('instance') || undefined}
placeholder="Filter by user"
jwt={$profile?.jwt}
jwt={profile.data?.jwt}
listing_type="All"
showWhenEmpty={true}
class="flex-1"
@@ -132,10 +132,10 @@
onselect={(e) =>
searchParam(page.url, 'user', e?.id.toString() ?? '', 'page')}
/>
{#if $profile?.user && isAdmin($profile?.user)}
{#if profile.data?.user && isAdmin(profile.data?.user)}
<UserAutocomplete
placeholder="Filter by moderator"
jwt={$profile?.jwt}
jwt={profile.data?.jwt}
listing_type="All"
showWhenEmpty={true}
class="flex-1"
@@ -73,13 +73,13 @@
{/if}
<TextInput
bind:value={password}
label={$t('form.profile.newPassword')}
label={$t('form.profile.data.newPassword')}
type="password"
required
/>
<TextInput
bind:value={password_verify}
label={$t('form.profile.verifyNewPassword')}
label={$t('form.profile.data.verifyNewPassword')}
type="password"
required
/>
+2 -3
View File
@@ -1,5 +1,4 @@
import { instance } from '$lib/instance.js'
import { getInstance } from '$lib/lemmy.js'
import { profile } from '$lib/auth.svelte.js'
import { error, redirect } from '@sveltejs/kit'
import { get } from 'svelte/store'
@@ -7,7 +6,7 @@ export function load({ params, url }) {
if (Number(params.instance)) {
const split = url.pathname.split('/')
split.splice(2, 0, `${getInstance()?.toLowerCase()}`)
split.splice(2, 0, `${profile.data.instance?.toLowerCase()}`)
const newUrl = new URL(url)
newUrl.pathname = split.join('/')
@@ -114,7 +114,7 @@
onMount(async () => {
if (
!(data.post.post_view.read && settings.markPostsAsRead) &&
$profile?.jwt
profile.data?.jwt
) {
getClient().markPostAsRead({
read: settings.markPostsAsRead,
@@ -237,12 +237,12 @@
<span class="text-primary-900 dark:text-primary-100 font-bold">
{$t('routes.post.remoteView')}
</span>
{#if $profile?.jwt}
{#if profile.data?.jwt}
<Button
class="ml-auto"
onclick={() => {
if ($profile?.jwt) {
fetchOnHome($profile?.jwt)
if (profile.data?.jwt) {
fetchOnHome(profile.data?.jwt)
}
}}
>
@@ -50,7 +50,7 @@
})
</script>
{#if $profile?.jwt}
{#if profile.data?.jwt}
{#if !commenting}
<EndPlaceholder class="">
<Button color="primary" onclick={() => (commenting = true)}>
@@ -89,8 +89,8 @@
}}
locked={(post.post_view.post.locked &&
!(
$profile?.user?.local_user_view.local_user.admin ||
$profile?.user?.moderates
profile.data?.user?.local_user_view.local_user.admin ||
profile.data?.user?.moderates
.map((c) => c.community.id)
.includes(post.community_view.community.id)
)) ||
@@ -106,7 +106,7 @@
{/if}
{/if}
{#if commenting || !$profile.jwt}
{#if commenting || !profile.data.jwt}
<div class="gap-2 flex items-center">
<Select size="md" bind:value={sort} onchange={onupdate}>
<Option icon={Fire} value="Hot">{$t('filter.sort.hot')}</Option>
@@ -35,7 +35,7 @@
let data = $state(pageData)
async function unblockUser(item: PersonBlockView) {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
data.person_blocks.splice(
data.person_blocks.findIndex((i) => i.target.id == item.target.id),
@@ -51,7 +51,7 @@
}
async function unblockCommunity(item: CommunityBlockView) {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
data.community_blocks.splice(
data.community_blocks.findIndex(
@@ -70,7 +70,7 @@
}
async function unblockInstances(item: InstanceBlockView) {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
if (!data.my_user?.instance_blocks) return
data.my_user.instance_blocks.splice(
@@ -19,7 +19,7 @@
url: '/profile/password',
},
{
name: $t('form.profile.2fa.2fa'),
name: $t('form.profile.data.2fa.2fa'),
url: '/profile/password/2fa',
},
{
@@ -50,7 +50,7 @@
>
<Icon src={Key} size="24" />
</Material>
<span class="font-medium text-lg">{$t('form.profile.2fa.2fa')}</span>
<span class="font-medium text-lg">{$t('form.profile.data.2fa.2fa')}</span>
<span class="text-sm">
{data.my_user?.local_user_view.local_user.totp_2fa_enabled
? $t('common.enabled')
@@ -58,7 +58,7 @@
disabled
type="password"
value={totpLink}
label={$t('form.profile.2fa.totp')}
label={$t('form.profile.data.2fa.totp')}
>
{#snippet suffix()}
<button
@@ -73,7 +73,7 @@
</button>
{/snippet}
<span class="font-normal text-xs">
{$t('form.profile.2fa.paste')}
{$t('form.profile.data.2fa.paste')}
</span>
</TextInput>
{/if}
@@ -22,8 +22,8 @@
old_password: oldPassword,
})
if (res?.jwt) {
const { instance, username } = $profile
deleteProfile($profile.id)
const { instance, username } = profile.data
deleteProfile(profile.data.id)
await setUser(res.jwt, instance, username!)
$currentInstance = instance
@@ -47,21 +47,21 @@
<form onsubmit={preventDefault(changePassword)} class="flex flex-col gap-4">
<TextInput
bind:value={oldPassword}
label={$t('form.profile.currentPassword')}
label={$t('form.profile.data.currentPassword')}
type="password"
minlength={10}
required
/>
<TextInput
bind:value={newPassword}
label={$t('form.profile.newPassword')}
label={$t('form.profile.data.newPassword')}
type="password"
minlength={10}
required
/>
<TextInput
bind:value={newPasswordVerify}
label={$t('form.profile.verifyNewPassword')}
label={$t('form.profile.data.verifyNewPassword')}
type="password"
minlength={10}
required
@@ -70,14 +70,9 @@
delete_content: deletion.deleteContent,
})
profileData.update((pd) => {
pd.profiles.splice(
pd.profiles.findIndex((p) => pd.profile == p.id),
1,
)
return pd
})
profileData.profiles.splice(
profileData.profiles.findIndex((p) => profileData.profile == p.id),
)
setUserID(-1)
toast({
@@ -102,7 +97,7 @@
onaction={() => deleteAccount(4)}
>
{#snippet customTitle()}
<span>{$t('form.profile.deleteAccount.label')}</span>
<span>{$t('form.profile.data.deleteAccount.label')}</span>
{/snippet}
<TextInput
label={$t('form.password')}
@@ -110,10 +105,10 @@
bind:value={deletion.password}
/>
<Checkbox bind:checked={deletion.deleteContent}>
{$t('form.profile.deleteAccount.deleteContent')}
{$t('form.profile.data.deleteAccount.deleteContent')}
{#snippet description()}
<span>
{$t('form.profile.deleteAccount.warning')}
{$t('form.profile.data.deleteAccount.warning')}
</span>
{/snippet}
</Checkbox>
@@ -133,10 +128,10 @@
{$t('routes.profile.delete.warning')}
</p>
<Switch bind:checked={deletion.deleteContent}>
{$t('form.profile.deleteAccount.deleteContent')}
{$t('form.profile.data.deleteAccount.deleteContent')}
{#snippet description()}
<span>
{$t('form.profile.deleteAccount.warning')}
{$t('form.profile.data.deleteAccount.warning')}
</span>
{/snippet}
</Switch>
@@ -40,17 +40,25 @@
let bannerImage: FileList | undefined = $state()
async function save() {
if (!formData || !$profile?.jwt) return
if (!formData || !profile.data?.jwt) return
loading = true
try {
let pfp = profileImage
? await uploadImage(profileImage[0], $profile.instance, $profile.jwt)
? await uploadImage(
profileImage[0],
profile.data.instance,
profile.data.jwt,
)
: undefined
let banner = bannerImage
? await uploadImage(bannerImage[0], $profile.instance, $profile.jwt)
? await uploadImage(
bannerImage[0],
profile.data.instance,
profile.data.jwt,
)
: undefined
const res = await getClient().saveUserSettings({
@@ -81,45 +89,54 @@
{/if}
{@render children?.()}
{#if data.my_user?.local_user_view?.local_user && formData}
<TextInput label={$t('form.profile.email')} bind:value={formData.email} />
<TextInput
label={$t('form.profile.displayName')}
label={$t('form.profile.data.email')}
bind:value={formData.email}
/>
<TextInput
label={$t('form.profile.data.displayName')}
bind:value={formData.display_name}
placeholder="Optional"
/>
<MarkdownEditor
images={false}
bind:value={() => formData.bio ?? '', (v) => (formData.bio = v)}
label={$t('form.profile.bio')}
label={$t('form.profile.data.bio')}
previewButton
/>
<div class="flex gap-2 items-center *:flex-1">
<ImageInput label={$t('form.profile.avatar')} bind:files={profileImage} />
<ImageInput label={$t('form.profile.banner')} bind:files={bannerImage} />
<ImageInput
label={$t('form.profile.data.avatar')}
bind:files={profileImage}
/>
<ImageInput
label={$t('form.profile.data.banner')}
bind:files={bannerImage}
/>
</div>
<TextInput
label={$t('form.profile.matrix')}
label={$t('form.profile.data.matrix')}
bind:value={formData.matrix_user_id}
placeholder="@user:example.com"
/>
<Switch bind:checked={formData.show_nsfw}>
{$t('form.profile.showNSFW')}
{$t('form.profile.data.showNSFW')}
</Switch>
<Switch bind:checked={formData.show_scores}>
{$t('form.profile.scores')}
{$t('form.profile.data.scores')}
</Switch>
<Switch bind:checked={formData.bot_account}>
{$t('form.profile.bot')}
{$t('form.profile.data.bot')}
</Switch>
<Switch bind:checked={formData.show_bot_accounts}>
{$t('form.profile.showBots')}
{$t('form.profile.data.showBots')}
</Switch>
<Switch bind:checked={formData.show_read_posts}>
{$t('form.profile.showRead')}
{$t('form.profile.data.showRead')}
</Switch>
<div class="space-y-1">
<SectionTitle>{$t('form.profile.languages.title')}</SectionTitle>
<p>{$t('form.profile.languages.description')}</p>
<SectionTitle>{$t('form.profile.data.languages.title')}</SectionTitle>
<p>{$t('form.profile.data.languages.description')}</p>
<Material rounding="xl" color="uniform" class="dark:bg-zinc-950">
{#if $site && formData.discussion_languages}
<div class="flex gap-2 flex-wrap flex-row">
+2 -2
View File
@@ -9,8 +9,8 @@ export let ssr = false
export async function load({ params, url, fetch }) {
const my_user =
// get(profile)?.user ??
(await client({ auth: get(profile)?.jwt, func: fetch }).getSite()).my_user
// profile.data?.user ??
(await client({ auth: profile.data?.jwt, func: fetch }).getSite()).my_user
return {
my_user: my_user,
+1 -1
View File
@@ -4,7 +4,7 @@ import { error } from '@sveltejs/kit'
import { get } from 'svelte/store'
export async function load({ fetch, url }) {
const { jwt } = get(profile)
const { jwt } = profile.data
let page = Number(url.searchParams.get('page')) || 1
+1 -1
View File
@@ -14,7 +14,7 @@
let loading = $state(false)
async function deleteImage(image: LocalImage) {
if (!$profile?.jwt) return
if (!profile.data?.jwt) return
try {
loading = true
+1 -1
View File
@@ -18,7 +18,7 @@ function getSavedItemPublished(item: PostView | CommentView) {
}
export async function load({ url, fetch }) {
if (!get(profile)) return { posts: [], page: 0 }
if (!profile) return { posts: [], page: 0 }
const page = Number(url.searchParams.get('page')) || 1
const type: 'comments' | 'posts' | 'all' =
(url.searchParams.get('type') as 'comments' | 'posts' | 'all') || 'all'
+1 -1
View File
@@ -136,7 +136,7 @@
<div transition:slide={{ axis: 'y', easing: expoOut }} class="max-w-sm">
<ObjectAutocomplete
label={$t('nav.create.community')}
jwt={$profile?.jwt}
jwt={profile.data?.jwt}
listing_type={'All'}
showWhenEmpty={true}
onselect={(c) =>
+1 -1
View File
@@ -57,7 +57,7 @@ export async function load({ url, fetch }) {
query: query,
results: everything,
streamed: {
object: get(profile)?.jwt
object: profile.data?.jwt
? getClient(undefined, fetch).resolveObject({
q: query,
})
+1 -1
View File
@@ -197,7 +197,7 @@
class="flex flex-col *:py-2 divide-y divide-slate-200 dark:divide-zinc-800"
style="scroll-behavior: smooth;"
>
{#if $profile?.jwt}
{#if profile.data?.jwt}
<Section open={false} id="account" title={$t('settings.account.title')}>
<div>
<Button
+1 -1
View File
@@ -201,7 +201,7 @@
</div>
</div>
{/if}
<Checkbox bind:checked={nsfw}>{$t('form.profile.showNSFW')}</Checkbox>
<Checkbox bind:checked={nsfw}>{$t('form.profile.data.showNSFW')}</Checkbox>
<input type="dn" name="honeypot" bind:value={honeypot} class="hidden" />
<Button
submit
+8 -7
View File
@@ -51,11 +51,12 @@
let blocking = false
async function blockUser(block: number) {
if (!$profile?.user || !$profile?.jwt) throw new Error('Unauthenticated')
if (!profile.data?.user || !profile.data?.jwt)
throw new Error('Unauthenticated')
blocking = true
try {
const blocked = isBlocked($profile.user, block)
const blocked = isBlocked(profile.data.user, block)
await getClient().blockPerson({
block: !blocked,
@@ -63,10 +64,10 @@
})
if (blocked) {
const index = $profile.user.person_blocks
const index = profile.data.user.person_blocks
.map((p) => p.target.id)
.indexOf(block)
$profile.user.person_blocks.splice(index, 1)
profile.data.user.person_blocks.splice(index, 1)
}
toast({
@@ -209,7 +210,7 @@
</Expandable>
{/if}
{#snippet actions()}
{#if $profile?.user && $profile.jwt && data.person_view.person.id != $profile.user.local_user_view.person.id}
{#if profile.data?.user && profile.data.jwt && data.person_view.person.id != profile.data.user.local_user_view.person.id}
<div class="flex items-center gap-2 w-full">
<Button
size="square-md"
@@ -234,7 +235,7 @@
{/snippet}
</Button>
{/if}
{#if isAdmin($profile?.user)}
{#if isAdmin(profile.data?.user)}
<Menu class="ml-auto" placement="bottom-end">
{#snippet target()}
<Button size="square-md">
@@ -280,7 +281,7 @@
{#snippet prefix()}
<Icon mini size="16" src={NoSymbol} />
{/snippet}
{isBlocked($profile.user, data.person_view.person.id)
{isBlocked(profile.data.user, data.person_view.person.id)
? 'Unblock'
: 'Block'}
</MenuButton>
+2 -5
View File
@@ -6,10 +6,7 @@
let link = $state('')
let photonified
run(() => {
photonified = photonify(link)
})
let photonified = $derived(photonify(link))
</script>
<h1 class="font-bold text-2xl">Photonify links</h1>
@@ -21,5 +18,5 @@
bind:value={link}
placeholder="https://lemmy.world/post/1"
/>
<TextInput label="Output" bind:value={photonified} />
<TextInput label="Output" value={photonified} />
</div>