refactor: sync masto (#1121)

zio/stable
三咲智子 Kevin Deng 2023-01-15 16:38:02 +08:00 committed by GitHub
parent eb1f769e32
commit 4422a57f49
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
81 changed files with 397 additions and 367 deletions

View File

@ -12,11 +12,11 @@ const isSelf = $(useSelfAccount(() => account))
const enable = $computed(() => !isSelf && currentUser.value) const enable = $computed(() => !isSelf && currentUser.value)
const relationship = $computed(() => props.relationship || useRelationship(account).value) const relationship = $computed(() => props.relationship || useRelationship(account).value)
const masto = useMasto() const { client } = $(useMasto())
async function toggleFollow() { async function toggleFollow() {
relationship!.following = !relationship!.following relationship!.following = !relationship!.following
try { try {
const newRel = await masto.v1.accounts[relationship!.following ? 'follow' : 'unfollow'](account.id) const newRel = await client.v1.accounts[relationship!.following ? 'follow' : 'unfollow'](account.id)
Object.assign(relationship!, newRel) Object.assign(relationship!, newRel)
} }
catch (err) { catch (err) {
@ -29,7 +29,7 @@ async function toggleFollow() {
async function unblock() { async function unblock() {
relationship!.blocking = false relationship!.blocking = false
try { try {
const newRel = await masto.v1.accounts.unblock(account.id) const newRel = await client.v1.accounts.unblock(account.id)
Object.assign(relationship!, newRel) Object.assign(relationship!, newRel)
} }
catch (err) { catch (err) {
@ -42,7 +42,7 @@ async function unblock() {
async function unmute() { async function unmute() {
relationship!.muting = false relationship!.muting = false
try { try {
const newRel = await masto.v1.accounts.unmute(account.id) const newRel = await client.v1.accounts.unmute(account.id)
Object.assign(relationship!, newRel) Object.assign(relationship!, newRel)
} }
catch (err) { catch (err) {

View File

@ -6,7 +6,7 @@ const { account } = defineProps<{
command?: boolean command?: boolean
}>() }>()
const masto = useMasto() const { client } = $(useMasto())
const { t } = useI18n() const { t } = useI18n()
@ -46,7 +46,7 @@ function previewAvatar() {
async function toggleNotify() { async function toggleNotify() {
relationship!.notifying = !relationship!.notifying relationship!.notifying = !relationship!.notifying
try { try {
const newRel = await masto.v1.accounts.follow(account.id, { notify: relationship!.notifying }) const newRel = await client.v1.accounts.follow(account.id, { notify: relationship!.notifying })
Object.assign(relationship!, newRel) Object.assign(relationship!, newRel)
} }
catch { catch {

View File

@ -10,7 +10,7 @@ let relationship = $(useRelationship(account))
const isSelf = $(useSelfAccount(() => account)) const isSelf = $(useSelfAccount(() => account))
const { t } = useI18n() const { t } = useI18n()
const masto = useMasto() const { client } = $(useMasto())
const isConfirmed = async (title: string) => { const isConfirmed = async (title: string) => {
return await openConfirmDialog(t('common.confirm_dialog.title', [title])) === 'confirm' return await openConfirmDialog(t('common.confirm_dialog.title', [title])) === 'confirm'
@ -22,10 +22,10 @@ const toggleMute = async (title: string) => {
relationship!.muting = !relationship!.muting relationship!.muting = !relationship!.muting
relationship = relationship!.muting relationship = relationship!.muting
? await masto.v1.accounts.mute(account.id, { ? await client.v1.accounts.mute(account.id, {
// TODO support more options // TODO support more options
}) })
: await masto.v1.accounts.unmute(account.id) : await client.v1.accounts.unmute(account.id)
} }
const toggleBlockUser = async (title: string) => { const toggleBlockUser = async (title: string) => {
@ -33,7 +33,7 @@ const toggleBlockUser = async (title: string) => {
return return
relationship!.blocking = !relationship!.blocking relationship!.blocking = !relationship!.blocking
relationship = await masto.v1.accounts[relationship!.blocking ? 'block' : 'unblock'](account.id) relationship = await client.v1.accounts[relationship!.blocking ? 'block' : 'unblock'](account.id)
} }
const toggleBlockDomain = async (title: string) => { const toggleBlockDomain = async (title: string) => {
@ -41,7 +41,7 @@ const toggleBlockDomain = async (title: string) => {
return return
relationship!.domainBlocking = !relationship!.domainBlocking relationship!.domainBlocking = !relationship!.domainBlocking
await masto.v1.domainBlocks[relationship!.domainBlocking ? 'block' : 'unblock'](getServerName(account)) await client.v1.domainBlocks[relationship!.domainBlocking ? 'block' : 'unblock'](getServerName(account))
} }
const toggleReblogs = async (title: string) => { const toggleReblogs = async (title: string) => {
@ -49,7 +49,7 @@ const toggleReblogs = async (title: string) => {
return return
const showingReblogs = !relationship?.showingReblogs const showingReblogs = !relationship?.showingReblogs
relationship = await masto.v1.accounts.follow(account.id, { reblogs: showingReblogs }) relationship = await client.v1.accounts.follow(account.id, { reblogs: showingReblogs })
} }
</script> </script>

View File

@ -42,7 +42,7 @@ defineSlots<{
const { t } = useI18n() const { t } = useI18n()
const { items, prevItems, update, state, endAnchor, error } = usePaginator(paginator, stream, eventType, preprocess) const { items, prevItems, update, state, endAnchor, error } = usePaginator(paginator, $$(stream), eventType, preprocess)
</script> </script>
<template> <template>

View File

@ -31,7 +31,7 @@ defineProps<{
<div flex items-center flex-shrink-0 gap-x-2> <div flex items-center flex-shrink-0 gap-x-2>
<slot name="actions" /> <slot name="actions" />
<PwaBadge lg:hidden /> <PwaBadge lg:hidden />
<NavUser v-if="isMastoInitialised" /> <NavUser v-if="isHydrated" />
<NavUserSkeleton v-else /> <NavUserSkeleton v-else />
</div> </div>
</div> </div>

View File

@ -51,7 +51,7 @@ const handleFavouritedBoostedByClose = () => {
</script> </script>
<template> <template>
<template v-if="isMastoInitialised"> <template v-if="isHydrated">
<ModalDialog v-model="isSigninDialogOpen" py-4 px-8 max-w-125> <ModalDialog v-model="isSigninDialogOpen" py-4 px-8 max-w-125>
<UserSignIn /> <UserSignIn />
</ModalDialog> </ModalDialog>

View File

@ -10,7 +10,7 @@ const moreMenuVisible = ref(false)
class="after-content-empty after:(h-[calc(100%+0.5px)] w-0.1px pointer-events-none)" class="after-content-empty after:(h-[calc(100%+0.5px)] w-0.1px pointer-events-none)"
> >
<!-- These weird styles above are used for scroll locking, don't change it unless you know exactly what you're doing. --> <!-- These weird styles above are used for scroll locking, don't change it unless you know exactly what you're doing. -->
<template v-if="isMastoInitialised && currentUser"> <template v-if="currentUser">
<NuxtLink to="/home" :active-class="moreMenuVisible ? '' : 'text-primary'" flex flex-row items-center place-content-center h-full flex-1 @click="$scrollToTop"> <NuxtLink to="/home" :active-class="moreMenuVisible ? '' : 'text-primary'" flex flex-row items-center place-content-center h-full flex-1 @click="$scrollToTop">
<div i-ri:home-5-line /> <div i-ri:home-5-line />
</NuxtLink> </NuxtLink>
@ -24,7 +24,7 @@ const moreMenuVisible = ref(false)
<div i-ri:at-line /> <div i-ri:at-line />
</NuxtLink> </NuxtLink>
</template> </template>
<template v-if="isMastoInitialised && !currentUser"> <template v-else>
<NuxtLink :to="`/${currentServer}/explore`" :active-class="moreMenuVisible ? '' : 'text-primary'" flex flex-row items-center place-content-center h-full flex-1 @click="$scrollToTop"> <NuxtLink :to="`/${currentServer}/explore`" :active-class="moreMenuVisible ? '' : 'text-primary'" flex flex-row items-center place-content-center h-full flex-1 @click="$scrollToTop">
<div i-ri:hashtag /> <div i-ri:hashtag />
</NuxtLink> </NuxtLink>

View File

@ -29,9 +29,9 @@ const { notifications } = useNotifications()
<NavSideItem :text="$t('action.compose')" to="/compose" icon="i-ri:quill-pen-line" user-only :command="command" /> <NavSideItem :text="$t('action.compose')" to="/compose" icon="i-ri:quill-pen-line" user-only :command="command" />
<div shrink hidden sm:block mt-4 /> <div shrink hidden sm:block mt-4 />
<NavSideItem :text="$t('nav.explore')" :to="isMastoInitialised ? `/${currentServer}/explore` : '/explore'" icon="i-ri:hashtag" :command="command" /> <NavSideItem :text="$t('nav.explore')" :to="isHydrated ? `/${currentServer}/explore` : '/explore'" icon="i-ri:hashtag" :command="command" />
<NavSideItem :text="$t('nav.local')" :to="isMastoInitialised ? `/${currentServer}/public/local` : '/public/local'" icon="i-ri:group-2-line " :command="command" /> <NavSideItem :text="$t('nav.local')" :to="isHydrated ? `/${currentServer}/public/local` : '/public/local'" icon="i-ri:group-2-line " :command="command" />
<NavSideItem :text="$t('nav.federated')" :to="isMastoInitialised ? `/${currentServer}/public` : '/public'" icon="i-ri:earth-line" :command="command" /> <NavSideItem :text="$t('nav.federated')" :to="isHydrated ? `/${currentServer}/public` : '/public'" icon="i-ri:earth-line" :command="command" />
<div shrink hidden sm:block mt-4 /> <div shrink hidden sm:block mt-4 />
<NavSideItem :text="$t('nav.settings')" to="/settings" icon="i-ri:settings-3-line" :command="command" /> <NavSideItem :text="$t('nav.settings')" to="/settings" icon="i-ri:settings-3-line" :command="command" />

View File

@ -29,7 +29,7 @@ useCommand({
}) })
let activeClass = $ref('text-primary') let activeClass = $ref('text-primary')
onMastoInit(async () => { onHydrated(async () => {
// TODO: force NuxtLink to reevaluate, we now we are in this route though, so we should force it to active // TODO: force NuxtLink to reevaluate, we now we are in this route though, so we should force it to active
// we don't have currentServer defined until later // we don't have currentServer defined until later
activeClass = '' activeClass = ''
@ -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(() => !isHydrated.value || (props.userOnly && !currentUser.value))
const noUserVisual = computed(() => isMastoInitialised.value && props.userOnly && !currentUser.value) const noUserVisual = computed(() => isHydrated.value && props.userOnly && !currentUser.value)
</script> </script>
<template> <template>

View File

@ -1,5 +1,5 @@
<template> <template>
<VDropdown v-if="isMastoInitialised && currentUser" sm:hidden> <VDropdown v-if="isHydrated && currentUser" sm:hidden>
<div style="-webkit-touch-callout: none;"> <div style="-webkit-touch-callout: none;">
<AccountAvatar <AccountAvatar
ref="avatar" ref="avatar"

View File

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

View File

@ -110,7 +110,7 @@ defineExpose({
</script> </script>
<template> <template>
<div v-if="isMastoInitialised && currentUser" flex="~ col gap-4" py3 px2 sm:px4> <div v-if="isHydrated && currentUser" 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

@ -39,7 +39,7 @@ const toggleTranslation = async () => {
isLoading.translation = false isLoading.translation = false
} }
const masto = useMasto() const { client } = $(useMasto())
const getPermalinkUrl = (status: mastodon.v1.Status) => { const getPermalinkUrl = (status: mastodon.v1.Status) => {
const url = getStatusPermalinkRoute(status) const url = getStatusPermalinkRoute(status)
@ -70,7 +70,7 @@ const deleteStatus = async () => {
return return
removeCachedStatus(status.id) removeCachedStatus(status.id)
await masto.v1.statuses.remove(status.id) await client.v1.statuses.remove(status.id)
if (route.name === 'status') if (route.name === 'status')
router.back() router.back()
@ -88,7 +88,7 @@ const deleteAndRedraft = async () => {
} }
removeCachedStatus(status.id) removeCachedStatus(status.id)
await masto.v1.statuses.remove(status.id) await client.v1.statuses.remove(status.id)
await openPublishDialog('dialog', await getDraftFromStatus(status), true) await openPublishDialog('dialog', await getDraftFromStatus(status), true)
// Go to the new status, if the page is the old status // Go to the new status, if the page is the old status
@ -214,7 +214,7 @@ const showFavoritedAndBoostedBy = () => {
@click="toggleTranslation" @click="toggleTranslation"
/> />
<template v-if="isMastoInitialised && currentUser"> <template v-if="isHydrated && currentUser">
<template v-if="isAuthor"> <template v-if="isAuthor">
<CommonDropdownItem <CommonDropdownItem
:text="status.pinned ? $t('menu.unpin_on_profile') : $t('menu.pin_on_profile')" :text="status.pinned ? $t('menu.unpin_on_profile') : $t('menu.pin_on_profile')"

View File

@ -3,8 +3,10 @@ import { favouritedBoostedByStatusId } from '~/composables/dialog'
const type = ref<'favourited-by' | 'boosted-by'>('favourited-by') const type = ref<'favourited-by' | 'boosted-by'>('favourited-by')
const { client } = $(useMasto())
function load() { function load() {
return useMasto().v1.statuses[type.value === 'favourited-by' ? 'listFavouritedBy' : 'listRebloggedBy'](favouritedBoostedByStatusId.value!) return client.v1.statuses[type.value === 'favourited-by' ? 'listFavouritedBy' : 'listRebloggedBy'](favouritedBoostedByStatusId.value!)
} }
const paginator = $computed(() => load()) const paginator = $computed(() => load())

View File

@ -15,7 +15,8 @@ const expiredTimeAgo = useTimeAgo(poll.expiresAt!, timeAgoOptions)
const expiredTimeFormatted = useFormattedDateTime(poll.expiresAt!) const expiredTimeFormatted = useFormattedDateTime(poll.expiresAt!)
const { formatPercentage } = useHumanReadableNumber() const { formatPercentage } = useHumanReadableNumber()
const masto = useMasto() const { client } = $(useMasto())
async function vote(e: Event) { async function vote(e: Event) {
const formData = new FormData(e.target as HTMLFormElement) const formData = new FormData(e.target as HTMLFormElement)
const choices = formData.getAll('choices') as string[] const choices = formData.getAll('choices') as string[]
@ -30,7 +31,7 @@ async function vote(e: Event) {
poll.votersCount = (poll.votersCount || 0) + 1 poll.votersCount = (poll.votersCount || 0) + 1
cacheStatus({ ...status, poll }, undefined, true) cacheStatus({ ...status, poll }, undefined, true)
await masto.v1.polls.vote(poll.id, { choices }) await client.v1.polls.vote(poll.id, { choices })
} }
const votersCount = $computed(() => poll.votersCount ?? 0) const votersCount = $computed(() => poll.votersCount ?? 0)

View File

@ -6,7 +6,7 @@ const { status } = defineProps<{
status: mastodon.v1.Status status: mastodon.v1.Status
}>() }>()
const paginator = useMasto().v1.statuses.listHistory(status.id) const paginator = useMastoClient().v1.statuses.listHistory(status.id)
const showHistory = (edit: mastodon.v1.StatusEdit) => { const showHistory = (edit: mastodon.v1.StatusEdit) => {
openEditHistoryDialog(edit) openEditHistoryDialog(edit)

View File

@ -9,13 +9,13 @@ const emit = defineEmits<{
(event: 'change'): void (event: 'change'): void
}>() }>()
const masto = useMasto() const { client } = $(useMasto())
const toggleFollowTag = async () => { const toggleFollowTag = async () => {
if (tag.following) if (tag.following)
await masto.v1.tags.unfollow(tag.name) await client.v1.tags.unfollow(tag.name)
else else
await masto.v1.tags.follow(tag.name) await client.v1.tags.follow(tag.name)
emit('change') emit('change')
} }

View File

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
const paginator = useMasto().v1.blocks.list() const paginator = useMastoClient().v1.blocks.list()
</script> </script>
<template> <template>

View File

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
const paginator = useMasto().v1.bookmarks.list() const paginator = useMastoClient().v1.bookmarks.list()
</script> </script>
<template> <template>

View File

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
const paginator = useMasto().v1.conversations.list() const paginator = useMastoClient().v1.conversations.list()
</script> </script>
<template> <template>

View File

@ -1,9 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
const masto = useMasto() const { client } = $(useMasto())
const paginator = masto.v1.domainBlocks.list() const paginator = client.v1.domainBlocks.list()
const unblock = async (domain: string) => { const unblock = async (domain: string) => {
await masto.v1.domainBlocks.unblock(domain) await client.v1.domainBlocks.unblock(domain)
} }
</script> </script>

View File

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
const paginator = useMasto().v1.favourites.list() const paginator = useMastoClient().v1.favourites.list()
</script> </script>
<template> <template>

View File

@ -1,7 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
const paginator = useMasto().v1.timelines.listHome({ limit: 30 }) const paginator = useMastoClient().v1.timelines.listHome({ limit: 30 })
const stream = useMasto().v1.stream.streamUser() const stream = $(useStreaming(client => client.v1.stream.streamUser()))
onBeforeUnmount(() => stream?.then(s => s.disconnect()))
</script> </script>
<template> <template>

View File

@ -1,11 +1,10 @@
<script setup lang="ts"> <script setup lang="ts">
// Default limit is 20 notifications, and servers are normally caped to 30 // Default limit is 20 notifications, and servers are normally caped to 30
const paginator = useMasto().v1.notifications.list({ limit: 30, types: ['mention'] }) const paginator = useMastoClient().v1.notifications.list({ limit: 30, types: ['mention'] })
const stream = $(useStreaming(client => client.v1.stream.streamUser()))
const { clearNotifications } = useNotifications() const { clearNotifications } = useNotifications()
onActivated(clearNotifications) onActivated(clearNotifications)
const stream = useMasto().v1.stream.streamUser()
</script> </script>
<template> <template>

View File

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
const paginator = useMasto().v1.mutes.list() const paginator = useMastoClient().v1.mutes.list()
</script> </script>
<template> <template>

View File

@ -1,11 +1,10 @@
<script setup lang="ts"> <script setup lang="ts">
// Default limit is 20 notifications, and servers are normally caped to 30 // Default limit is 20 notifications, and servers are normally caped to 30
const paginator = useMasto().v1.notifications.list({ limit: 30 }) const paginator = useMastoClient().v1.notifications.list({ limit: 30 })
const stream = useStreaming(client => client.v1.stream.streamUser())
const { clearNotifications } = useNotifications() const { clearNotifications } = useNotifications()
onActivated(clearNotifications) onActivated(clearNotifications)
const stream = useMasto().v1.stream.streamUser()
</script> </script>
<template> <template>

View File

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

View File

@ -1,7 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
const paginator = useMasto().v1.timelines.listPublic({ limit: 30 }) const paginator = useMastoClient().v1.timelines.listPublic({ limit: 30 })
const stream = useMasto().v1.stream.streamPublicTimeline() const stream = useStreaming(client => client.v1.stream.streamPublicTimeline())
onBeforeUnmount(() => stream.then(s => s.disconnect()))
</script> </script>
<template> <template>

View File

@ -1,7 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
const paginator = useMasto().v1.timelines.listPublic({ limit: 30, local: true }) const paginator = useMastoClient().v1.timelines.listPublic({ limit: 30, local: true })
const stream = useMasto().v1.stream.streamCommunityTimeline() const stream = useStreaming(client => client.v1.stream.streamCommunityTimeline())
onBeforeUnmount(() => stream.then(s => s.disconnect()))
</script> </script>
<template> <template>

View File

@ -2,14 +2,13 @@
import type { UserLogin } from '~/types' import type { UserLogin } from '~/types'
const all = useUsers() const all = useUsers()
const router = useRouter() const router = useRouter()
const masto = useMasto()
const switchUser = (user: UserLogin) => { const clickUser = (user: UserLogin) => {
if (user.account.id === currentUser.value?.account.id) if (user.account.id === currentUser.value?.account.id)
router.push(getAccountRoute(user.account)) router.push(getAccountRoute(user.account))
else else
masto.loginTo(user) switchUser(user)
} }
</script> </script>
@ -24,7 +23,7 @@ const switchUser = (user: UserLogin) => {
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="clickUser(user)"
> >
<AccountAvatar w-13 h-13 :account="user.account" square /> <AccountAvatar w-13 h-13 :account="user.account" square />
</button> </button>

View File

@ -28,7 +28,7 @@ async function oauth() {
server = server.split('/')[0] server = server.split('/')[0]
try { try {
location.href = await (globalThis.$fetch as any)(`/api/${server || publicServer.value}/login`, { const url = await (globalThis.$fetch as any)(`/api/${server || publicServer.value}/login`, {
method: 'POST', method: 'POST',
body: { body: {
force_login: users.value.some(u => u.server === server), force_login: users.value.some(u => u.server === server),
@ -36,6 +36,7 @@ async function oauth() {
lang: userSettings.value.language, lang: userSettings.value.language,
}, },
}) })
location.href = url
} }
catch (err) { catch (err) {
console.error(err) console.error(err)

View File

@ -1,6 +1,6 @@
<template> <template>
<div p8 lg:flex="~ col gap2" hidden> <div p8 lg:flex="~ col gap2" hidden>
<p v-if="isMastoInitialised" text-sm> <p v-if="isHydrated" text-sm>
<i18n-t keypath="user.sign_in_notice_title"> <i18n-t keypath="user.sign_in_notice_title">
<strong>{{ currentServer }}</strong> <strong>{{ currentServer }}</strong>
</i18n-t> </i18n-t>

View File

@ -15,12 +15,11 @@ const sorted = computed(() => {
}) })
const router = useRouter() const router = useRouter()
const masto = useMasto() const clickUser = (user: UserLogin) => {
const switchUser = (user: UserLogin) => {
if (user.account.id === currentUser.value?.account.id) if (user.account.id === currentUser.value?.account.id)
router.push(getAccountRoute(user.account)) router.push(getAccountRoute(user.account))
else else
masto.loginTo(user) switchUser(user)
} }
</script> </script>
@ -31,7 +30,7 @@ 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="clickUser(user)"
> >
<AccountInfo :account="user.account" :hover-card="false" square /> <AccountInfo :account="user.account" :hover-card="false" square />
<div flex-auto /> <div flex-auto />
@ -45,7 +44,7 @@ const switchUser = (user: UserLogin) => {
@click="openSigninDialog" @click="openSigninDialog"
/> />
<CommonDropdownItem <CommonDropdownItem
v-if="isMastoInitialised && currentUser" v-if="isHydrated && currentUser"
:text="$t('user.sign_out_account', [getFullHandle(currentUser.account)])" :text="$t('user.sign_out_account', [getFullHandle(currentUser.account)])"
icon="i-ri:logout-box-line rtl-flip" icon="i-ri:logout-box-line rtl-flip"
@click="signout" @click="signout"

View File

@ -24,7 +24,7 @@ export function fetchStatus(id: string, force = false): Promise<mastodon.v1.Stat
const cached = cache.get(key) const cached = cache.get(key)
if (cached && !force) if (cached && !force)
return cached return cached
const promise = useMasto().v1.statuses.fetch(id) const promise = useMastoClient().v1.statuses.fetch(id)
.then((status) => { .then((status) => {
cacheStatus(status) cacheStatus(status)
return status return status
@ -44,7 +44,7 @@ export function fetchAccountById(id?: string | null): Promise<mastodon.v1.Accoun
if (cached) if (cached)
return cached return cached
const domain = currentInstance.value?.uri const domain = currentInstance.value?.uri
const promise = useMasto().v1.accounts.fetch(id) const promise = useMastoClient().v1.accounts.fetch(id)
.then((r) => { .then((r) => {
if (r.acct && !r.acct.includes('@') && domain) if (r.acct && !r.acct.includes('@') && domain)
r.acct = `${r.acct}@${domain}` r.acct = `${r.acct}@${domain}`
@ -64,7 +64,7 @@ export async function fetchAccountByHandle(acct: string): Promise<mastodon.v1.Ac
if (cached) if (cached)
return cached return cached
const domain = currentInstance.value?.uri const domain = currentInstance.value?.uri
const account = useMasto().v1.accounts.lookup({ acct }) const account = useMastoClient().v1.accounts.lookup({ acct })
.then((r) => { .then((r) => {
if (r.acct && !r.acct.includes('@') && domain) if (r.acct && !r.acct.includes('@') && domain)
r.acct = `${r.acct}@${domain}` r.acct = `${r.acct}@${domain}`

View File

@ -337,7 +337,7 @@ export const provideGlobalCommands = () => {
icon: 'i-ri:user-shared-line', icon: 'i-ri:user-shared-line',
onActivate() { onActivate() {
masto.loginTo(user) loginTo(masto, user)
}, },
}))) })))
useCommand({ useCommand({

View File

@ -19,8 +19,8 @@ export async function updateCustomEmojis() {
if (Date.now() - currentCustomEmojis.value.lastUpdate < TTL) if (Date.now() - currentCustomEmojis.value.lastUpdate < TTL)
return return
const masto = useMasto() const { client } = $(useMasto())
const emojis = await masto.v1.customEmojis.list() const emojis = await client.v1.customEmojis.list()
Object.assign(currentCustomEmojis.value, { Object.assign(currentCustomEmojis.value, {
lastUpdate: Date.now(), lastUpdate: Date.now(),
emojis, emojis,

View File

@ -1,11 +1,115 @@
import type { ElkMasto } from '~/types' import type { Pausable } from '@vueuse/core'
import type { CreateClientParams, WsEvents, mastodon } from 'masto'
import { createClient, fetchV1Instance } from 'masto'
import type { Ref } from 'vue'
import type { ElkInstance } from '../users'
import type { Mutable } from '~/types/utils'
import type { UserLogin } from '~/types'
export const createMasto = () => {
let client = $shallowRef<mastodon.Client>(undefined as never)
let params = $ref<Mutable<CreateClientParams>>()
const canStreaming = $computed(() => !!params?.streamingApiUrl)
const setParams = (newParams: Partial<CreateClientParams>) => {
const p = { ...params, ...newParams } as CreateClientParams
client = createClient(p)
params = p
}
return {
client: $$(client),
params: readonly($$(params)),
canStreaming: $$(canStreaming),
setParams,
}
}
export type ElkMasto = ReturnType<typeof createMasto>
export const useMasto = () => useNuxtApp().$masto as ElkMasto export const useMasto = () => useNuxtApp().$masto as ElkMasto
export const useMastoClient = () => useMasto().client.value
export const isMastoInitialised = computed(() => process.client && useMasto().loggedIn.value) export function mastoLogin(masto: ElkMasto, user: Pick<UserLogin, 'server' | 'token'>) {
const { setParams } = $(masto)
export const onMastoInit = (cb: () => unknown) => { const server = user.server
watchOnce(isMastoInitialised, () => { const url = `https://${server}`
cb() const instance: ElkInstance = reactive(getInstanceCache(server) || { uri: server })
}, { immediate: isMastoInitialised.value }) setParams({
url,
accessToken: user?.token,
disableVersionCheck: true,
streamingApiUrl: instance?.urls?.streamingApi,
})
fetchV1Instance({ url }).then((newInstance) => {
Object.assign(instance, newInstance)
setParams({
streamingApiUrl: newInstance.urls.streamingApi,
})
instances.value[server] = newInstance
})
return instance
}
interface UseStreamingOptions<Controls extends boolean> {
/**
* Expose more controls
*
* @default false
*/
controls?: Controls
/**
* Connect on calling
*
* @default true
*/
immediate?: boolean
}
export function useStreaming(
cb: (client: mastodon.Client) => Promise<WsEvents>,
options: UseStreamingOptions<true>,
): { stream: Ref<Promise<WsEvents> | undefined> } & Pausable
export function useStreaming(
cb: (client: mastodon.Client) => Promise<WsEvents>,
options?: UseStreamingOptions<false>,
): Ref<Promise<WsEvents> | undefined>
export function useStreaming(
cb: (client: mastodon.Client) => Promise<WsEvents>,
{ immediate = true, controls }: UseStreamingOptions<boolean> = {},
): ({ stream: Ref<Promise<WsEvents> | undefined> } & Pausable) | Ref<Promise<WsEvents> | undefined> {
const { canStreaming, client } = useMasto()
const isActive = ref(immediate)
const stream = ref<Promise<WsEvents>>()
function pause() {
isActive.value = false
}
function resume() {
isActive.value = true
}
function cleanup() {
if (stream.value) {
stream.value.then(s => s.disconnect()).catch(() => Promise.resolve())
stream.value = undefined
}
}
watchEffect(() => {
cleanup()
if (canStreaming.value && isActive.value)
stream.value = cb(client.value)
})
tryOnBeforeUnmount(() => isActive.value = false)
if (controls)
return { stream, isActive, pause, resume }
else
return stream
} }

View File

@ -4,7 +4,8 @@ const notifications = reactive<Record<string, undefined | [Promise<WsEvents>, st
export const useNotifications = () => { export const useNotifications = () => {
const id = currentUser.value?.account.id const id = currentUser.value?.account.id
const masto = useMasto()
const { client, canStreaming } = $(useMasto())
async function clearNotifications() { async function clearNotifications() {
if (!id || !notifications[id]) if (!id || !notifications[id])
@ -12,24 +13,26 @@ export const useNotifications = () => {
const lastReadId = notifications[id]![1][0] const lastReadId = notifications[id]![1][0]
notifications[id]![1] = [] notifications[id]![1] = []
await masto.v1.markers.create({ await client.v1.markers.create({
notifications: { lastReadId }, notifications: { lastReadId },
}) })
} }
async function connect(): Promise<void> { async function connect(): Promise<void> {
if (!isMastoInitialised.value || !id || notifications[id] || !currentUser.value?.token) if (!isHydrated.value || !id || notifications[id] || !currentUser.value?.token)
return return
const stream = masto.v1.stream.streamUser() await until($$(canStreaming)).toBe(true)
const stream = client.v1.stream.streamUser()
notifications[id] = [stream, []] notifications[id] = [stream, []]
stream.then(s => s.on('notification', (n) => { stream.then(s => s.on('notification', (n) => {
if (notifications[id]) if (notifications[id])
notifications[id]![1].unshift(n.id) notifications[id]![1].unshift(n.id)
})) }))
const position = await masto.v1.markers.fetch({ timeline: ['notifications'] }) const position = await client.v1.markers.fetch({ timeline: ['notifications'] })
const paginator = masto.v1.notifications.list({ limit: 30 }) const paginator = client.v1.notifications.list({ limit: 30 })
do { do {
const result = await paginator.next() const result = await paginator.next()
if (!result.done && result.value.length) { if (!result.done && result.value.length) {
@ -53,10 +56,10 @@ export const useNotifications = () => {
} }
watch(currentUser, disconnect) watch(currentUser, disconnect)
if (isMastoInitialised.value)
onHydrated(() => {
connect() connect()
else })
watchOnce(isMastoInitialised, connect)
return { return {
notifications: computed(() => id ? notifications[id]?.[1].length ?? 0 : 0), notifications: computed(() => id ? notifications[id]?.[1].length ?? 0 : 0),

View File

@ -12,7 +12,7 @@ export const usePublish = (options: {
}) => { }) => {
const { expanded, isUploading, initialDraft } = $(options) const { expanded, isUploading, initialDraft } = $(options)
let { draft, isEmpty } = $(options.draftState) let { draft, isEmpty } = $(options.draftState)
const masto = useMasto() const { client } = $(useMasto())
let isSending = $ref(false) let isSending = $ref(false)
const isExpanded = $ref(false) const isExpanded = $ref(false)
@ -51,9 +51,9 @@ export const usePublish = (options: {
let status: mastodon.v1.Status let status: mastodon.v1.Status
if (!draft.editingStatus) if (!draft.editingStatus)
status = await masto.v1.statuses.create(payload) status = await client.v1.statuses.create(payload)
else else
status = await masto.v1.statuses.update(draft.editingStatus.id, payload) status = await client.v1.statuses.update(draft.editingStatus.id, payload)
if (draft.params.inReplyToId) if (draft.params.inReplyToId)
navigateToStatus({ status }) navigateToStatus({ status })
@ -83,7 +83,7 @@ export type MediaAttachmentUploadError = [filename: string, message: string]
export const useUploadMediaAttachment = (draftRef: Ref<Draft>) => { export const useUploadMediaAttachment = (draftRef: Ref<Draft>) => {
const draft = $(draftRef) const draft = $(draftRef)
const masto = useMasto() const { client } = $(useMasto())
const { t } = useI18n() const { t } = useI18n()
let isUploading = $ref<boolean>(false) let isUploading = $ref<boolean>(false)
@ -96,12 +96,12 @@ export const useUploadMediaAttachment = (draftRef: Ref<Draft>) => {
failedAttachments = [] failedAttachments = []
// TODO: display some kind of message if too many media are selected // TODO: display some kind of message if too many media are selected
// DONE // DONE
const limit = currentInstance.value!.configuration.statuses.maxMediaAttachments || 4 const limit = currentInstance.value!.configuration?.statuses.maxMediaAttachments || 4
for (const file of files.slice(0, limit)) { for (const file of files.slice(0, limit)) {
if (draft.attachments.length < limit) { if (draft.attachments.length < limit) {
isExceedingAttachmentLimit = false isExceedingAttachmentLimit = false
try { try {
const attachment = await masto.v1.mediaAttachments.create({ const attachment = await client.v1.mediaAttachments.create({
file, file,
}) })
draft.attachments.push(attachment) draft.attachments.push(attachment)
@ -121,7 +121,7 @@ export const useUploadMediaAttachment = (draftRef: Ref<Draft>) => {
} }
async function pickAttachments() { async function pickAttachments() {
const mimeTypes = currentInstance.value!.configuration.mediaAttachments.supportedMimeTypes const mimeTypes = currentInstance.value!.configuration?.mediaAttachments.supportedMimeTypes
const files = await fileOpen({ const files = await fileOpen({
description: 'Attachments', description: 'Attachments',
multiple: true, multiple: true,
@ -132,7 +132,7 @@ export const useUploadMediaAttachment = (draftRef: Ref<Draft>) => {
async function setDescription(att: mastodon.v1.MediaAttachment, description: string) { async function setDescription(att: mastodon.v1.MediaAttachment, description: string) {
att.description = description att.description = description
await masto.v1.mediaAttachments.update(att.id, { description: att.description }) await client.v1.mediaAttachments.update(att.id, { description: att.description })
} }
function removeAttachment(index: number) { function removeAttachment(index: number) {

View File

@ -27,7 +27,7 @@ export function useRelationship(account: mastodon.v1.Account): Ref<mastodon.v1.R
async function fetchRelationships() { async function fetchRelationships() {
const requested = Array.from(requestedRelationships.entries()).filter(([, r]) => !r.value) const requested = Array.from(requestedRelationships.entries()).filter(([, r]) => !r.value)
const relationships = await useMasto().v1.accounts.fetchRelationships(requested.map(([id]) => id)) const relationships = await useMastoClient().v1.accounts.fetchRelationships(requested.map(([id]) => id))
for (let i = 0; i < requested.length; i++) for (let i = 0; i < requested.length; i++)
requested[i][1].value = relationships[i] requested[i][1].value = relationships[i]
} }

View File

@ -22,7 +22,7 @@ export type SearchResult = HashTagSearchResult | AccountSearchResult | StatusSea
export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOptions = {}) { export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOptions = {}) {
const done = ref(false) const done = ref(false)
const masto = useMasto() const { client } = $(useMasto())
const loading = ref(false) const loading = ref(false)
const accounts = ref<AccountSearchResult[]>([]) const accounts = ref<AccountSearchResult[]>([])
const hashtags = ref<HashTagSearchResult[]>([]) const hashtags = ref<HashTagSearchResult[]>([])
@ -59,11 +59,11 @@ export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOpt
} }
watch(() => resolveUnref(query), () => { watch(() => resolveUnref(query), () => {
loading.value = !!(q && isMastoInitialised.value) loading.value = !!(q && isHydrated.value)
}) })
debouncedWatch(() => resolveUnref(query), async () => { debouncedWatch(() => resolveUnref(query), async () => {
if (!q || !isMastoInitialised.value) if (!q || !isHydrated.value)
return return
loading.value = true loading.value = true
@ -72,7 +72,7 @@ export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOpt
* 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.v2.search({ paginator = client.v2.search({
q, q,
...resolveUnref(options), ...resolveUnref(options),
resolve: !!currentUser.value, resolve: !!currentUser.value,
@ -87,7 +87,7 @@ export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOpt
}, { debounce: 300 }) }, { debounce: 300 })
const next = async () => { const next = async () => {
if (!q || !isMastoInitialised.value || !paginator) if (!q || !isHydrated.value || !paginator)
return return
loading.value = true loading.value = true

View File

@ -9,7 +9,7 @@ export interface StatusActionsProps {
export function useStatusActions(props: StatusActionsProps) { export function useStatusActions(props: StatusActionsProps) {
let status = $ref<mastodon.v1.Status>({ ...props.status }) let status = $ref<mastodon.v1.Status>({ ...props.status })
const masto = useMasto() const { client } = $(useMasto())
watch( watch(
() => props.status, () => props.status,
@ -61,7 +61,7 @@ export function useStatusActions(props: StatusActionsProps) {
const toggleReblog = () => toggleStatusAction( const toggleReblog = () => toggleStatusAction(
'reblogged', 'reblogged',
() => masto.v1.statuses[status.reblogged ? 'unreblog' : 'reblog'](status.id).then((res) => { () => client.v1.statuses[status.reblogged ? 'unreblog' : 'reblog'](status.id).then((res) => {
if (status.reblogged) if (status.reblogged)
// returns the original status // returns the original status
return res.reblog! return res.reblog!
@ -72,23 +72,23 @@ export function useStatusActions(props: StatusActionsProps) {
const toggleFavourite = () => toggleStatusAction( const toggleFavourite = () => toggleStatusAction(
'favourited', 'favourited',
() => masto.v1.statuses[status.favourited ? 'unfavourite' : 'favourite'](status.id), () => client.v1.statuses[status.favourited ? 'unfavourite' : 'favourite'](status.id),
'favouritesCount', 'favouritesCount',
) )
const toggleBookmark = () => toggleStatusAction( const toggleBookmark = () => toggleStatusAction(
'bookmarked', 'bookmarked',
() => masto.v1.statuses[status.bookmarked ? 'unbookmark' : 'bookmark'](status.id), () => client.v1.statuses[status.bookmarked ? 'unbookmark' : 'bookmark'](status.id),
) )
const togglePin = async () => toggleStatusAction( const togglePin = async () => toggleStatusAction(
'pinned', 'pinned',
() => masto.v1.statuses[status.pinned ? 'unpin' : 'pin'](status.id), () => client.v1.statuses[status.pinned ? 'unpin' : 'pin'](status.id),
) )
const toggleMute = async () => toggleStatusAction( const toggleMute = async () => toggleStatusAction(
'muted', 'muted',
() => masto.v1.statuses[status.muted ? 'unmute' : 'mute'](status.id), () => client.v1.statuses[status.muted ? 'unmute' : 'mute'](status.id),
) )
return { return {

View File

@ -1,9 +1,10 @@
import type { Paginator, WsEvents, mastodon } from 'masto' import type { Paginator, WsEvents, mastodon } from 'masto'
import type { Ref } from 'vue'
import type { PaginatorState } from '~/types' import type { PaginatorState } from '~/types'
export function usePaginator<T, P, U = T>( export function usePaginator<T, P, U = T>(
_paginator: Paginator<T[], P>, _paginator: Paginator<T[], P>,
stream?: Promise<WsEvents>, stream: Ref<Promise<WsEvents> | undefined>,
eventType: 'notification' | 'update' = 'update', eventType: 'notification' | 'update' = 'update',
preprocess: (items: (T | U)[]) => U[] = items => items as unknown as U[], preprocess: (items: (T | U)[]) => U[] = items => items as unknown as U[],
buffer = 10, buffer = 10,
@ -13,7 +14,7 @@ export function usePaginator<T, P, U = T>(
// so clone it // so clone it
const paginator = _paginator.clone() const paginator = _paginator.clone()
const state = ref<PaginatorState>(isMastoInitialised.value ? 'idle' : 'loading') const state = ref<PaginatorState>(isHydrated.value ? 'idle' : 'loading')
const items = ref<U[]>([]) const items = ref<U[]>([])
const nextItems = ref<U[]>([]) const nextItems = ref<U[]>([])
const prevItems = ref<T[]>([]) const prevItems = ref<T[]>([])
@ -29,37 +30,39 @@ export function usePaginator<T, P, U = T>(
prevItems.value = [] prevItems.value = []
} }
stream?.then((s) => { watch(stream, (stream) => {
s.on(eventType, (status) => { stream?.then((s) => {
if ('uri' in status) s.on(eventType, (status) => {
if ('uri' in status)
cacheStatus(status, undefined, true)
const index = prevItems.value.findIndex((i: any) => i.id === status.id)
if (index >= 0)
prevItems.value.splice(index, 1)
prevItems.value.unshift(status as any)
})
// TODO: update statuses
s.on('status.update', (status) => {
cacheStatus(status, undefined, true) cacheStatus(status, undefined, true)
const index = prevItems.value.findIndex((i: any) => i.id === status.id) const data = items.value as mastodon.v1.Status[]
if (index >= 0) const index = data.findIndex(s => s.id === status.id)
prevItems.value.splice(index, 1) if (index >= 0)
data[index] = status
})
prevItems.value.unshift(status as any) s.on('delete', (id) => {
removeCachedStatus(id)
const data = items.value as mastodon.v1.Status[]
const index = data.findIndex(s => s.id === id)
if (index >= 0)
data.splice(index, 1)
})
}) })
}, { immediate: true })
// TODO: update statuses
s.on('status.update', (status) => {
cacheStatus(status, undefined, true)
const data = items.value as mastodon.v1.Status[]
const index = data.findIndex(s => s.id === status.id)
if (index >= 0)
data[index] = status
})
s.on('delete', (id) => {
removeCachedStatus(id)
const data = items.value as mastodon.v1.Status[]
const index = data.findIndex(s => s.id === id)
if (index >= 0)
data.splice(index, 1)
})
})
async function loadNext() { async function loadNext() {
if (state.value !== 'idle') if (state.value !== 'idle')
@ -101,8 +104,8 @@ export function usePaginator<T, P, U = T>(
bound.update() bound.update()
}, 1000) }, 1000)
if (!isMastoInitialised.value) { if (!isHydrated.value) {
onMastoInit(() => { onHydrated(() => {
state.value = 'idle' state.value = 'idle'
loadNext() loadNext()
}) })

View File

@ -132,5 +132,5 @@ async function sendSubscriptionToBackend(
data, data,
} }
return await useMasto().v1.webPushSubscriptions.create(params) return await useMastoClient().v1.webPushSubscriptions.create(params)
} }

View File

@ -13,7 +13,7 @@ const supportsPushNotifications = typeof window !== 'undefined'
&& 'getKey' in PushSubscription.prototype && 'getKey' in PushSubscription.prototype
export const usePushManager = () => { export const usePushManager = () => {
const masto = useMasto() const { client } = $(useMasto())
const isSubscribed = ref(false) const isSubscribed = ref(false)
const notificationPermission = ref<PermissionState | undefined>( const notificationPermission = ref<PermissionState | undefined>(
Notification.permission === 'denied' Notification.permission === 'denied'
@ -168,7 +168,7 @@ export const usePushManager = () => {
if (policyChanged) if (policyChanged)
await subscribe(data, policy, true) await subscribe(data, policy, true)
else else
currentUser.value.pushSubscription = await masto.v1.webPushSubscriptions.update({ data }) currentUser.value.pushSubscription = await client.v1.webPushSubscriptions.update({ data })
policyChanged && await nextTick() policyChanged && await nextTick()

View File

@ -14,7 +14,7 @@ export const MentionSuggestion: Partial<SuggestionOptions> = {
if (query.length === 0) if (query.length === 0)
return [] return []
const results = await useMasto().v2.search({ q: query, type: 'accounts', limit: 25, resolve: true }) const results = await useMastoClient().v2.search({ q: query, type: 'accounts', limit: 25, resolve: true })
return results.accounts return results.accounts
}, },
render: createSuggestionRenderer(TiptapMentionList), render: createSuggestionRenderer(TiptapMentionList),
@ -27,7 +27,7 @@ export const HashtagSuggestion: Partial<SuggestionOptions> = {
if (query.length === 0) if (query.length === 0)
return [] return []
const results = await useMasto().v2.search({ const results = await useMastoClient().v2.search({
q: query, q: query,
type: 'hashtags', type: 'hashtags',
limit: 25, limit: 25,

View File

@ -1,8 +1,9 @@
import { createClient, fetchV1Instance } from 'masto'
import type { mastodon } from 'masto' import type { mastodon } from 'masto'
import type { EffectScope, Ref } from 'vue' import type { EffectScope, Ref } from 'vue'
import type { MaybeComputedRef, RemovableRef } from '@vueuse/core' import type { MaybeComputedRef, RemovableRef } from '@vueuse/core'
import type { ElkMasto, UserLogin } from '~/types' import type { ElkMasto } from './masto/masto'
import type { UserLogin } from '~/types'
import type { Overwrite } from '~/types/utils'
import { import {
DEFAULT_POST_CHARS_LIMIT, DEFAULT_POST_CHARS_LIMIT,
STORAGE_KEY_CURRENT_USER, STORAGE_KEY_CURRENT_USER,
@ -41,9 +42,12 @@ const initializeUsers = async (): Promise<Ref<UserLogin[]> | RemovableRef<UserLo
} }
const users = await initializeUsers() const users = await initializeUsers()
const instances = useLocalStorage<Record<string, mastodon.v1.Instance>>(STORAGE_KEY_SERVERS, mock ? mock.server : {}, { deep: true }) export const instances = useLocalStorage<Record<string, mastodon.v1.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 : '')
export type ElkInstance = Partial<mastodon.v1.Instance> & { uri: string }
export const getInstanceCache = (server: string): mastodon.v1.Instance | undefined => instances.value[server]
export const currentUser = computed<UserLogin | undefined>(() => { export const currentUser = computed<UserLogin | undefined>(() => {
if (currentUserId.value) { if (currentUserId.value) {
const user = users.value.find(user => user.account?.id === currentUserId.value) const user = users.value.find(user => user.account?.id === currentUserId.value)
@ -54,9 +58,9 @@ export const currentUser = computed<UserLogin | undefined>(() => {
return users.value[0] return users.value[0]
}) })
const publicInstance = ref<mastodon.v1.Instance | null>(null) const publicInstance = ref<ElkInstance | null>(null)
export const currentInstance = computed<null | mastodon.v1.Instance>(() => currentUser.value ? instances.value[currentUser.value.server] ?? null : publicInstance.value) export const currentInstance = computed<null | ElkInstance>(() => currentUser.value ? instances.value[currentUser.value.server] ?? null : publicInstance.value)
export const isGlitchEdition = computed(() => currentInstance.value?.version.includes('+glitch')) export const isGlitchEdition = computed(() => currentInstance.value?.version?.includes('+glitch'))
export const publicServer = ref('') export const publicServer = ref('')
export const currentServer = computed<string>(() => currentUser.value?.server || publicServer.value) export const currentServer = computed<string>(() => currentUser.value?.server || publicServer.value)
@ -102,91 +106,63 @@ export const useUsers = () => users
export const useSelfAccount = (user: MaybeComputedRef<mastodon.v1.Account | undefined>) => export const useSelfAccount = (user: MaybeComputedRef<mastodon.v1.Account | undefined>) =>
computed(() => currentUser.value && resolveUnref(user)?.id === currentUser.value.account.id) computed(() => currentUser.value && resolveUnref(user)?.id === currentUser.value.account.id)
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?: mastodon.v1.AccountCredentials }) { export async function loginTo(masto: ElkMasto, user: Overwrite<UserLogin, { account?: mastodon.v1.AccountCredentials }>) {
const route = useRoute() const { client } = $(masto)
const router = useRouter() const instance = mastoLogin(masto, user)
const server = user?.server || route.params.server as string || publicServer.value
const url = `https://${server}`
const instance = await fetchV1Instance({
url,
})
const masto = createClient({
url,
streamingApiUrl: instance.urls.streamingApi,
accessToken: user?.token,
disableVersionCheck: true,
})
if (!user?.token) { if (!user?.token) {
publicServer.value = server publicServer.value = user.server
publicInstance.value = instance publicInstance.value = instance
return
} }
function getUser() {
return users.value.find(u => u.server === user.server && u.token === user.token)
}
const account = getUser()?.account
if (account)
currentUserId.value = account.id
const [me, pushSubscription] = await Promise.all([
fetchAccountInfo(client, user.server),
// if PWA is not enabled, don't get push subscription
useRuntimeConfig().public.pwaEnabled
// we get 404 response instead empty data
? client.v1.webPushSubscriptions.fetch().catch(() => Promise.resolve(undefined))
: Promise.resolve(undefined),
])
const existingUser = getUser()
if (existingUser) {
existingUser.account = me
existingUser.pushSubscription = pushSubscription
}
else { else {
try { users.value.push({
const [me, pushSubscription] = await Promise.all([ ...user,
masto.v1.accounts.verifyCredentials(), account: me,
// if PWA is not enabled, don't get push subscription pushSubscription,
useRuntimeConfig().public.pwaEnabled
// we get 404 response instead empty data
? masto.v1.webPushSubscriptions.fetch().catch(() => Promise.resolve(undefined))
: Promise.resolve(undefined),
])
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 (err) {
console.error(err)
await signout()
}
}
// This only cleans up the URL; page content should stay the same
if (route.path === '/signin/callback') {
await router.push('/home')
}
else if ('server' in route.params && user?.token && !useNuxtApp()._processingMiddleware) {
await router.push({
...route,
force: true,
}) })
} }
return masto currentUserId.value = me.id
} }
export function setAccountInfo(userId: string, account: mastodon.v1.AccountCredentials) { export async function fetchAccountInfo(client: mastodon.Client, server: string) {
const index = getUsersIndexByUserId(userId) const account = await client.v1.accounts.verifyCredentials()
if (index === -1)
return false
users.value[index].account = account
return true
}
export async function pullMyAccountInfo() {
const account = await useMasto().v1.accounts.verifyCredentials()
if (!account.acct.includes('@')) if (!account.acct.includes('@'))
account.acct = `${account.acct}@${currentInstance.value!.uri}` account.acct = `${account.acct}@${server}`
cacheAccount(account, server, true)
setAccountInfo(currentUserId.value, account) return account
cacheAccount(account, currentServer.value, true)
} }
export function getUsersIndexByUserId(userId: string) { export async function refreshAccountInfo() {
return users.value.findIndex(u => u.account?.id === userId) const account = await fetchAccountInfo(useMastoClient(), currentServer.value)
currentUser.value!.account = account
return account
} }
export async function removePushNotificationData(user: UserLogin, fromSWPushManager = true) { export async function removePushNotificationData(user: UserLogin, fromSWPushManager = true) {
@ -223,7 +199,23 @@ export async function removePushNotifications(user: UserLogin) {
return return
// unsubscribe push notifications // unsubscribe push notifications
await useMasto().v1.webPushSubscriptions.remove().catch(() => Promise.resolve()) await useMastoClient().v1.webPushSubscriptions.remove().catch(() => Promise.resolve())
}
export async function switchUser(user: UserLogin) {
const masto = useMasto()
await loginTo(masto, user)
// This only cleans up the URL; page content should stay the same
const route = useRoute()
const router = useRouter()
if ('server' in route.params && user?.token && !useNuxtApp()._processingMiddleware) {
await router.push({
...route,
force: true,
})
}
} }
export async function signout() { export async function signout() {
@ -258,7 +250,7 @@ export async function signout() {
if (!currentUserId.value) if (!currentUserId.value)
await useRouter().push('/') await useRouter().push('/')
await masto.loginTo(currentUser.value) loginTo(masto, currentUser.value)
} }
export function checkLogin() { export function checkLogin() {
@ -320,57 +312,3 @@ export function clearUserLocalStorage(account?: mastodon.v1.Account) {
delete value.value[id] delete value.value[id]
}) })
} }
export const createMasto = () => {
const api = shallowRef<mastodon.Client | null>(null)
const apiPromise = ref<Promise<mastodon.Client> | null>(null)
const initialised = computed(() => !!api.value)
const masto = new Proxy({} as ElkMasto, {
get(_, key: keyof ElkMasto) {
if (key === 'loggedIn')
return initialised
if (key === 'loginTo') {
return (...args: any[]): Promise<mastodon.Client> => {
return apiPromise.value = loginTo(...args).then((r) => {
api.value = r
return masto
}).catch(() => {
// Show error page when Mastodon server is down
throw createError({
fatal: true,
statusMessage: 'Could not log into account.',
})
})
}
}
if (api.value && key in api.value)
return api.value[key as keyof mastodon.Client]
if (!api.value) {
return new Proxy({}, {
get(_, subkey) {
if (typeof subkey === 'string' && subkey.startsWith('iterate')) {
return (...args: any[]) => {
let paginator: any
function next() {
paginator = paginator || (api.value as any)?.[key][subkey](...args)
return paginator.next()
}
return { next }
}
}
return (...args: any[]) => apiPromise.value?.then((r: any) => r[key][subkey](...args))
},
})
}
return undefined
},
})
return masto
}

View File

@ -6,6 +6,10 @@ import { useHead } from '#head'
export const isHydrated = ref(false) export const isHydrated = ref(false)
export const onHydrated = (cb: () => unknown) => {
watchOnce(isHydrated, () => cb(), { immediate: isHydrated.value })
}
/** /**
* ### Whether the current component is running in the background * ### Whether the current component is running in the background
* *

View File

@ -19,12 +19,9 @@ const defaultMessage = 'Something went wrong'
const message = error.message ?? errorCodes[error.statusCode!] ?? defaultMessage const message = error.message ?? errorCodes[error.statusCode!] ?? defaultMessage
const state = ref<'error' | 'reloading'>('error') const state = ref<'error' | 'reloading'>('error')
const masto = useMasto()
const reload = async () => { const reload = async () => {
state.value = 'reloading' state.value = 'reloading'
try { try {
if (!masto.loggedIn.value)
await masto.loginTo(currentUser.value)
clearError({ redirect: currentUser.value ? '/home' : `/${currentServer.value}/public/local` }) clearError({ redirect: currentUser.value ? '/home' : `/${currentServer.value}/public/local` })
} }
catch (err) { catch (err) {

View File

@ -22,7 +22,7 @@ const showUserPicker = logicAnd(
<NavTitle /> <NavTitle />
<NavSide command /> <NavSide command />
<div flex-auto /> <div flex-auto />
<div v-if="isMastoInitialised" flex flex-col> <div v-if="isHydrated" flex flex-col>
<div hidden xl:block> <div hidden xl:block>
<UserSignInEntry v-if="!currentUser" /> <UserSignInEntry v-if="!currentUser" />
</div> </div>

View File

@ -4,7 +4,7 @@ export default defineNuxtRouteMiddleware((to) => {
if (to.path === '/signin/callback') if (to.path === '/signin/callback')
return return
onMastoInit(() => { onHydrated(() => {
if (!currentUser.value) { if (!currentUser.value) {
if (to.path === '/home' && to.query['share-target'] !== undefined) if (to.path === '/home' && to.query['share-target'] !== undefined)
return navigateTo('/share-target') return navigateTo('/share-target')

View File

@ -2,23 +2,14 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
if (process.server) if (process.server)
return return
const masto = useMasto()
// Skip running middleware before masto has been initialised
if (!masto)
return
if (!('server' in to.params)) if (!('server' in to.params))
return return
const user = currentUser.value const user = currentUser.value
const masto = useMasto()
if (!user) { if (!user) {
if (from.params.server !== to.params.server) { if (from.params.server !== to.params.server)
await masto.loginTo({ loginTo(masto, { server: to.params.server as string })
server: to.params.server as string,
})
}
return return
} }
@ -49,11 +40,8 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
return getAccountRoute(account) return getAccountRoute(account)
} }
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 // If we're logged in, search for the local id the account or status corresponds to
const { accounts, statuses } = await masto.v2.search({ q: `https:/${to.fullPath}`, resolve: true, limit: 1 }) const { accounts, statuses } = await masto.client.value.v2.search({ q: `https:/${to.fullPath}`, resolve: true, limit: 1 })
if (statuses[0]) if (statuses[0])
return getStatusRoute(statuses[0]) return getStatusRoute(statuses[0])

View File

@ -15,13 +15,13 @@ const publishWidget = ref()
const { data: status, pending, refresh: refreshStatus } = useAsyncData( const { data: status, pending, refresh: refreshStatus } = useAsyncData(
`status:${id}`, `status:${id}`,
() => fetchStatus(id), () => fetchStatus(id),
{ watch: [isMastoInitialised], immediate: isMastoInitialised.value }, { watch: [isHydrated], immediate: isHydrated.value },
) )
const masto = useMasto() const { client } = $(useMasto())
const { data: context, pending: pendingContext, refresh: refreshContext } = useAsyncData( const { data: context, pending: pendingContext, refresh: refreshContext } = useAsyncData(
`context:${id}`, `context:${id}`,
async () => masto.v1.statuses.fetchContext(id), async () => client.v1.statuses.fetchContext(id),
{ watch: [isMastoInitialised], immediate: isMastoInitialised.value }, { watch: [isHydrated], immediate: isHydrated.value },
) )
const replyDraft = $computed(() => status.value ? getReplyDraft(status.value) : null) const replyDraft = $computed(() => status.value ? getReplyDraft(status.value) : null)

View File

@ -8,7 +8,7 @@ const accountName = $(computedEager(() => toShortHandle(params.account as string
const { t } = useI18n() const { t } = useI18n()
const { data: account, pending, refresh } = $(await useAsyncData(() => fetchAccountByHandle(accountName).catch(() => null), { watch: [isMastoInitialised], immediate: isMastoInitialised.value })) const { data: account, pending, refresh } = $(await useAsyncData(() => fetchAccountByHandle(accountName).catch(() => null), { immediate: process.client }))
const relationship = $computed(() => account ? useRelationship(account).value : undefined) const relationship = $computed(() => account ? useRelationship(account).value : undefined)
onReactivated(() => { onReactivated(() => {

View File

@ -6,7 +6,7 @@ const handle = $(computedEager(() => params.account as string))
definePageMeta({ name: 'account-followers' }) definePageMeta({ name: 'account-followers' })
const account = await fetchAccountByHandle(handle) const account = await fetchAccountByHandle(handle)
const paginator = account ? useMasto().v1.accounts.listFollowers(account.id, {}) : null const paginator = account ? useMastoClient().v1.accounts.listFollowers(account.id, {}) : null
const isSelf = useSelfAccount(account) const isSelf = useSelfAccount(account)

View File

@ -6,7 +6,7 @@ const handle = $(computedEager(() => params.account as string))
definePageMeta({ name: 'account-following' }) definePageMeta({ name: 'account-following' })
const account = await fetchAccountByHandle(handle) const account = await fetchAccountByHandle(handle)
const paginator = account ? useMasto().v1.accounts.listFollowing(account.id, {}) : null const paginator = account ? useMastoClient().v1.accounts.listFollowing(account.id, {}) : null
const isSelf = useSelfAccount(account) const isSelf = useSelfAccount(account)

View File

@ -8,7 +8,7 @@ const { t } = useI18n()
const account = await fetchAccountByHandle(handle) const account = await fetchAccountByHandle(handle)
const paginator = useMasto().v1.accounts.listStatuses(account.id, { limit: 30, excludeReplies: true }) const paginator = useMastoClient().v1.accounts.listStatuses(account.id, { limit: 30, excludeReplies: true })
if (account) { if (account) {
useHeadFixed({ useHeadFixed({

View File

@ -7,7 +7,7 @@ const handle = $(computedEager(() => params.account as string))
const account = await fetchAccountByHandle(handle) const account = await fetchAccountByHandle(handle)
const paginator = useMasto().v1.accounts.listStatuses(account.id, { onlyMedia: true, excludeReplies: false }) const paginator = useMastoClient().v1.accounts.listStatuses(account.id, { onlyMedia: true, excludeReplies: false })
if (account) { if (account) {
useHeadFixed({ useHeadFixed({

View File

@ -7,7 +7,7 @@ const handle = $(computedEager(() => params.account as string))
const account = await fetchAccountByHandle(handle) const account = await fetchAccountByHandle(handle)
const paginator = useMasto().v1.accounts.listStatuses(account.id, { excludeReplies: false }) const paginator = useMastoClient().v1.accounts.listStatuses(account.id, { excludeReplies: false })
if (account) { if (account) {
useHeadFixed({ useHeadFixed({

View File

@ -18,7 +18,7 @@ const tabs = $computed(() => [
{ {
to: isHydrated.value ? `/${currentServer.value}/explore/users` : '/explore/users', to: isHydrated.value ? `/${currentServer.value}/explore/users` : '/explore/users',
display: isHydrated.value ? t('tab.for_you') : '', display: isHydrated.value ? t('tab.for_you') : '',
disabled: !isMastoInitialised.value || !currentUser.value, disabled: !isHydrated.value || !currentUser.value,
}, },
] as const) ] as const)
</script> </script>
@ -35,6 +35,6 @@ const tabs = $computed(() => [
<template #header> <template #header>
<CommonRouteTabs replace :options="tabs" /> <CommonRouteTabs replace :options="tabs" />
</template> </template>
<NuxtPage v-if="isMastoInitialised" /> <NuxtPage v-if="isHydrated" />
</MainContent> </MainContent>
</template> </template>

View File

@ -3,7 +3,7 @@ import { STORAGE_KEY_HIDE_EXPLORE_POSTS_TIPS } from '~~/constants'
const { t } = useI18n() const { t } = useI18n()
const paginator = useMasto().v1.trends.listStatuses() const paginator = useMastoClient().v1.trends.listStatuses()
const hideNewsTips = useLocalStorage(STORAGE_KEY_HIDE_EXPLORE_POSTS_TIPS, false) const hideNewsTips = useLocalStorage(STORAGE_KEY_HIDE_EXPLORE_POSTS_TIPS, false)

View File

@ -3,7 +3,7 @@ import { STORAGE_KEY_HIDE_EXPLORE_NEWS_TIPS } from '~~/constants'
const { t } = useI18n() const { t } = useI18n()
const paginator = useMasto().v1.trends.listLinks() const paginator = useMastoClient().v1.trends.listLinks()
const hideNewsTips = useLocalStorage(STORAGE_KEY_HIDE_EXPLORE_NEWS_TIPS, false) const hideNewsTips = useLocalStorage(STORAGE_KEY_HIDE_EXPLORE_NEWS_TIPS, false)

View File

@ -3,8 +3,8 @@ import { STORAGE_KEY_HIDE_EXPLORE_TAGS_TIPS } from '~~/constants'
const { t } = useI18n() const { t } = useI18n()
const masto = useMasto() const { client } = $(useMasto())
const paginator = masto.v1.trends.listTags({ const paginator = client.v1.trends.listTags({
limit: 20, limit: 20,
}) })

View File

@ -2,7 +2,7 @@
const { t } = useI18n() const { t } = useI18n()
// limit: 20 is the default configuration of the official client // limit: 20 is the default configuration of the official client
const paginator = useMasto().v2.suggestions.list({ limit: 20 }) const paginator = useMastoClient().v2.suggestions.list({ limit: 20 })
useHeadFixed({ useHeadFixed({
title: () => `${t('tab.for_you')} | ${t('nav.explore')}`, title: () => `${t('tab.for_you')} | ${t('nav.explore')}`,

View File

@ -17,6 +17,6 @@ useHeadFixed({
</NuxtLink> </NuxtLink>
</template> </template>
<TimelinePublic v-if="isMastoInitialised" /> <TimelinePublic v-if="isHydrated" />
</MainContent> </MainContent>
</template> </template>

View File

@ -16,6 +16,6 @@ useHeadFixed({
</NuxtLink> </NuxtLink>
</template> </template>
<TimelinePublicLocal v-if="isMastoInitialised" /> <TimelinePublicLocal v-if="isHydrated" />
</MainContent> </MainContent>
</template> </template>

View File

@ -6,12 +6,11 @@ definePageMeta({
const params = useRoute().params const params = useRoute().params
const tagName = $(computedEager(() => params.tag as string)) const tagName = $(computedEager(() => params.tag as string))
const masto = useMasto() const { client } = $(useMasto())
const { data: tag, refresh } = $(await useAsyncData(() => masto.v1.tags.fetch(tagName), { watch: [isMastoInitialised], immediate: isMastoInitialised.value })) const { data: tag, refresh } = $(await useAsyncData(() => client.v1.tags.fetch(tagName)))
const paginator = masto.v1.timelines.listHashtag(tagName) const paginator = client.v1.timelines.listHashtag(tagName)
const stream = masto.v1.stream.streamTagTimeline(tagName) const stream = useStreaming(client => client.v1.stream.streamTagTimeline(tagName))
onBeforeUnmount(() => stream.then(s => s.disconnect()))
if (tag) { if (tag) {
useHeadFixed({ useHeadFixed({

View File

@ -16,6 +16,6 @@ useHeadFixed({
<span timeline-title-style>{{ $t('nav.blocked_users') }}</span> <span timeline-title-style>{{ $t('nav.blocked_users') }}</span>
</template> </template>
<TimelineBlocks v-if="isMastoInitialised" /> <TimelineBlocks v-if="isHydrated" />
</MainContent> </MainContent>
</template> </template>

View File

@ -19,6 +19,6 @@ useHeadFixed({
</NuxtLink> </NuxtLink>
</template> </template>
<TimelineBookmarks v-if="isMastoInitialised" /> <TimelineBookmarks v-if="isHydrated" />
</MainContent> </MainContent>
</template> </template>

View File

@ -19,6 +19,6 @@ useHeadFixed({
</NuxtLink> </NuxtLink>
</template> </template>
<TimelineConversations v-if="isMastoInitialised" /> <TimelineConversations v-if="isHydrated" />
</MainContent> </MainContent>
</template> </template>

View File

@ -16,6 +16,6 @@ useHeadFixed({
<span timeline-title-style>{{ $t('nav.blocked_domains') }}</span> <span timeline-title-style>{{ $t('nav.blocked_domains') }}</span>
</template> </template>
<TimelineDomainBlocks v-if="isMastoInitialised" /> <TimelineDomainBlocks v-if="isHydrated" />
</MainContent> </MainContent>
</template> </template>

View File

@ -19,6 +19,6 @@ useHeadFixed({
</NuxtLink> </NuxtLink>
</template> </template>
<TimelineFavourites v-if="isMastoInitialised" /> <TimelineFavourites v-if="isHydrated" />
</MainContent> </MainContent>
</template> </template>

View File

@ -6,6 +6,11 @@ definePageMeta({
alias: ['/signin/callback'], alias: ['/signin/callback'],
}) })
const route = useRoute()
const router = useRouter()
if (process.client && route.path === '/signin/callback')
router.push('/home')
const { t } = useI18n() const { t } = useI18n()
useHeadFixed({ useHeadFixed({
title: () => t('nav.home'), title: () => t('nav.home'),
@ -21,6 +26,6 @@ useHeadFixed({
</NuxtLink> </NuxtLink>
</template> </template>
<TimelineHome v-if="isMastoInitialised" /> <TimelineHome v-if="isHydrated" />
</MainContent> </MainContent>
</template> </template>

View File

@ -16,6 +16,6 @@ useHeadFixed({
<span timeline-title-style>{{ $t('nav.muted_users') }}</span> <span timeline-title-style>{{ $t('nav.muted_users') }}</span>
</template> </template>
<TimelineMutes v-if="isMastoInitialised" /> <TimelineMutes v-if="isHydrated" />
</MainContent> </MainContent>
</template> </template>

View File

@ -6,5 +6,5 @@ useHeadFixed({
</script> </script>
<template> <template>
<TimelineNotifications v-if="isMastoInitialised" /> <TimelineNotifications v-if="isHydrated" />
</template> </template>

View File

@ -6,5 +6,5 @@ useHeadFixed({
</script> </script>
<template> <template>
<TimelineMentions v-if="isMastoInitialised" /> <TimelineMentions v-if="isHydrated" />
</template> </template>

View File

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

View File

@ -17,7 +17,7 @@ useHeadFixed({
</template> </template>
<div px2 mt3> <div px2 mt3>
<SearchWidget v-if="isMastoInitialised" /> <SearchWidget v-if="isHydrated" />
</div> </div>
</MainContent> </MainContent>
</template> </template>

View File

@ -13,6 +13,8 @@ useHeadFixed({
title: () => `${t('settings.profile.appearance.title')} | ${t('nav.settings')}`, title: () => `${t('settings.profile.appearance.title')} | ${t('nav.settings')}`,
}) })
const { client } = $(useMasto())
const account = $computed(() => currentUser.value?.account) const account = $computed(() => currentUser.value?.account)
const onlineSrc = $computed(() => ({ const onlineSrc = $computed(() => ({
@ -57,7 +59,7 @@ const { submit, submitting } = submitter(async ({ dirtyFields }) => {
if (!isCanSubmit.value) if (!isCanSubmit.value)
return return
const res = await useMasto().v1.accounts.updateCredentials(dirtyFields.value as mastodon.v1.UpdateCredentialsParams) const res = await client.v1.accounts.updateCredentials(dirtyFields.value as mastodon.v1.UpdateCredentialsParams)
.then(account => ({ account })) .then(account => ({ account }))
.catch((error: Error) => ({ error })) .catch((error: Error) => ({ error }))
@ -67,18 +69,20 @@ const { submit, submitting } = submitter(async ({ dirtyFields }) => {
return return
} }
setAccountInfo(account!.id, res.account) currentUser.value!.account = res.account
reset() reset()
}) })
const refreshInfo = async () => { const refreshInfo = async () => {
if (!currentUser.value)
return
// Keep the information to be edited up to date // Keep the information to be edited up to date
await pullMyAccountInfo() await refreshAccountInfo()
if (!isDirty) if (!isDirty)
reset() reset()
} }
onMastoInit(refreshInfo) onHydrated(refreshInfo)
onReactivated(refreshInfo) onReactivated(refreshInfo)
</script> </script>

View File

@ -1,23 +1,17 @@
export default defineNuxtPlugin(async (nuxtApp) => { export default defineNuxtPlugin(() => {
const { params, query } = useRoute()
publicServer.value = params.server as string || useRuntimeConfig().public.defaultServer
const masto = createMasto() const masto = createMasto()
publicServer.value = publicServer.value || useRuntimeConfig().public.defaultServer const user = typeof query.server === 'string' && typeof query.token === 'string'
? {
server: query.server,
token: query.token,
vapidKey: typeof query.vapid_key === 'string' ? query.vapid_key : undefined,
}
: currentUser.value || { server: publicServer.value }
if (process.client) { loginTo(masto, user)
const { query } = useRoute()
const user = typeof query.server === 'string' && typeof query.token === 'string'
? {
server: query.server,
token: query.token,
vapidKey: typeof query.vapid_key === 'string' ? query.vapid_key : undefined,
}
: currentUser.value
nuxtApp.hook('app:suspense:resolve', () => {
// TODO: improve upstream to make this synchronous (delayed auth)
if (!masto.loggedIn.value)
masto.loginTo(user)
})
}
return { return {
provide: { provide: {

View File

@ -1,5 +1,4 @@
import type { mastodon } from 'masto' import type { mastodon } from 'masto'
import type { Ref } from 'vue'
import type { MarkNonNullable, Mutable } from './utils' import type { MarkNonNullable, Mutable } from './utils'
export interface AppInfo { export interface AppInfo {
@ -20,11 +19,6 @@ export interface UserLogin {
pushSubscription?: mastodon.v1.WebPushSubscription pushSubscription?: mastodon.v1.WebPushSubscription
} }
export interface ElkMasto extends mastodon.Client {
loginTo (user?: Omit<UserLogin, 'account'> & { account?: mastodon.v1.AccountCredentials }): Promise<mastodon.Client>
loggedIn: Ref<boolean>
}
export type PaginatorState = 'idle' | 'loading' | 'done' | 'error' export type PaginatorState = 'idle' | 'loading' | 'done' | 'error'
export interface GroupedNotifications { export interface GroupedNotifications {