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()
// 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>
<template>

View file

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

View file

@ -7,7 +7,7 @@ const { account } = defineProps<{
}>()
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 toggleMute = async () => {
@ -53,7 +53,7 @@ const toggleBlockDomain = async () => {
/>
</NuxtLink>
<template v-if="currentUser">
<template v-if="!isGuest">
<template v-if="!isSelf">
<CommonDropdownItem
: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
// when we know there is no user.
const noUserDisable = computed(() => !isMastoInitialised.value || (props.userOnly && !currentUser.value))
const noUserVisual = computed(() => isMastoInitialised.value && props.userOnly && !currentUser.value)
const noUserDisable = computed(() => !isMastoInitialised.value || (props.userOnly && isGuest.value))
const noUserVisual = computed(() => isMastoInitialised.value && props.userOnly && isGuest.value)
</script>
<template>

View file

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

View file

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

View file

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

View file

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

View file

@ -184,7 +184,7 @@ defineExpose({
</script>
<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">
<div flex="~ col gap-1">
<div id="state-editing" text-secondary self-center>

View file

@ -23,7 +23,7 @@ const clipboard = useClipboard()
const router = useRouter()
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 {
toggle: _toggleTranslation,
@ -178,7 +178,7 @@ async function editStatus() {
/>
<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')"
:icon="status.muted ? 'i-ri:eye-line' : 'i-ri:eye-off-line'"
:command="command"

View file

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

View file

@ -22,7 +22,11 @@ const account = isSelf ? computed(() => status.account) : useAccountById(status.
<template v-if="account">
<div i-ri:reply-fill :class="collapsed ? '' : 'scale-x-[-1]'" text-secondary-light />
<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 />
</template>
</template>

View file

@ -16,7 +16,7 @@ const { formatNumber } = useHumanReadableNumber()
const virtualScroller = $(useFeatureFlag('experimentalVirtualScroll'))
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>

View file

@ -1,5 +1,5 @@
<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>
<template>

View file

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

View file

@ -1,16 +1,6 @@
<script setup lang="ts">
import type { UserLogin } from '~/types'
const all = useUsers()
const router = useRouter()
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>
<template>
@ -21,11 +11,14 @@ const switchUser = (user: UserLogin) => {
flex rounded
cursor-pointer
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"
@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>
</template>
</div>

View file

@ -1,7 +1,8 @@
<script setup lang="ts">
import Fuse from 'fuse.js'
import { $fetch } from 'ofetch'
import { DEFAULT_SERVER } from '~/constants'
const masto = useMasto()
const input = $ref<HTMLInputElement>()
let server = $ref<string>('')
@ -26,7 +27,7 @@ async function oauth() {
server = server.split('/')[0]
try {
location.href = await $fetch<string>(`/api/${server || DEFAULT_SERVER}/login`, {
location.href = await $fetch<string>(`/api/${server}/login`, {
method: 'POST',
body: {
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() {
if (server.startsWith('https://'))
server = server.replace('https://', '')
@ -180,9 +186,19 @@ onClickOutside($$(input), () => {
</i18n-t>
</span>
</div>
<button flex="~ row" gap-x-2 items-center btn-solid mt2 :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" />
{{ $t('action.sign_in') }}
</button>
<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" />
{{ $t('action.sign_in') }}
</button>
</div>
</form>
</template>

View file

@ -1,6 +1,4 @@
<script setup lang="ts">
import type { UserLogin } from '~/types'
const emit = defineEmits<{
(event: 'click'): void
}>()
@ -8,20 +6,10 @@ const emit = defineEmits<{
const all = useUsers()
const sorted = computed(() => {
return [
currentUser.value!,
...all.value.filter(account => account.token !== currentUser.value?.token),
].filter(Boolean)
return all.value.sort((a, b) => isSameUser(a, currentUser.value) ? -1 : isSameUser(b, currentUser.value) ? 1 : 0)
})
const router = useRouter()
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>
<template>
@ -31,11 +19,12 @@ const switchUser = (user: UserLogin) => {
flex rounded px4 py3 text-left
hover:bg-active cursor-pointer transition-100
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 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>
</template>
<div border="t base" pt2>
@ -45,8 +34,8 @@ const switchUser = (user: UserLogin) => {
@click="openSigninDialog"
/>
<CommonDropdownItem
v-if="isMastoInitialised && currentUser"
:text="$t('user.sign_out_account', [getFullHandle(currentUser.account)])"
v-if="isMastoInitialised && canSignOut"
:text="$t('user.sign_out_account', [getFullHandle(currentUser)])"
icon="i-ri:logout-box-line rtl-flip"
@click="signout"
/>

View file

@ -330,9 +330,9 @@ export const provideGlobalCommands = () => {
parent: 'account-switch',
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',
onActivate() {
@ -342,9 +342,8 @@ export const provideGlobalCommands = () => {
useCommand({
scope: 'Account',
visible: () => currentUser.value,
name: () => t('user.sign_out_account', [getFullHandle(currentUser.value!.account)]),
visible: () => canSignOut.value,
name: () => t('user.sign_out_account', [getFullHandle(currentUser.value)]),
icon: 'i-ri:logout-box-line',
onActivate() {

View file

@ -1,4 +1,5 @@
import type { Account } from 'masto'
import type { UserLogin } from '~/types'
export function getDisplayName(account?: Account, options?: { rich?: boolean }) {
const displayName = account?.displayName || account?.username || ''
@ -20,7 +21,11 @@ export function getServerName(account: Account) {
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}`
if (!currentUser.value || account.acct.includes('@'))
return handle

View file

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

View file

@ -56,7 +56,7 @@ function mentionHTML(acct: string) {
export function getReplyDraft(status: Status) {
const accountsToMention: string[] = []
const userId = currentUser.value?.account.id
const userId = currentUser.value.account!.id
if (status.account.id !== userId)
accountsToMention.push(status.account.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) {
const cu = currentUser.value
if (cu) {
if (checkAuth(cu)) {
await removePushNotifications(cu)
removePushNotification && await removePushNotificationData(cu, fromSWPushManager)
}
@ -105,7 +105,7 @@ async function unsubscribeFromBackend(fromSWPushManager: boolean, removePushNoti
async function removePushNotificationDataOnError(e: Error) {
const cu = currentUser.value
if (cu)
if (checkAuth(cu))
await removePushNotificationData(cu, true)
throw e

View file

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

View file

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

View file

@ -16,6 +16,7 @@ import type { PushNotificationPolicy, PushNotificationRequest } from '~/composab
import { useAsyncIDBKeyval } from '~/composables/idb'
const mock = process.mock
export const GUEST_ID = '[anonymous]'
const initializeUsers = async (): Promise<Ref<UserLogin[]> | RemovableRef<UserLogin[]>> => {
let defaultUsers = mock ? [mock.user] : []
@ -43,22 +44,42 @@ const initializeUsers = async (): Promise<Ref<UserLogin[]> | RemovableRef<UserLo
const users = await initializeUsers()
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 isGuestId = computed(() => !currentUserId.value || currentUserId.value.startsWith(`${GUEST_ID}@`))
const defaultUser: UserLogin<false> = {
server: DEFAULT_SERVER,
guest: true,
}
export const currentUser = computed<UserLogin | undefined>(() => {
if (currentUserId.value) {
const user = users.value.find(user => user.account?.id === currentUserId.value)
if (user)
return user
}
export const currentUser = computed<UserLogin>(() => {
let user: UserLogin | undefined
if (!currentUserId.value) {
// 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 currentInstance = computed<null | Instance>(() => currentUser.value ? instances.value[currentUser.value.server] ?? null : publicInstance.value)
export const currentServer = computed<string>(() => currentUser.value.server)
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 currentServer = computed<string>(() => currentUser.value?.server || publicServer.value)
export const currentUserHandle = computed(() =>
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
if (process.client) {
@ -91,74 +112,109 @@ if (process.client) {
}, { 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 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 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({
url: `https://${server}`,
accessToken: user?.token,
url: `https://${user.server}`,
accessToken: user.token,
disableVersionCheck: true,
// Suppress warning of `masto/fetch` usage
disableExperimentalWarning: true,
})
if (!user?.token) {
publicServer.value = server
publicInstance.value = await masto.instances.fetch()
if (user.guest) {
const instance = await masto.instances.fetch()
instances.value[server] = instance
}
else {
try {
const [me, instance, pushSubscription] = await Promise.all([
masto.accounts.verifyCredentials(),
masto.instances.fetch(),
// if PWA is not enabled, don't get push subscription
useRuntimeConfig().public.pwaEnabled
// we get 404 response instead empty data
? masto.pushSubscriptions.fetch().catch(() => Promise.resolve(undefined))
: Promise.resolve(undefined),
])
const [me, instance, pushSubscription] = await Promise.all([
masto.accounts.verifyCredentials(),
masto.instances.fetch(),
// if PWA is not enabled, don't get push subscription
useRuntimeConfig().public.pwaEnabled
// we get 404 response instead empty data
? masto.pushSubscriptions.fetch().catch(() => Promise.resolve(undefined))
: Promise.resolve(undefined),
])
if (!me.acct.includes('@'))
me.acct = `${me.acct}@${instance.uri}`
if (!me.acct.includes('@'))
me.acct = `${me.acct}@${instance.uri}`
user.account = me
user.pushSubscription = pushSubscription
currentUserId.value = me.id
instances.value[server] = instance
if (!users.value.some(u => u.server === user.server && u.token === user.token))
users.value.push(user as UserLogin)
}
catch {
await signout()
}
user.account = me
user.pushSubscription = pushSubscription
instances.value[server] = instance
}
if (needPush)
users.value.push(user)
currentUserId.value = getUniqueUserId(user)
// 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')
}
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({
...route,
params: {
...route.params,
server: user.server,
},
force: true,
})
}
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) {
const index = getUsersIndexByUserId(userId)
@ -182,10 +238,10 @@ export function getUsersIndexByUserId(userId: string) {
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
user.pushSubscription = undefined
const { acct } = user.account
const { acct } = user.account!
// clear request notification permission
delete useLocalStorage<PushNotificationRequest>(STORAGE_KEY_NOTIFICATION, {}).value[acct]
// 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)
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() {
// TODO: confirm
if (!currentUser.value)
if (!canSignOut.value)
return
const masto = useMasto()
const _currentUserId = currentUser.value.account.id
const index = users.value.findIndex(u => u.account?.id === _currentUserId)
const index = users.value.findIndex(u => isSameUser(u, currentUser.value))
if (index !== -1) {
// Clear stale data
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]
await removePushNotifications(currentUser.value)
await removePushNotificationData(currentUser.value)
if (checkAuth(currentUser.value)) {
await removePushNotifications(currentUser.value)
await removePushNotificationData(currentUser.value)
}
currentUserId.value = ''
// Remove the current user from the users
users.value.splice(index, 1)
}
// Set currentUserId to next user if available
currentUserId.value = users.value[0]?.account?.id
if (!currentUserId.value)
await useRouter().push('/')
// Set currentUserId to next user
currentUserId.value = getUniqueUserId(users.value[0] ? users.value[0] : defaultUser)
const masto = useMasto()
await masto.loginTo(currentUser.value)
}
const notifications = reactive<Record<string, undefined | [Promise<WsEvents>, number]>>({})
export const useNotifications = () => {
const id = currentUser.value?.account.id
const id = $computed(() => currentUser.value.account?.id)
const masto = useMasto()
const clearNotifications = () => {
@ -269,7 +325,7 @@ export const useNotifications = () => {
}
async function connect(): Promise<void> {
if (!isMastoInitialised.value || !id || notifications[id] || !currentUser.value?.token)
if (!isMastoInitialised.value || !id || notifications[id] || !currentUser.value.token)
return
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>>
return computed(() => {
const id = currentUser.value?.account.id
? currentUser.value.account.acct
: '[anonymous]'
const id = currentUser.value.guest
? GUEST_ID
: currentUser.value.account!.acct
all.value[id] = Object.assign(initial(), 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) {
if (!account)
account = currentUser.value?.account
account = currentUser.value.account
if (!account)
return
@ -354,10 +410,11 @@ export const createMasto = () => {
if (key === 'loginTo') {
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
return masto
}).catch(() => {
}).catch((err: any) => {
console.error(err)
// Show error page when Mastodon server is down
throw createError({
fatal: true,

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,4 +1,4 @@
export default defineNuxtRouteMiddleware(async (to, from) => {
export default defineNuxtRouteMiddleware(async (to) => {
if (process.server)
return
@ -13,23 +13,6 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
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
if (!to.params.server) {
return {
@ -41,28 +24,11 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
}
}
try {
// If we're already on an account page, we can search for this on the new instance
if (to.params.account && to.name !== 'status' && to.params.account.includes('@')) {
const account = await fetchAccountByHandle(to.params.account as string)
if (account)
return getAccountRoute(account)
}
// No need to additionally resolve an id if we're already logged in
if (user.server === to.params.server)
return
if (!masto.loggedIn.value)
await masto.loginTo(currentUser.value)
// 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'
masto.loginTo({
server: to.params.server as string,
})
})

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -36,7 +36,7 @@ export default defineConfig({
// buttons
'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-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-action-icon': 'btn-base hover:bg-active rounded-full h9 w9 flex items-center justify-center disabled:bg-transparent disabled:text-$c-text-secondary',