Compare commits

...

15 commits

Author SHA1 Message Date
三咲智子
bdc045349c
Merge branch 'main' into feat/guest 2023-01-07 03:39:21 +08:00
三咲智子
9bb4dfcfaa
fix: type 2023-01-07 03:33:45 +08:00
三咲智子
49c4be3b67
Merge branch 'main' into feat/guest 2023-01-07 03:32:31 +08:00
三咲智子
32feeded7a
chore: simplify 2023-01-04 23:41:32 +08:00
三咲智子
53dcd8b28f
fix: resolve conflicts 2023-01-04 23:41:32 +08:00
三咲智子
66295199b4
refactor: rename 2023-01-04 23:41:32 +08:00
三咲智子
8af8abfc9f
refactor: remove optional chainning & non-null assertion 2023-01-04 23:41:32 +08:00
三咲智子
4ed0b339e0
fix: pinned 2023-01-04 23:41:32 +08:00
三咲智子
b980d519d5
fix: router 2023-01-04 23:41:32 +08:00
三咲智子
313cafa23c
feat: wip 2023-01-04 23:41:32 +08:00
三咲智子
f7df0e54f5
fix: settings 2023-01-04 23:41:32 +08:00
三咲智子
bfd5c3a446
feat: wip 2023-01-04 23:41:32 +08:00
三咲智子
aecfcb61bf
refactor: extract guest id 2023-01-04 23:41:32 +08:00
三咲智子
f2d125ed4e
feat: wip 2023-01-04 23:41:32 +08:00
三咲智子
1816530f84
wip 2023-01-04 23:41:32 +08:00
45 changed files with 300 additions and 224 deletions

View file

@ -3,7 +3,7 @@ setupPageHeader()
provideGlobalCommands() provideGlobalCommands()
// We want to trigger rerendering the page when account changes // We want to trigger rerendering the page when account changes
const key = computed(() => `${currentUser.value?.server ?? currentServer.value}:${currentUser.value?.account.id || ''}`) const key = computed(() => getUniqueUserId(currentUser.value))
</script> </script>
<template> <template>

View file

@ -7,8 +7,8 @@ const { account, command, ...props } = defineProps<{
command?: boolean command?: boolean
}>() }>()
const isSelf = $computed(() => currentUser.value?.account.id === account.id) const isSelf = $computed(() => checkAuth(currentUser.value) && currentUser.value.account.id === account.id)
const enable = $computed(() => !isSelf && currentUser.value) const enable = $computed(() => !isSelf && !isGuest.value)
const relationship = $computed(() => props.relationship || useRelationship(account).value) const relationship = $computed(() => props.relationship || useRelationship(account).value)
const masto = useMasto() const masto = useMasto()

View file

@ -0,0 +1,18 @@
<script setup lang="ts">
import type { UserLogin } from '~/types'
defineProps<{
user: UserLogin
}>()
</script>
<template>
<div flex="~ gap3" items-center>
<div bg="gray/40" rounded-full w-54px h-54px flex shrink-0 items-center justify-center text-5>
G
</div>
<div>
Guest from <span font-bold>{{ user.server }}</span>
</div>
</div>
</template>

View file

@ -59,7 +59,7 @@ watchEffect(() => {
iconFields.value = icons iconFields.value = icons
}) })
const isSelf = $computed(() => currentUser.value?.account.id === account.id) const isSelf = $computed(() => checkAuth(currentUser.value) && currentUser.value.account.id === account.id)
</script> </script>
<template> <template>

View file

