feat: add account switcher

This commit is contained in:
Xyphyn committed 2023-08-01 12:20:37 -07:00
1 parent fc1afecfdd
commit 54ab6fdc82
6 files changed
+169 -61

No files matched your search

+39 -15
View File
@@ -1,5 +1,5 @@
import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js' import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js'
import { DEFAULT_INSTANCE_URL, getClient } from '$lib/lemmy.js' import { DEFAULT_INSTANCE_URL, getClient, instance } from '$lib/lemmy.js'
import type { MyUserInfo } from 'lemmy-js-client' import type { MyUserInfo } from 'lemmy-js-client'
import { get, writable } from 'svelte/store' import { get, writable } from 'svelte/store'
@@ -19,6 +19,7 @@ interface Profile {
instance: string instance: string
jwt?: string jwt?: string
user?: PersonData user?: PersonData
username?: string
} }
/** /**
@@ -45,6 +46,9 @@ profileData.subscribe((pd) => {
export const profile = writable<Profile | undefined>(getProfile()) export const profile = writable<Profile | undefined>(getProfile())
profile.subscribe(async (p) => { profile.subscribe(async (p) => {
if (p?.instance) {
instance.set(p.instance)
}
if (!p || !p.jwt) { if (!p || !p.jwt) {
profileData.update((pd) => ({ ...pd, profile: -1 })) profileData.update((pd) => ({ ...pd, profile: -1 }))
return return
@@ -54,13 +58,13 @@ profile.subscribe(async (p) => {
// fetch the user because p.user is undefined // fetch the user because p.user is undefined
const user = await userFromJwt(p.jwt, p.instance) const user = await userFromJwt(p.jwt, p.instance)
p = { profile.update(() => ({
...p, ...p,
user: user, user: user,
} }))
}) })
export async function setUser(jwt: string, instance: string) { export async function setUser(jwt: string, instance: string, username: string) {
try { try {
new URL(`https://${instance}`) new URL(`https://${instance}`)
} catch (err) { } catch (err) {
@@ -83,6 +87,7 @@ export async function setUser(jwt: string, instance: string) {
id: id, id: id,
instance: instance, instance: instance,
jwt: jwt, jwt: jwt,
username: username,
} }
profile.set({ profile.set({
@@ -120,32 +125,51 @@ const userToPersonData = (user: MyUserInfo): PersonData => ({
function getProfile() { function getProfile() {
const id = get(profileData).profile const id = get(profileData).profile
console.log('id is', id)
// returns something that isn't -1
if (id == -1) { if (id == -1) {
console.log('returning, since ID is', id)
// still logs :/
return return
} }
console.log('fetching user of id', id)
const pd = get(profileData) const pd = get(profileData)
console.log('pd', pd)
return pd.profiles.find((p) => p.id == id) return pd.profiles.find((p) => p.id == id)
} }
export function resetProfile() {
profile.set({
id: -1,
instance: DEFAULT_INSTANCE_URL,
})
profileData.update((p) => ({ ...p, profile: -1 }))
}
export function deleteProfile(id: number) {
const pd = get(profileData)
const index = pd.profiles.findIndex((p) => p.id == id)
if (index <= -1) return
pd.profiles.splice(index, 1)
profileData.update((p) => ({
...p,
profiles: pd.profiles,
}))
if (id == get(profile)?.id) {
resetProfile()
}
}
export function setUserID(id: number) { export function setUserID(id: number) {
const pd = get(profileData) const pd = get(profileData)
console.log('pd', pd) if (id == -1) {
resetProfile()
return
}
const prof = pd.profiles.find((p) => p.id == id) const prof = pd.profiles.find((p) => p.id == id)
profile.set(prof) profile.set(prof)
profileData.update((p) => ({ ...p, profile: id })) profileData.update((p) => ({ ...p, profile: id }))
console.log('new', pd)
return prof return prof
} }
+23 -45
View File
@@ -153,20 +153,15 @@
slot="button" slot="button"
on:click={toggleOpen} on:click={toggleOpen}
> >
{#if $user === undefined} {#if $profile?.user}
<div class="w-full h-full grid place-items-center">
<Spinner width={20} />
</div>
{/if}
{#if $user}
<div class="w-8 h-8 aspect-square object-cover rounded-full"> <div class="w-8 h-8 aspect-square object-cover rounded-full">
<Avatar <Avatar
url={$user.local_user_view.person.avatar} url={$profile.user.local_user_view.person.avatar}
width={32} width={32}
alt={$user.local_user_view.person.name} alt={$profile.user.local_user_view.person.name}
/> />
</div> </div>
{#if $user.unreads > 0} {#if $profile.user.unreads > 0}
<div <div
class="rounded-full w-2 h-2 bg-red-500 absolute top-0 left-0 z-10" class="rounded-full w-2 h-2 bg-red-500 absolute top-0 left-0 z-10"
/> />
@@ -174,18 +169,19 @@
{/if} {/if}
</button> </button>
<li class="text-xs opacity-80 text-left mx-4 my-1 py-1"> <li class="text-xs opacity-80 text-left mx-4 my-1 py-1">
{$user ? $user.local_user_view.person.name : 'Profile'} {$profile?.user ? $profile.user.local_user_view.person.name : 'Profile'}
</li> </li>
{#if $profile} {#if $profile?.user}
<!-- <MenuButton <MenuButton
link link
href="/u/{$user.local_user_view.person.name}@{$authData.instance}" href="/u/{$profile.user.local_user_view.person
.name}@{$profile.instance}"
> >
<Icon src={UserCircle} mini width={16} /> Profile <Icon src={UserCircle} mini width={16} /> Profile
</MenuButton> </MenuButton>
<MenuButton link href="/inbox"> <MenuButton link href="/inbox">
<div class="relative"> <div class="relative">
{#if $user.unreads > 0} {#if $profile.user.unreads > 0}
<div <div
class="rounded-full w-2 h-2 bg-red-500 absolute -top-1 -left-1" class="rounded-full w-2 h-2 bg-red-500 absolute -top-1 -left-1"
/> />
@@ -196,39 +192,21 @@
<MenuButton link href="/saved"> <MenuButton link href="/saved">
<Icon src={Bookmark} mini width={16} /> Saved <Icon src={Bookmark} mini width={16} /> Saved
</MenuButton> </MenuButton>
<MenuButton
on:click={() => {
localStorage.removeItem('user')
user.set(undefined)
authData.set(undefined)
}}
color="dangerSecondary"
>
<Icon src={ArrowRightOnRectangle} mini width={16} />Log out
</MenuButton> -->
{/if} {/if}
{#if !$profile?.user} {#if !$profile?.user && $profileData.profiles.length == 0}
{#if $profileData.profiles.length == 0} <MenuButton link href="/login">
<MenuButton link href="/login"> <Icon src={ArrowLeftOnRectangle} mini width={16} />
<Icon src={ArrowLeftOnRectangle} mini width={16} /> Log in
Log in </MenuButton>
</MenuButton>
{:else}
<MenuButton
on:click={() => {
const acc = Number(prompt('user id'))
setUserID(acc)
}}
>
<Icon src={ArrowLeftOnRectangle} mini width={16} />
change account
</MenuButton>
{/if}
{:else} {:else}
<MenuButton on:click={() => console.log($profile)}> <MenuButton link href="/accounts">
<Icon src={Beaker} mini width={16} /> <Icon src={ArrowLeftOnRectangle} mini width={16} />
Log user Switch account
<span
class="text-xs font-bold bg-slate-100 dark:bg-zinc-700 px-2 py-0.5 rounded-md ml-auto"
>
{$profileData.profiles.length}
</span>
</MenuButton> </MenuButton>
{/if} {/if}
<hr class="dark:opacity-10 w-[90%] my-2 mx-auto" /> <hr class="dark:opacity-10 w-[90%] my-2 mx-auto" />
@@ -0,0 +1,15 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte'
type T = $$Generic
const dispatcher = createEventDispatcher<{ action: any }>()
function action(detail: any) {
dispatcher('action', detail)
}
</script>
<ul class="divide-y divide-slate-200 dark:divide-zinc-900 flex flex-col">
<slot {action} />
</ul>
@@ -0,0 +1,3 @@
<div class="p-2 flex flex-row">
<slot />
</div>
+88
View File
@@ -0,0 +1,88 @@
<script lang="ts">
import {
profileData,
setUserID,
profile as currentProfile,
resetProfile,
deleteProfile,
} from '$lib/auth.js'
import Button from '$lib/components/input/Button.svelte'
import EditableList from '$lib/components/ui/list/EditableList.svelte'
import { ArrowLeftOnRectangle, Icon, Plus, Trash } from 'svelte-hero-icons'
import { flip } from 'svelte/animate'
</script>
{#if $profileData.profiles.length == 0}
<div class="h-full flex items-center justify-center">
<div
class="text-slate-600 dark:text-zinc-400 flex flex-col justify-center items-center py-8 gap-4"
>
<div class="flex flex-col items-center">
<Icon src={ArrowLeftOnRectangle} size="48" solid />
<h1 class="font-bold text-3xl">No accounts</h1>
</div>
<Button href="/login" size="lg">
<Icon slot="icon" src={ArrowLeftOnRectangle} size="16" mini />
Log in
</Button>
</div>
</div>
{:else}
<div class="flex flex-col h-full gap-4">
<div class="flex flex-row justify-between">
<h1 class="text-2xl font-bold">Accounts</h1>
<Button
on:click={() => {
$profileData.profiles = []
resetProfile()
}}
>
Delete all
</Button>
</div>
<EditableList
on:action={(id) => {
deleteProfile(id.detail)
}}
let:action
>
{#each $profileData.profiles as profile (profile.id)}
<div
class="flex flex-row gap-4 items-center py-4"
animate:flip={{ duration: 250 }}
>
<div class="flex flex-col">
<span class="font-bold">{profile.username}</span>
<span class="text-sm text-slate-600 dark:text-zinc-400">
{profile.instance}
</span>
</div>
<div class="ml-auto" />
<Button
on:click={() => {
if (profile.id == $currentProfile?.id) {
setUserID(-1)
} else {
setUserID(profile.id)
}
}}
color={profile.id == $currentProfile?.id ? 'primary' : 'secondary'}
>
{profile.id == $currentProfile?.id ? 'Current' : 'Switch to'}
</Button>
<Button
on:click={() => action(profile.id)}
class="!p-2"
color="danger"
>
<Icon slot="icon" src={Trash} size="16" mini />
</Button>
</div>
{/each}
</EditableList>
<Button href="/login" size="lg" class="mt-auto">
<Icon slot="icon" src={Plus} size="16" mini />
Add more
</Button>
</div>
{/if}
+1 -1
View File
@@ -41,7 +41,7 @@
}) })
if (response?.jwt) { if (response?.jwt) {
setUser(response.jwt, data.instance) setUser(response.jwt, data.instance, data.username)
toast({ content: 'Successfully logged in.', type: ToastType.success }) toast({ content: 'Successfully logged in.', type: ToastType.success })
goto('/') goto('/')