@ -7,7 +7,7 @@ const { account } = defineProps<{
}>() }>()
let relationship = $(useRelationship(account)) let relationship = $(useRelationship(account))
const isSelf = $computed(() => currentUser.value?.account.id === account.id) const isSelf = $computed(() => checkAuth(currentUser.value) && currentUser.value.account.id === account.id)
const masto = useMasto() const masto = useMasto()
const toggleMute = async () => { const toggleMute = async () => {
@ -53,7 +53,7 @@ const toggleBlockDomain = async () => {
/> />
</NuxtLink> </NuxtLink>
<template v-if="currentUser"> <template v-if="!isGuest">
<template v-if="!isSelf"> <template v-if="!isSelf">
<CommonDropdownItem <CommonDropdownItem
:text="$t('menu.mention_account', [`@${account.acct}`])" :text="$t('menu.mention_account', [`@${account.acct}`])"

View file

@ -39,8 +39,8 @@ onMastoInit(async () => {
// Optimize rendering for the common case of being logged in, only show visual feedback for disabled user-only items // Optimize rendering for the common case of being logged in, only show visual feedback for disabled user-only items
// when we know there is no user. // when we know there is no user.
const noUserDisable = computed(() => !isMastoInitialised.value || (props.userOnly && !currentUser.value)) const noUserDisable = computed(() => !isMastoInitialised.value || (props.userOnly && isGuest.value))
const noUserVisual = computed(() => isMastoInitialised.value && props.userOnly && !currentUser.value) const noUserVisual = computed(() => isMastoInitialised.value && props.userOnly && isGuest.value)
</script> </script>
<template> <template>

View file

@ -2,6 +2,7 @@
<VDropdown v-if="isMastoInitialised && currentUser" sm:hidden> <VDropdown v-if="isMastoInitialised && currentUser" sm:hidden>
<div style="-webkit-touch-callout: none;"> <div style="-webkit-touch-callout: none;">
<AccountAvatar <AccountAvatar
v-if="!currentUser.guest"
ref="avatar" ref="avatar"
:account="currentUser.account" :account="currentUser.account"
h-8 h-8
@ -9,6 +10,9 @@
:draggable="false" :draggable="false"
square square
/> />
<div v-else bg="gray/40" rounded-full w-8 h-8 flex items-center justify-center text-5>
G
</div>
</div> </div>
<template #popper="{ hide }"> <template #popper="{ hide }">

View file

@ -11,7 +11,7 @@ defineSlots<{
error: {} error: {}
}>() }>()
const isLegacyAccount = computed(() => !currentUser.value?.vapidKey) const isLegacyAccount = computed(() => !currentUser.value.vapidKey)
</script> </script>
<template> <template>

View file

@ -25,7 +25,7 @@ let subscribeError = $ref<string>('')
let showSubscribeError = $ref<boolean>(false) let showSubscribeError = $ref<boolean>(false)
const hideNotification = () => { const hideNotification = () => {
const key = currentUser.value?.account?.acct const key = currentUser.value.account?.acct
if (key) if (key)
hiddenNotification.value[key] = true hiddenNotification.value[key] = true
} }
@ -36,7 +36,7 @@ const showWarning = $computed(() => {
return isSupported return isSupported
&& (!isSubscribed.value || !notificationPermission.value || notificationPermission.value === 'prompt') && (!isSubscribed.value || !notificationPermission.value || notificationPermission.value === 'prompt')
&& !(hiddenNotification.value[currentUser.value?.account?.acct ?? ''] === true) && !(hiddenNotification.value[currentUser.value.account?.acct ?? ''] === true)
}) })
const saveSettings = async () => { const saveSettings = async () => {

View file

@ -1,6 +1,6 @@
<script setup> <script setup>
const disabled = computed(() => !isMastoInitialised.value || !currentUser.value) const disabled = computed(() => !isMastoInitialised.value || isGuest.value)
const disabledVisual = computed(() => isMastoInitialised.value && !currentUser.value) const disabledVisual = computed(() => isMastoInitialised.value && isGuest.value)
</script> </script>
<template> <template>

View file

@ -184,7 +184,7 @@ defineExpose({
</script> </script>
<template> <template>
<div v-if="isMastoInitialised && currentUser" flex="~ col gap-4" py3 px2 sm:px4> <div v-if="isMastoInitialised && currentUser.account && !isGuest" flex="~ col gap-4" py3 px2 sm:px4>
<template v-if="draft.editingStatus"> <template v-if="draft.editingStatus">
<div flex="~ col gap-1"> <div flex="~ col gap-1">
<div id="state-editing" text-secondary self-center> <div id="state-editing" text-secondary self-center>

View file

@ -23,7 +23,7 @@ const clipboard = useClipboard()
const router = useRouter() const router = useRouter()
const route = useRoute() const route = useRoute()
const isAuthor = $computed(() => status.account.id === currentUser.value?.account.id) const isAuthor = $computed(() => checkAuth(currentUser.value) && status.account.id === currentUser.value.account.id)
const { const {
toggle: _toggleTranslation, toggle: _toggleTranslation,
@ -178,7 +178,7 @@ async function editStatus() {
/> />
<CommonDropdownItem <CommonDropdownItem
v-if="currentUser && (status.account.id === currentUser.account.id || status.mentions.some(m => m.id === currentUser!.account.id))" v-if="!isGuest && (status.account.id === currentUser!.account!.id || status.mentions.some(m => m.id === currentUser!.account!.id))"
:text="status.muted ? $t('menu.unmute_conversation') : $t('menu.mute_conversation')" :text="status.muted ? $t('menu.unmute_conversation') : $t('menu.mute_conversation')"
:icon="status.muted ? 'i-ri:eye-line' : 'i-ri:eye-off-line'" :icon="status.muted ? 'i-ri:eye-line' : 'i-ri:eye-off-line'"
:command="command" :command="command"

View file

@ -6,7 +6,7 @@ const { account, status } = defineProps<{
const originalUrl = computed(() => { const originalUrl = computed(() => {
const [handle, _server] = account.split('@') const [handle, _server] = account.split('@')
const server = _server || currentUser.value?.server const server = _server || currentUser.value.server
if (!server) if (!server)
return null return null

View file

@ -22,7 +22,11 @@ const account = isSelf ? computed(() => status.account) : useAccountById(status.
<template v-if="account"> <template v-if="account">
<div i-ri:reply-fill :class="collapsed ? '' : 'scale-x-[-1]'" text-secondary-light /> <div i-ri:reply-fill :class="collapsed ? '' : 'scale-x-[-1]'" text-secondary-light />
<template v-if="!collapsed"> <template v-if="!collapsed">
<AccountAvatar v-if="isSelf || simplified || status.inReplyToAccountId === currentUser?.account.id" :account="account" :link="false" w-5 h-5 mx-0.5 /> <AccountAvatar
v-if="isSelf || simplified
|| (checkAuth(currentUser) && status.inReplyToAccountId === currentUser?.account.id)"
:account="account" :link="false" w-5 h-5 mx-0.5
/>
<AccountInlineInfo v-else :account="account" :link="false" mx-0.5 /> <AccountInlineInfo v-else :account="account" :link="false" mx-0.5 />
</template> </template>
</template> </template>

View file

@ -16,7 +16,7 @@ const { formatNumber } = useHumanReadableNumber()
const virtualScroller = $(useFeatureFlag('experimentalVirtualScroll')) const virtualScroller = $(useFeatureFlag('experimentalVirtualScroll'))
const showOriginSite = $computed(() => const showOriginSite = $computed(() =>
account && account.id !== currentUser.value?.account.id && getServerName(account) !== currentServer.value, account && account.id !== currentUser.value?.account?.id && getServerName(account) !== currentServer.value,
) )
</script> </script>

View file

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
const paginator = useMasto().accounts.iterateStatuses(currentUser.value!.account.id, { pinned: true }) const paginator = useMasto().accounts.iterateStatuses(currentUser.value.account!.id, { pinned: true })
</script> </script>
<template> <template>

View file

@ -1,8 +1,10 @@
<template> <template>
<VDropdown :distance="0" placement="top-start"> <VDropdown :distance="0" placement="top-start">
<button btn-action-icon :aria-label="$t('action.switch_account')"> <button btn-action-icon :aria-label="$t('action.switch_account')">
<div :class="{ 'hidden xl:block': currentUser }" i-ri:more-2-line /> <div :class="{ 'hidden xl:block': !isGuest }" i-ri:more-2-line />
<AccountAvatar v-if="currentUser" xl:hidden :account="currentUser.account" w-9 h-9 square /> <AccountAvatar v-if="checkAuth(currentUser)" xl:hidden :account="currentUser.account" w-9 h-9 square />
<!-- TODO -->
<span v-else>TODO: Guest</span>
</button> </button>
<template #popper="{ hide }"> <template #popper="{ hide }">
<UserSwitcher @click="hide" /> <UserSwitcher @click="hide" />

View file

@ -1,16 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import type { UserLogin } from '~/types'
const all = useUsers() const all = useUsers()
const router = useRouter()
const masto = useMasto() const masto = useMasto()
const switchUser = (user: UserLogin) => {
if (user.account.id === currentUser.value?.account.id)
router.push(getAccountRoute(user.account))
else
masto.loginTo(user)
}
</script> </script>
<template> <template>
@ -21,11 +11,14 @@ const switchUser = (user: UserLogin) => {
flex rounded flex rounded
cursor-pointer cursor-pointer
aria-label="Switch user" aria-label="Switch user"
:class="user.account.id === currentUser?.account.id ? '' : 'op25 grayscale'" :class="user.account?.id === currentUser?.account?.id ? '' : 'op25 grayscale'"
hover="filter-none op100" hover="filter-none op100"
@click="switchUser(user)" @click="switchUser(user, masto)"
> >
<AccountAvatar w-13 h-13 :account="user.account" square /> <AccountAvatar v-if="checkAuth(user)" w-13 h-13 :account="user.account" square />
<div v-else bg="gray/40" rounded-full w-13 h-13 flex shrink-0 items-center justify-center text-5>
G
</div>
</button> </button>
</template> </template>
</div> </div>

View file

@ -1,7 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import Fuse from 'fuse.js' import Fuse from 'fuse.js'
import { $fetch } from 'ofetch' import { $fetch } from 'ofetch'
import { DEFAULT_SERVER } from '~/constants'
const masto = useMasto()
const input = $ref<HTMLInputElement>() const input = $ref<HTMLInputElement>()
let server = $ref<string>('') let server = $ref<string>('')
@ -26,7 +27,7 @@ async function oauth() {
server = server.split('/')[0] server = server.split('/')[0]
try { try {
location.href = await $fetch<string>(`/api/${server || DEFAULT_SERVER}/login`, { location.href = await $fetch<string>(`/api/${server}/login`, {
method: 'POST', method: 'POST',
body: { body: {
origin: location.origin, origin: location.origin,
@ -46,6 +47,11 @@ async function oauth() {
} }
} }
async function explore() {
await masto.loginTo({ server, guest: true })
isSigninDialogOpen.value = false
}
async function handleInput() { async function handleInput() {
if (server.startsWith('https://')) if (server.startsWith('https://'))
server = server.replace('https://', '') server = server.replace('https://', '')
@ -180,9 +186,19 @@ onClickOutside($$(input), () => {
</i18n-t> </i18n-t>
</span> </span>
</div> </div>
<button flex="~ row" gap-x-2 items-center btn-solid mt2 :disabled="!server || busy"> <div flex="~ gap2" mt2 items-center>
<button
type="button"
flex="~ row" gap-x-2 items-center btn-outline text-sm px2 py1 h-fit :disabled="!server || busy"
@click="explore"
>
<span aria-hidden="true" inline-block :class="busy ? 'i-ri:loader-2-fill animate animate-spin' : 'i-ri:user-4-line'" />
{{ $t('action.explore_as_a_guest') }}
</button>
<button flex="~ row" gap-x-2 items-center btn-solid :disabled="!server || busy">
<span aria-hidden="true" inline-block :class="busy ? 'i-ri:loader-2-fill animate animate-spin' : 'i-ri:login-circle-line'" class="rtl-flip" /> <span aria-hidden="true" inline-block :class="busy ? 'i-ri:loader-2-fill animate animate-spin' : 'i-ri:login-circle-line'" class="rtl-flip" />
{{ $t('action.sign_in') }} {{ $t('action.sign_in') }}
</button> </button>
</div>
</form> </form>
</template> </template>

View file

@ -1,6 +1,4 @@
<script setup lang="ts"> <script setup lang="ts">
import type { UserLogin } from '~/types'
const emit = defineEmits<{ const emit = defineEmits<{
(event: 'click'): void (event: 'click'): void
}>() }>()
@ -8,20 +6,10 @@ const emit = defineEmits<{
const all = useUsers() const all = useUsers()
const sorted = computed(() => { const sorted = computed(() => {
return [ return all.value.sort((a, b) => isSameUser(a, currentUser.value) ? -1 : isSameUser(b, currentUser.value) ? 1 : 0)
currentUser.value!,
...all.value.filter(account => account.token !== currentUser.value?.token),
].filter(Boolean)
}) })
const router = useRouter()
const masto = useMasto() const masto = useMasto()
const switchUser = (user: UserLogin) => {
if (user.account.id === currentUser.value?.account.id)
router.push(getAccountRoute(user.account))
else
masto.loginTo(user)
}
</script> </script>
<template> <template>
@ -31,11 +19,12 @@ const switchUser = (user: UserLogin) => {
flex rounded px4 py3 text-left flex rounded px4 py3 text-left
hover:bg-active cursor-pointer transition-100 hover:bg-active cursor-pointer transition-100
aria-label="Switch user" aria-label="Switch user"
@click="switchUser(user)" @click="switchUser(user, masto)"
> >
<AccountInfo :account="user.account" :hover-card="false" square /> <AccountInfo v-if="checkAuth(user)" :account="user.account" :hover-card="false" square />
<AccountGuest v-else :user="user" />
<div flex-auto /> <div flex-auto />
<div v-if="user.token === currentUser?.token" i-ri:check-line text-primary mya text-2xl /> <div v-if="isSameUser(user, currentUser)" i-ri:check-line text-primary mya text-2xl />
</button> </button>
</template> </template>
<div border="t base" pt2> <div border="t base" pt2>
@ -45,8 +34,8 @@ const switchUser = (user: UserLogin) => {
@click="openSigninDialog" @click="openSigninDialog"
/> />
<CommonDropdownItem <CommonDropdownItem
v-if="isMastoInitialised && currentUser" v-if="isMastoInitialised && canSignOut"
:text="$t('user.sign_out_account', [getFullHandle(currentUser.account)])" :text="$t('user.sign_out_account', [getFullHandle(currentUser)])"
icon="i-ri:logout-box-line rtl-flip" icon="i-ri:logout-box-line rtl-flip"
@click="signout" @click="signout"
/> />

View file

@ -330,9 +330,9 @@ export const provideGlobalCommands = () => {
parent: 'account-switch', parent: 'account-switch',
scope: 'Switch account', scope: 'Switch account',
visible: () => user.account.id !== currentUser.value?.account.id, visible: () => !isSameUser(user, currentUser.value),
name: () => t('command.switch_account', [getFullHandle(user.account)]), name: () => t('command.switch_account', [user.guest ? `guest from ${user.server}` : getFullHandle(user)]),
icon: 'i-ri:user-shared-line', icon: 'i-ri:user-shared-line',
onActivate() { onActivate() {
@ -342,9 +342,8 @@ export const provideGlobalCommands = () => {
useCommand({ useCommand({
scope: 'Account', scope: 'Account',
visible: () => currentUser.value, visible: () => canSignOut.value,
name: () => t('user.sign_out_account', [getFullHandle(currentUser.value)]),
name: () => t('user.sign_out_account', [getFullHandle(currentUser.value!.account)]),
icon: 'i-ri:logout-box-line', icon: 'i-ri:logout-box-line',
onActivate() { onActivate() {

View file

@ -1,4 +1,5 @@
import type { Account } from 'masto' import type { Account } from 'masto'
import type { UserLogin } from '~/types'
export function getDisplayName(account?: Account, options?: { rich?: boolean }) { export function getDisplayName(account?: Account, options?: { rich?: boolean }) {
const displayName = account?.displayName || account?.username || '' const displayName = account?.displayName || account?.username || ''
@ -20,7 +21,11 @@ export function getServerName(account: Account) {
return currentInstance.value?.uri || '' return currentInstance.value?.uri || ''
} }
export function getFullHandle(account: Account) { export function getFullHandle(_account: Account | UserLogin) {
if ('guest' in _account && _account.guest)
return `${GUEST_ID}@${_account.server}`
const account = 'server' in _account ? _account.account : _account
const handle = `@${account.acct}` const handle = `@${account.acct}`
if (!currentUser.value || account.acct.includes('@')) if (!currentUser.value || account.acct.includes('@'))
return handle return handle

View file

@ -9,7 +9,7 @@ const requestedRelationships = new Map<string, Ref<Relationship | undefined>>()
let timeoutHandle: NodeJS.Timeout | undefined let timeoutHandle: NodeJS.Timeout | undefined
export function useRelationship(account: Account): Ref<Relationship | undefined> { export function useRelationship(account: Account): Ref<Relationship | undefined> {
if (!currentUser.value) if (isGuest.value)
return ref() return ref()
let relationship = requestedRelationships.get(account.id) let relationship = requestedRelationships.get(account.id)
if (relationship) if (relationship)

View file

@ -25,7 +25,7 @@ export function useSearch(query: MaybeRef<string>, options?: UseSearchOptions) {
* Based on the source it seems like modifying the params when calling next would result in a new search, * Based on the source it seems like modifying the params when calling next would result in a new search,
* but that doesn't seem to be the case. So instead we just create a new paginator with the new params. * but that doesn't seem to be the case. So instead we just create a new paginator with the new params.
*/ */
paginator = masto.search({ q: unref(query), resolve: !!currentUser.value, type: unref(options?.type) }) paginator = masto.search({ q: unref(query), resolve: !isGuest.value, type: unref(options?.type) })
const nextResults = await paginator.next() const nextResults = await paginator.next()
done.value = nextResults.done || false done.value = nextResults.done || false

View file

@ -56,7 +56,7 @@ function mentionHTML(acct: string) {
export function getReplyDraft(status: Status) { export function getReplyDraft(status: Status) {
const accountsToMention: string[] = [] const accountsToMention: string[] = []
const userId = currentUser.value?.account.id const userId = currentUser.value.account!.id
if (status.account.id !== userId) if (status.account.id !== userId)
accountsToMention.push(status.account.acct) accountsToMention.push(status.account.acct)
accountsToMention.push(...(status.mentions.filter(mention => mention.id !== userId).map(mention => mention.acct))) accountsToMention.push(...(status.mentions.filter(mention => mention.id !== userId).map(mention => mention.acct)))

View file

@ -97,7 +97,7 @@ async function subscribe(
async function unsubscribeFromBackend(fromSWPushManager: boolean, removePushNotification = true) { async function unsubscribeFromBackend(fromSWPushManager: boolean, removePushNotification = true) {
const cu = currentUser.value const cu = currentUser.value
if (cu) { if (checkAuth(cu)) {
await removePushNotifications(cu) await removePushNotifications(cu)
removePushNotification && await removePushNotificationData(cu, fromSWPushManager) removePushNotification && await removePushNotificationData(cu, fromSWPushManager)
} }
@ -105,7 +105,7 @@ async function unsubscribeFromBackend(fromSWPushManager: boolean, removePushNoti
async function removePushNotificationDataOnError(e: Error) { async function removePushNotificationDataOnError(e: Error) {
const cu = currentUser.value const cu = currentUser.value
if (cu) if (checkAuth(cu))
await removePushNotificationData(cu, true) await removePushNotificationData(cu, true)
throw e throw e

View file

@ -8,7 +8,7 @@ export interface PushManagerSubscriptionInfo {
subscription: PushSubscription | null subscription: PushSubscription | null
} }
export interface RequiredUserLogin extends Required<Omit<UserLogin, 'account' | 'pushSubscription'>> { export interface RequiredUserLogin extends Required<Pick<UserLogin, 'server' | 'token' | 'vapidKey'>> {
pushSubscription?: MastoPushSubscription pushSubscription?: MastoPushSubscription
} }

View file

@ -6,6 +6,7 @@ import type {
SubscriptionResult, SubscriptionResult,
} from '~/composables/push-notifications/types' } from '~/composables/push-notifications/types'
import { STORAGE_KEY_NOTIFICATION, STORAGE_KEY_NOTIFICATION_POLICY } from '~/constants' import { STORAGE_KEY_NOTIFICATION, STORAGE_KEY_NOTIFICATION_POLICY } from '~/constants'
import type { UserLogin } from '~/types'
const supportsPushNotifications = typeof window !== 'undefined' const supportsPushNotifications = typeof window !== 'undefined'
&& 'serviceWorker' in navigator && 'serviceWorker' in navigator
@ -28,12 +29,12 @@ export const usePushManager = () => {
const hiddenNotification = useLocalStorage<PushNotificationRequest>(STORAGE_KEY_NOTIFICATION, {}) const hiddenNotification = useLocalStorage<PushNotificationRequest>(STORAGE_KEY_NOTIFICATION, {})
const configuredPolicy = useLocalStorage<PushNotificationPolicy>(STORAGE_KEY_NOTIFICATION_POLICY, {}) const configuredPolicy = useLocalStorage<PushNotificationPolicy>(STORAGE_KEY_NOTIFICATION_POLICY, {})
const pushNotificationData = ref({ const pushNotificationData = ref({
follow: currentUser.value?.pushSubscription?.alerts.follow ?? true, follow: currentUser.value.pushSubscription?.alerts.follow ?? true,
favourite: currentUser.value?.pushSubscription?.alerts.favourite ?? true, favourite: currentUser.value.pushSubscription?.alerts.favourite ?? true,
reblog: currentUser.value?.pushSubscription?.alerts.reblog ?? true, reblog: currentUser.value.pushSubscription?.alerts.reblog ?? true,
mention: currentUser.value?.pushSubscription?.alerts.mention ?? true, mention: currentUser.value.pushSubscription?.alerts.mention ?? true,
poll: currentUser.value?.pushSubscription?.alerts.poll ?? true, poll: currentUser.value.pushSubscription?.alerts.poll ?? true,
policy: configuredPolicy.value[currentUser.value?.account?.acct ?? ''] ?? 'all', policy: configuredPolicy.value[currentUser.value.account?.acct ?? ''] ?? 'all',
}) })
// don't clone, we're using indexeddb // don't clone, we're using indexeddb
const { history, commit, clear } = useManualRefHistory(pushNotificationData) const { history, commit, clear } = useManualRefHistory(pushNotificationData)
@ -48,7 +49,7 @@ export const usePushManager = () => {
|| current.policy !== previous.policy || current.policy !== previous.policy
}) })
watch(() => currentUser.value?.pushSubscription, (subscription) => { watch(() => currentUser.value.pushSubscription, (subscription) => {
isSubscribed.value = !!subscription isSubscribed.value = !!subscription
pushNotificationData.value = { pushNotificationData.value = {
follow: subscription?.alerts.follow ?? false, follow: subscription?.alerts.follow ?? false,
@ -56,7 +57,7 @@ export const usePushManager = () => {
reblog: subscription?.alerts.reblog ?? false, reblog: subscription?.alerts.reblog ?? false,
mention: subscription?.alerts.mention ?? false, mention: subscription?.alerts.mention ?? false,
poll: subscription?.alerts.poll ?? false, poll: subscription?.alerts.poll ?? false,
policy: configuredPolicy.value[currentUser.value?.account?.acct ?? ''] ?? 'all', policy: configuredPolicy.value[currentUser.value.account?.acct ?? ''] ?? 'all',
} }
}, { immediate: true, flush: 'post' }) }, { immediate: true, flush: 'post' })
@ -68,10 +69,10 @@ export const usePushManager = () => {
if (!isSupported) if (!isSupported)
return 'not-supported' return 'not-supported'
if (!currentUser.value) if (isGuest.value)
return 'no-user' return 'no-user'
const { pushSubscription, server, token, vapidKey, account: { acct } } = currentUser.value const { pushSubscription, server, token, vapidKey, account: { acct } } = currentUser.value as UserLogin<true>
if (!token || !server || !vapidKey) if (!token || !server || !vapidKey)
return 'invalid-vapid-key' return 'invalid-vapid-key'
@ -87,9 +88,7 @@ export const usePushManager = () => {
} }
currentUser.value.pushSubscription = await createPushSubscription( currentUser.value.pushSubscription = await createPushSubscription(
{ { pushSubscription, server, token, vapidKey },
pushSubscription, server, token, vapidKey,
},
notificationData ?? { notificationData ?? {
alerts: { alerts: {
follow: true, follow: true,
@ -110,7 +109,7 @@ export const usePushManager = () => {
} }
const unsubscribe = async () => { const unsubscribe = async () => {
if (!isSupported || !isSubscribed || !currentUser.value) if (!isSupported || !isSubscribed || !checkAuth(currentUser.value))
return false return false
await removePushNotifications(currentUser.value) await removePushNotifications(currentUser.value)
@ -118,15 +117,18 @@ export const usePushManager = () => {
} }
const saveSettings = async (policy?: SubscriptionPolicy) => { const saveSettings = async (policy?: SubscriptionPolicy) => {
if (!checkAuth(currentUser.value))
return
if (policy) if (policy)
pushNotificationData.value.policy = policy pushNotificationData.value.policy = policy
commit() commit()
if (policy) if (policy)
configuredPolicy.value[currentUser.value!.account.acct ?? ''] = policy configuredPolicy.value[currentUser.value.account.acct ?? ''] = policy
else else
configuredPolicy.value[currentUser.value!.account.acct ?? ''] = pushNotificationData.value.policy configuredPolicy.value[currentUser.value.account.acct ?? ''] = pushNotificationData.value.policy
await nextTick() await nextTick()
clear() clear()
@ -134,6 +136,9 @@ export const usePushManager = () => {
} }
const undoChanges = () => { const undoChanges = () => {
if (!checkAuth(currentUser.value))
return
const current = pushNotificationData.value const current = pushNotificationData.value
const previous = history.value[0].snapshot const previous = history.value[0].snapshot
current.favourite = previous.favourite current.favourite = previous.favourite
@ -142,7 +147,7 @@ export const usePushManager = () => {
current.follow = previous.follow current.follow = previous.follow
current.poll = previous.poll current.poll = previous.poll
current.policy = previous.policy current.policy = previous.policy
configuredPolicy.value[currentUser.value!.account.acct ?? ''] = previous.policy configuredPolicy.value[currentUser.value.account.acct ?? ''] = previous.policy
commit() commit()
clear() clear()
} }

View file

@ -16,6 +16,7 @@ import type { PushNotificationPolicy, PushNotificationRequest } from '~/composab
import { useAsyncIDBKeyval } from '~/composables/idb' import { useAsyncIDBKeyval } from '~/composables/idb'
const mock = process.mock const mock = process.mock
export const GUEST_ID = '[anonymous]'
const initializeUsers = async (): Promise<Ref<UserLogin[]> | RemovableRef<UserLogin[]>> => { const initializeUsers = async (): Promise<Ref<UserLogin[]> | RemovableRef<UserLogin[]>> => {
let defaultUsers = mock ? [mock.user] : [] let defaultUsers = mock ? [mock.user] : []
@ -43,22 +44,42 @@ const initializeUsers = async (): Promise<Ref<UserLogin[]> | RemovableRef<UserLo
const users = await initializeUsers() const users = await initializeUsers()
const instances = useLocalStorage<Record<string, Instance>>(STORAGE_KEY_SERVERS, mock ? mock.server : {}, { deep: true }) const instances = useLocalStorage<Record<string, Instance>>(STORAGE_KEY_SERVERS, mock ? mock.server : {}, { deep: true })
const currentUserId = useLocalStorage<string>(STORAGE_KEY_CURRENT_USER, mock ? mock.user.account.id : '') const currentUserId = useLocalStorage<string>(STORAGE_KEY_CURRENT_USER, mock ? mock.user.account.id : '')
const isGuestId = computed(() => !currentUserId.value || currentUserId.value.startsWith(`${GUEST_ID}@`))
const defaultUser: UserLogin<false> = {
server: DEFAULT_SERVER,
guest: true,
}
export const currentUser = computed<UserLogin | undefined>(() => { export const currentUser = computed<UserLogin>(() => {
if (currentUserId.value) { let user: UserLogin | undefined
const user = users.value.find(user => user.account?.id === currentUserId.value) if (!currentUserId.value) {
if (user)
return user
}
// Fallback to the first account // Fallback to the first account
return users.value[0] user = users.value[0]
}
else if (isGuestId.value) {
const server = currentUserId.value.replace(`${GUEST_ID}@`, '')
user = users.value.find(user => user.guest && user.server === server)
}
else {
user = users.value.find(user => user.account?.id === currentUserId.value)
}
return user || defaultUser
}) })
const publicInstance = ref<Instance | null>(null) export const currentServer = computed<string>(() => currentUser.value.server)
export const currentInstance = computed<null | Instance>(() => currentUser.value ? instances.value[currentUser.value.server] ?? null : publicInstance.value) export const currentInstance = computed<null | Instance>(() => {
return instances.value[currentServer.value] ?? null
})
export const checkAuth = (val: UserLogin | undefined): val is UserLogin<true> => !!(val && !val.guest)
export const isGuest = computed(() => !checkAuth(currentUser.value))
export const getUniqueUserId = (user: UserLogin) =>
user.guest ? `${GUEST_ID}@${user.server}` : user.account.id
export const isSameUser = (a: UserLogin | undefined, b: UserLogin | undefined) =>
a && b && getUniqueUserId(a) === getUniqueUserId(b)
export const publicServer = ref(DEFAULT_SERVER) export const currentUserHandle = computed(() =>
export const currentServer = computed<string>(() => currentUser.value?.server || publicServer.value) currentUser.value.guest ? GUEST_ID : currentUser.value.account!.acct,
)
// when multiple tabs: we need to reload window when sign in, switch account or sign out // when multiple tabs: we need to reload window when sign in, switch account or sign out
if (process.client) { if (process.client) {
@ -91,34 +112,53 @@ if (process.client) {
}, { immediate: true, flush: 'post' }) }, { immediate: true, flush: 'post' })
} }
export const currentUserHandle = computed(() => currentUser.value?.account.id
? `${currentUser.value.account.acct}@${currentInstance.value?.uri || currentServer.value}`
: '[anonymous]',
)
export const useUsers = () => users export const useUsers = () => users
export const characterLimit = computed(() => currentInstance.value?.configuration.statuses.maxCharacters ?? DEFAULT_POST_CHARS_LIMIT) export const characterLimit = computed(() => currentInstance.value?.configuration.statuses.maxCharacters ?? DEFAULT_POST_CHARS_LIMIT)
async function loginTo(user?: Omit<UserLogin, 'account'> & { account?: AccountCredentials }) { async function loginTo({ server, token, vapidKey, pushSubscription, guest = false }: { guest?: boolean } & Omit<UserLogin, 'guest'>) {
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const server = user?.server || route.params.server as string || publicServer.value
const oldServer = currentUser.value.server
let user: UserLogin | undefined = token
? users.value.find(u => u.server === server && u.token === token)
: ((guest
? undefined
: users.value.find(u => u.server === server && u.token))
|| users.value.find(u => u.server === server && u.guest))
const needPush = !user
if (!user) {
if (token) {
user = {
server,
guest: false,
token,
vapidKey,
pushSubscription,
account: undefined as any, // to be assigned later
}
}
else {
user = { server, guest: true }
}
}
const masto = await loginMasto({ const masto = await loginMasto({
url: `https://${server}`, url: `https://${user.server}`,
accessToken: user?.token, accessToken: user.token,
disableVersionCheck: true, disableVersionCheck: true,
// Suppress warning of `masto/fetch` usage // Suppress warning of `masto/fetch` usage
disableExperimentalWarning: true, disableExperimentalWarning: true,
}) })
if (!user?.token) { if (user.guest) {
publicServer.value = server const instance = await masto.instances.fetch()
publicInstance.value = await masto.instances.fetch() instances.value[server] = instance
} }
else { else {
try {
const [me, instance, pushSubscription] = await Promise.all([ const [me, instance, pushSubscription] = await Promise.all([
masto.accounts.verifyCredentials(), masto.accounts.verifyCredentials(),
masto.instances.fetch(), masto.instances.fetch(),
@ -134,31 +174,47 @@ async function loginTo(user?: Omit<UserLogin, 'account'> & { account?: AccountCr
user.account = me user.account = me
user.pushSubscription = pushSubscription user.pushSubscription = pushSubscription
currentUserId.value = me.id
instances.value[server] = instance instances.value[server] = instance
}
if (!users.value.some(u => u.server === user.server && u.token === user.token)) if (needPush)
users.value.push(user as UserLogin) users.value.push(user)
}
catch { currentUserId.value = getUniqueUserId(user)
await signout()
}
}
// This only cleans up the URL; page content should stay the same // This only cleans up the URL; page content should stay the same
if (route.path === '/signin/callback') { if (!user.guest && (route.path === '/signin/callback' || route.path === '/')) {
await router.push('/home') await router.push('/home')
} }
else if (isGuest.value && route.meta.middleware === 'auth') {
await router.push(`/${server}/public`)
}
else if ('server' in route.params && user.server !== route.params.server) {
if (!route.params.account.includes('@'))
// convert to long handle
route.params.account += `@${oldServer}`
else if ('server' in route.params && user?.token && !useNuxtApp()._processingMiddleware) {
await router.push({ await router.push({
...route, ...route,
params: {
...route.params,
server: user.server,
},
force: true, force: true,
}) })
} }
return masto return masto
} }
export type LoginTo = typeof loginTo
export const switchUser = (user: UserLogin, masto: ElkMasto) => {
const router = useRouter()
if (!user.guest && !isGuest.value && user.account.id === currentUser.value.account!.id)
router.push(getAccountRoute(user.account))
else
masto.loginTo(user)
}
export function setAccountInfo(userId: string, account: AccountCredentials) { export function setAccountInfo(userId: string, account: AccountCredentials) {
const index = getUsersIndexByUserId(userId) const index = getUsersIndexByUserId(userId)
@ -182,10 +238,10 @@ export function getUsersIndexByUserId(userId: string) {
return users.value.findIndex(u => u.account?.id === userId) return users.value.findIndex(u => u.account?.id === userId)
} }
export async function removePushNotificationData(user: UserLogin, fromSWPushManager = true) { export async function removePushNotificationData(user: UserLogin<true>, fromSWPushManager = true) {
// clear push subscription // clear push subscription
user.pushSubscription = undefined user.pushSubscription = undefined
const { acct } = user.account const { acct } = user.account!
// clear request notification permission // clear request notification permission
delete useLocalStorage<PushNotificationRequest>(STORAGE_KEY_NOTIFICATION, {}).value[acct] delete useLocalStorage<PushNotificationRequest>(STORAGE_KEY_NOTIFICATION, {}).value[acct]
// clear push notification policy // clear push notification policy
@ -208,7 +264,7 @@ export async function removePushNotificationData(user: UserLogin, fromSWPushMana
} }
} }
export async function removePushNotifications(user: UserLogin) { export async function removePushNotifications(user: UserLogin<true>) {
if (!user.pushSubscription) if (!user.pushSubscription)
return return
@ -221,45 +277,45 @@ export async function removePushNotifications(user: UserLogin) {
} }
} }
// do not sign out if there is only one guest user
export const canSignOut = computed(() =>
users.value.length > 1 || !users.value[0].guest,
)
export async function signout() { export async function signout() {
// TODO: confirm // TODO: confirm
if (!currentUser.value)
if (!canSignOut.value)
return return
const masto = useMasto() const index = users.value.findIndex(u => isSameUser(u, currentUser.value))
const _currentUserId = currentUser.value.account.id
const index = users.value.findIndex(u => u.account?.id === _currentUserId)
if (index !== -1) { if (index !== -1) {
// Clear stale data // Clear stale data
clearUserLocalStorage() clearUserLocalStorage()
if (!users.value.some((u, i) => u.server === currentUser.value!.server && i !== index)) if (!users.value.some((u, i) => u.server === currentUser.value.server && i !== index))
delete instances.value[currentUser.value.server] delete instances.value[currentUser.value.server]
if (checkAuth(currentUser.value)) {
await removePushNotifications(currentUser.value) await removePushNotifications(currentUser.value)
await removePushNotificationData(currentUser.value) await removePushNotificationData(currentUser.value)
}
currentUserId.value = '' currentUserId.value = ''
// Remove the current user from the users // Remove the current user from the users
users.value.splice(index, 1) users.value.splice(index, 1)
} }
// Set currentUserId to next user if available // Set currentUserId to next user
currentUserId.value = users.value[0]?.account?.id currentUserId.value = getUniqueUserId(users.value[0] ? users.value[0] : defaultUser)
if (!currentUserId.value)
await useRouter().push('/')
const masto = useMasto()
await masto.loginTo(currentUser.value) await masto.loginTo(currentUser.value)
} }
const notifications = reactive<Record<string, undefined | [Promise<WsEvents>, number]>>({}) const notifications = reactive<Record<string, undefined | [Promise<WsEvents>, number]>>({})
export const useNotifications = () => { export const useNotifications = () => {
const id = currentUser.value?.account.id const id = $computed(() => currentUser.value.account?.id)
const masto = useMasto() const masto = useMasto()
const clearNotifications = () => { const clearNotifications = () => {
@ -269,7 +325,7 @@ export const useNotifications = () => {
} }
async function connect(): Promise<void> { async function connect(): Promise<void> {
if (!isMastoInitialised.value || !id || notifications[id] || !currentUser.value?.token) if (!isMastoInitialised.value || !id || notifications[id] || !currentUser.value.token)
return return
const stream = masto.stream.streamUser() const stream = masto.stream.streamUser()
@ -317,9 +373,9 @@ export function useUserLocalStorage<T extends object>(key: string, initial: () =
const all = storages.get(key) as Ref<Record<string, T>> const all = storages.get(key) as Ref<Record<string, T>>
return computed(() => { return computed(() => {
const id = currentUser.value?.account.id const id = currentUser.value.guest
? currentUser.value.account.acct ? GUEST_ID
: '[anonymous]' : currentUser.value.account!.acct
all.value[id] = Object.assign(initial(), all.value[id] || {}) all.value[id] = Object.assign(initial(), all.value[id] || {})
return all.value[id] return all.value[id]
}) })
@ -330,7 +386,7 @@ export function useUserLocalStorage<T extends object>(key: string, initial: () =
*/ */
export function clearUserLocalStorage(account?: Account) { export function clearUserLocalStorage(account?: Account) {
if (!account) if (!account)
account = currentUser.value?.account account = currentUser.value.account
if (!account) if (!account)
return return
@ -354,10 +410,11 @@ export const createMasto = () => {
if (key === 'loginTo') { if (key === 'loginTo') {
return (...args: any[]): Promise<MastoClient> => { return (...args: any[]): Promise<MastoClient> => {
return apiPromise.value = loginTo(...args).then((r) => { return apiPromise.value = (loginTo as any)(...args).then((r: any) => {
api.value = r api.value = r
return masto return masto
}).catch(() => { }).catch((err: any) => {
console.error(err)
// Show error page when Mastodon server is down // Show error page when Mastodon server is down
throw createError({ throw createError({
fatal: true, fatal: true,

View file

@ -22,7 +22,7 @@ const reload = async () => {
try { try {
if (!masto.loggedIn.value) if (!masto.loggedIn.value)
await masto.loginTo(currentUser.value) await masto.loginTo(currentUser.value)
clearError({ redirect: currentUser.value ? '/home' : `/${currentServer.value}/public` }) clearError({ redirect: !isGuest.value ? '/home' : `/${currentServer.value}/public` })
} }
catch { catch {
state.value = 'error' state.value = 'error'

View file

@ -22,14 +22,15 @@ const showUserPicker = logicAnd(
<NavSide command /> <NavSide command />
<div flex-auto /> <div flex-auto />
<div v-if="isMastoInitialised" flex flex-col> <div v-if="isMastoInitialised" flex flex-col>
<div hidden xl:block> <div v-if="isGuest" hidden xl:block>
<UserSignInEntry v-if="!currentUser" /> <UserSignInEntry />
</div> </div>
<div v-if="currentUser" p6 pb8 w-full> <div v-if="currentUser" p6 pb8 w-full>
<div hidden xl-block> <div hidden xl-block>
<UserPicker v-if="showUserPicker" /> <UserPicker v-if="showUserPicker" />
<div v-else flex="~" items-center justify-between> <div v-else flex="~" items-center justify-between>
<NuxtLink <NuxtLink
v-if="checkAuth(currentUser)"
hidden xl:block hidden xl:block
rounded-3 text-primary text-start w-full rounded-3 text-primary text-start w-full
hover:bg-active cursor-pointer transition-100 hover:bg-active cursor-pointer transition-100
@ -37,6 +38,8 @@ const showUserPicker = logicAnd(
> >
<AccountInfo :account="currentUser.account" md:break-words square /> <AccountInfo :account="currentUser.account" md:break-words square />
</NuxtLink> </NuxtLink>
<AccountGuest v-else :user="currentUser" />
<UserDropdown /> <UserDropdown />
</div> </div>
</div> </div>

View file

@ -49,6 +49,7 @@
"confirm": "Confirm", "confirm": "Confirm",
"edit": "Edit", "edit": "Edit",
"enter_app": "Enter App", "enter_app": "Enter App",
"explore_as_a_guest": "Explore as a guest",
"favourite": "Favourite", "favourite": "Favourite",
"favourited": "Favourited", "favourited": "Favourited",
"more": "More", "more": "More",

View file

@ -50,6 +50,7 @@
"confirm": "Confirm", "confirm": "Confirm",
"edit": "Edit", "edit": "Edit",
"enter_app": "Enter App", "enter_app": "Enter App",
"explore_as_a_guest": "Explore as a guest",
"favourite": "Favorite", "favourite": "Favorite",
"favourite_count": "{0}", "favourite_count": "{0}",
"favourited": "Favorited", "favourited": "Favorited",

View file

@ -49,6 +49,7 @@
"confirm": "确认", "confirm": "确认",
"edit": "编辑", "edit": "编辑",
"enter_app": "进入应用", "enter_app": "进入应用",
"explore_as_a_guest": "游客浏览",
"favourite": "喜欢", "favourite": "喜欢",
"favourited": "已喜欢", "favourited": "已喜欢",
"more": "更多", "more": "更多",

View file

@ -5,7 +5,7 @@ export default defineNuxtRouteMiddleware((to) => {
return return
onMastoInit(() => { onMastoInit(() => {
if (!currentUser.value) if (isGuest.value)
return navigateTo(`/${currentServer.value}/public`) return navigateTo(`/${currentServer.value}/public`)
if (to.path === '/') if (to.path === '/')
return navigateTo('/home') return navigateTo('/home')

View file

@ -1,4 +1,4 @@
export default defineNuxtRouteMiddleware(async (to, from) => { export default defineNuxtRouteMiddleware(async (to) => {
if (process.server) if (process.server)
return return
@ -13,23 +13,6 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
const user = currentUser.value const user = currentUser.value
if (!user) {
if (from.params.server !== to.params.server) {
await masto.loginTo({
server: to.params.server as string,
})
}
return
}
// No need to additionally resolve an id if we're already logged in
if (user.server === to.params.server)
return
// Tags don't need to be redirected to a local id
if (to.params.tag)
return
// Handle redirecting to new permalink structure for users with old links // Handle redirecting to new permalink structure for users with old links
if (!to.params.server) { if (!to.params.server) {
return { return {
@ -41,28 +24,11 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
} }
} }
try { // No need to additionally resolve an id if we're already logged in
// If we're already on an account page, we can search for this on the new instance if (user.server === to.params.server)
if (to.params.account && to.name !== 'status' && to.params.account.includes('@')) { return
const account = await fetchAccountByHandle(to.params.account as string)
if (account)
return getAccountRoute(account)
}
if (!masto.loggedIn.value) masto.loginTo({
await masto.loginTo(currentUser.value) server: to.params.server as string,
})
// If we're logged in, search for the local id the account or status corresponds to
const { value } = await masto.search({ q: `https:/${to.fullPath}`, resolve: true, limit: 1 }).next()
const { accounts, statuses } = value
if (statuses[0])
return getStatusRoute(statuses[0])
if (accounts[0])
return getAccountRoute(accounts[0])
}
catch {}
return '/home'
}) })

View file

@ -76,7 +76,7 @@ onReactivated(() => {
:actions="status.visibility !== 'direct'" :actions="status.visibility !== 'direct'"
/> />
<PublishWidget <PublishWidget
v-if="currentUser" v-if="!isGuest"
ref="publishWidget" ref="publishWidget"
border="y base" border="y base"
:draft-key="replyDraft!.key" :draft-key="replyDraft!.key"

View file

@ -18,7 +18,7 @@ const tabs = $computed(() => [
{ {
to: `/${currentServer.value}/explore/users`, to: `/${currentServer.value}/explore/users`,
display: t('tab.for_you'), display: t('tab.for_you'),
disabled: !isMastoInitialised.value || !currentUser.value, disabled: !isMastoInitialised.value || isGuest.value,
}, },
] as const) ] as const)
</script> </script>

View file

@ -19,6 +19,6 @@ useHeadFixed({
</NuxtLink> </NuxtLink>
</template> </template>
<TimelinePinned v-if="isMastoInitialised && currentUser" /> <TimelinePinned v-if="isMastoInitialised && !isGuest" />
</MainContent> </MainContent>
</template> </template>

View file

@ -27,7 +27,7 @@ const isRootPath = computedEager(() => route.name === 'settings')
</template> </template>
<div xl:w-97 lg:w-78 w-full> <div xl:w-97 lg:w-78 w-full>
<SettingsItem <SettingsItem
v-if="isHydrated && currentUser " v-if="isHydrated && !isGuest"
command command
icon="i-ri:user-line" icon="i-ri:user-line"
:text="$t('settings.profile.label')" :text="$t('settings.profile.label')"

View file

@ -15,7 +15,7 @@ useHeadFixed({
title: () => `${t('settings.profile.appearance.title')} | ${t('nav.settings')}`, title: () => `${t('settings.profile.appearance.title')} | ${t('nav.settings')}`,
}) })
const account = $computed(() => currentUser.value?.account) const account = $computed(() => currentUser.value.account)
const onlineSrc = $computed(() => ({ const onlineSrc = $computed(() => ({
avatar: account?.avatar || '', avatar: account?.avatar || '',

View file

@ -40,7 +40,7 @@ async function importTokens() {
const users = data.users as UserLogin[] const users = data.users as UserLogin[]
const newUsers: UserLogin[] = [] const newUsers: UserLogin[] = []
for (const user of users) { for (const user of users) {
if (loggedInUsers.value.some(u => u.server === user.server && u.account.id === user.account.id)) if (loggedInUsers.value.some(u => isSameUser(u, user)))
continue continue
newUsers.push(user) newUsers.push(user)
} }
@ -69,8 +69,9 @@ async function importTokens() {
<div p6> <div p6>
<template v-if="loggedInUsers.length"> <template v-if="loggedInUsers.length">
<div flex="~ col gap2"> <div flex="~ col gap2">
<div v-for="user of loggedInUsers" :key="user.account.id"> <div v-for="user of loggedInUsers" :key="getUniqueUserId(user)">
<AccountInfo :account="user.account" :hover-card="false" /> <AccountInfo v-if="!user.guest" :account="user.account" :hover-card="false" />
<AccountGuest v-else :user="user" />
</div> </div>
</div> </div>
<div my4 border="t base" /> <div my4 border="t base" />

View file

@ -8,6 +8,7 @@ export default defineNuxtPlugin(async (nuxtApp) => {
server: query.server, server: query.server,
token: query.token, token: query.token,
vapidKey: typeof query.vapid_key === 'string' ? query.vapid_key : undefined, vapidKey: typeof query.vapid_key === 'string' ? query.vapid_key : undefined,
guest: false,
} }
: currentUser.value : currentUser.value

View file

@ -1,6 +1,7 @@
import type { Account, AccountCredentials, Attachment, CreateStatusParams, Emoji, Instance, MastoClient, Notification, PushSubscription, Status } from 'masto' import type { Account, AccountCredentials, Attachment, CreateStatusParams, Emoji, Instance, MastoClient, Notification, PushSubscription, Status } from 'masto'
import type { Ref } from 'vue' import type { Ref } from 'vue'
import type { MarkNonNullable, Mutable } from './utils' import type { MarkNonNullable, Mutable } from './utils'
import type { LoginTo } from '~/composables/users'
export interface AppInfo { export interface AppInfo {
id: string id: string
@ -12,16 +13,25 @@ export interface AppInfo {
vapid_key: string vapid_key: string
} }
export interface UserLogin { interface UserLoginWithToken {
server: string
token?: string
account: AccountCredentials account: AccountCredentials
vapidKey?: string guest: false
pushSubscription?: PushSubscription
} }
interface UserLoginGuest {
account?: undefined
guest: true
}
export type UserLogin<WithToken extends boolean = boolean> = {
server: string
token?: string
vapidKey?: string
pushSubscription?: PushSubscription
} & ((WithToken extends false ? UserLoginGuest : never) | (WithToken extends true ? UserLoginWithToken : never))
export interface ElkMasto extends MastoClient { export interface ElkMasto extends MastoClient {
loginTo (user?: Omit<UserLogin, 'account'> & { account?: AccountCredentials }): Promise<MastoClient> loginTo: LoginTo
loggedIn: Ref<boolean> loggedIn: Ref<boolean>
} }

View file

@ -36,7 +36,7 @@ export default defineConfig({
// buttons // buttons
'btn-base': 'cursor-pointer disabled:pointer-events-none disabled:bg-$c-bg-btn-disabled disabled:text-$c-text-btn-disabled', 'btn-base': 'cursor-pointer disabled:pointer-events-none disabled:bg-$c-bg-btn-disabled disabled:text-$c-text-btn-disabled',
'btn-solid': 'btn-base px-4 py-2 rounded text-$c-text-btn bg-$c-primary hover:bg-$c-primary-active', 'btn-solid': 'btn-base px-4 py-2 rounded text-$c-text-btn bg-$c-primary hover:bg-$c-primary-active',
'btn-outline': 'btn-base px-4 py-2 rounded text-$c-primary border border-$c-primary hover:bg-$c-primary hover:text-inverted', 'btn-outline': 'btn-base px-4 py-2 rounded text-$c-primary border border-$c-primary hover:bg-$c-primary hover:text-inverted disabled:border-$c-bg-btn-disabled',
'btn-text': 'btn-base px-4 py-2 text-$c-primary hover:text-$c-primary-active', 'btn-text': 'btn-base px-4 py-2 text-$c-primary hover:text-$c-primary-active',
'btn-action-icon': 'btn-base hover:bg-active rounded-full h9 w9 flex items-center justify-center disabled:bg-transparent disabled:text-$c-text-secondary', 'btn-action-icon': 'btn-base hover:bg-active rounded-full h9 w9 flex items-center justify-center disabled:bg-transparent disabled:text-$c-text-secondary',