refactor: sync masto (#1121)

This commit is contained in:
三咲智子 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 relationship = $computed(() => props.relationship || useRelationship(account).value)
const masto = useMasto()
const { client } = $(useMasto())
async function toggleFollow() {
relationship!.following = !relationship!.following
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)
}
catch (err) {
@ -29,7 +29,7 @@ async function toggleFollow() {
async function unblock() {
relationship!.blocking = false
try {
const newRel = await masto.v1.accounts.unblock(account.id)
const newRel = await client.v1.accounts.unblock(account.id)
Object.assign(relationship!, newRel)
}
catch (err) {
@ -42,7 +42,7 @@ async function unblock() {
async function unmute() {
relationship!.muting = false
try {
const newRel = await masto.v1.accounts.unmute(account.id)
const newRel = await client.v1.accounts.unmute(account.id)
Object.assign(relationship!, newRel)
}
catch (err) {

View file

@ -6,7 +6,7 @@ const { account } = defineProps<{
command?: boolean
}>()
const masto = useMasto()
const { client } = $(useMasto())
const { t } = useI18n()
@ -46,7 +46,7 @@ function previewAvatar() {
async function toggleNotify() {
relationship!.notifying = !relationship!.notifying
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)
}
catch {

View file

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

View file

@ -42,7 +42,7 @@ defineSlots<{
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>
<template>

View file

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

View file

@ -51,7 +51,7 @@ const handleFavouritedBoostedByClose = () => {
</script>
<template>
<template v-if="isMastoInitialised">
<template v-if="isHydrated">
<ModalDialog v-model="isSigninDialogOpen" py-4 px-8 max-w-125>
<UserSignIn />
</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)"
>
<!-- 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">
<div i-ri:home-5-line />
</NuxtLink>
@ -24,7 +24,7 @@ const moreMenuVisible = ref(false)
<div i-ri:at-line />
</NuxtLink>
</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">
<div i-ri:hashtag />
</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" />
<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.local')" :to="isMastoInitialised ? `/${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.explore')" :to="isHydrated ? `/${currentServer}/explore` : '/explore'" icon="i-ri:hashtag" :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="isHydrated ? `/${currentServer}/public` : '/public'" icon="i-ri:earth-line" :command="command" />
<div shrink hidden sm:block mt-4 />
<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')
onMastoInit(async () => {
onHydrated(async () => {
// 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
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
// 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(() => !isHydrated.value || (props.userOnly && !currentUser.value))
const noUserVisual = computed(() => isHydrated.value && props.userOnly && !currentUser.value)
</script>
<template>

View file

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

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(() => !isHydrated.value || !currentUser.value)
const disabledVisual = computed(() => isHydrated.value && !currentUser.value)
</script>
<template>

View file

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

View file

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

View file

@ -15,7 +15,8 @@ const expiredTimeAgo = useTimeAgo(poll.expiresAt!, timeAgoOptions)
const expiredTimeFormatted = useFormattedDateTime(poll.expiresAt!)
const { formatPercentage } = useHumanReadableNumber()
const masto = useMasto()
const { client } = $(useMasto())
async function vote(e: Event) {
const formData = new FormData(e.target as HTMLFormElement)
const choices = formData.getAll('choices') as string[]
@ -30,7 +31,7 @@ async function vote(e: Event) {
poll.votersCount = (poll.votersCount || 0) + 1
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)

View file

@ -6,7 +6,7 @@ const { status } = defineProps<{
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) => {
openEditHistoryDialog(edit)

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,11 +1,10 @@
<script setup lang="ts">
// 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()
onActivated(clearNotifications)
const stream = useMasto().v1.stream.streamUser()
</script>
<template>

View file

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

View file

@ -1,11 +1,10 @@
<script setup lang="ts">
// 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()
onActivated(clearNotifications)
const stream = useMasto().v1.stream.streamUser()
</script>
<template>

View file

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

View file

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

View file

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

View file

@ -2,14 +2,13 @@
import type { UserLogin } from '~/types'
const all = useUsers()
const router = useRouter()
const masto = useMasto()
const switchUser = (user: UserLogin) => {
const clickUser = (user: UserLogin) => {
if (user.account.id === currentUser.value?.account.id)
router.push(getAccountRoute(user.account))
else
masto.loginTo(user)
switchUser(user)
}
</script>
@ -24,7 +23,7 @@ const switchUser = (user: UserLogin) => {
aria-label="Switch user"
:class="user.account.id === currentUser?.account.id ? '' : 'op25 grayscale'"
hover="filter-none op100"
@click="switchUser(user)"
@click="clickUser(user)"
>
<AccountAvatar w-13 h-13 :account="user.account" square />
</button>

View file

@ -28,7 +28,7 @@ async function oauth() {
server = server.split('/')[0]
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',
body: {
force_login: users.value.some(u => u.server === server),
@ -36,6 +36,7 @@ async function oauth() {
lang: userSettings.value.language,
},
})
location.href = url
}
catch (err) {
console.error(err)

View file

@ -1,6 +1,6 @@
<template>
<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">
<strong>{{ currentServer }}</strong>
</i18n-t>

View file

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

View file

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

View file

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

View file

@ -19,8 +19,8 @@ export async function updateCustomEmojis() {
if (Date.now() - currentCustomEmojis.value.lastUpdate < TTL)
return
const masto = useMasto()
const emojis = await masto.v1.customEmojis.list()
const { client } = $(useMasto())
const emojis = await client.v1.customEmojis.list()
Object.assign(currentCustomEmojis.value, {
lastUpdate: Date.now(),
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 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) => {
watchOnce(isMastoInitialised, () => {
cb()
}, { immediate: isMastoInitialised.value })
const server = user.server
const url = `https://${server}`
const instance: ElkInstance = reactive(getInstanceCache(server) || { uri: server })
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 = () => {
const id = currentUser.value?.account.id
const masto = useMasto()
const { client, canStreaming } = $(useMasto())
async function clearNotifications() {
if (!id || !notifications[id])
@ -12,24 +13,26 @@ export const useNotifications = () => {
const lastReadId = notifications[id]![1][0]
notifications[id]![1] = []
await masto.v1.markers.create({
await client.v1.markers.create({
notifications: { lastReadId },
})
}
async function connect(): Promise<void> {
if (!isMastoInitialised.value || !id || notifications[id] || !currentUser.value?.token)
if (!isHydrated.value || !id || notifications[id] || !currentUser.value?.token)
return
const stream = masto.v1.stream.streamUser()
await until($$(canStreaming)).toBe(true)
const stream = client.v1.stream.streamUser()
notifications[id] = [stream, []]
stream.then(s => s.on('notification', (n) => {
if (notifications[id])
notifications[id]![1].unshift(n.id)
}))
const position = await masto.v1.markers.fetch({ timeline: ['notifications'] })
const paginator = masto.v1.notifications.list({ limit: 30 })
const position = await client.v1.markers.fetch({ timeline: ['notifications'] })
const paginator = client.v1.notifications.list({ limit: 30 })
do {
const result = await paginator.next()
if (!result.done && result.value.length) {
@ -53,10 +56,10 @@ export const useNotifications = () => {
}
watch(currentUser, disconnect)
if (isMastoInitialised.value)
onHydrated(() => {
connect()
else
watchOnce(isMastoInitialised, connect)
})
return {
notifications: computed(() => id ? notifications[id]?.[1].length ?? 0 : 0),

View file

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

View file

@ -27,7 +27,7 @@ export function useRelationship(account: mastodon.v1.Account): Ref<mastodon.v1.R
async function fetchRelationships() {
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++)
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 = {}) {
const done = ref(false)
const masto = useMasto()
const { client } = $(useMasto())
const loading = ref(false)
const accounts = ref<AccountSearchResult[]>([])
const hashtags = ref<HashTagSearchResult[]>([])
@ -59,11 +59,11 @@ export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOpt
}
watch(() => resolveUnref(query), () => {
loading.value = !!(q && isMastoInitialised.value)
loading.value = !!(q && isHydrated.value)
})
debouncedWatch(() => resolveUnref(query), async () => {
if (!q || !isMastoInitialised.value)
if (!q || !isHydrated.value)
return
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,
* 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,
...resolveUnref(options),
resolve: !!currentUser.value,
@ -87,7 +87,7 @@ export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOpt
}, { debounce: 300 })
const next = async () => {
if (!q || !isMastoInitialised.value || !paginator)
if (!q || !isHydrated.value || !paginator)
return
loading.value = true

View file

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

View file

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

View file

@ -132,5 +132,5 @@ async function sendSubscriptionToBackend(
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
export const usePushManager = () => {
const masto = useMasto()
const { client } = $(useMasto())
const isSubscribed = ref(false)
const notificationPermission = ref<PermissionState | undefined>(
Notification.permission === 'denied'
@ -168,7 +168,7 @@ export const usePushManager = () => {
if (policyChanged)
await subscribe(data, policy, true)
else
currentUser.value.pushSubscription = await masto.v1.webPushSubscriptions.update({ data })
currentUser.value.pushSubscription = await client.v1.webPushSubscriptions.update({ data })
policyChanged && await nextTick()

View file

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

View file

@ -1,8 +1,9 @@
import { createClient, fetchV1Instance } from 'masto'
import type { mastodon } from 'masto'
import type { EffectScope, Ref } from 'vue'
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 {
DEFAULT_POST_CHARS_LIMIT,
STORAGE_KEY_CURRENT_USER,
@ -41,9 +42,12 @@ const initializeUsers = async (): Promise<Ref<UserLogin[]> | RemovableRef<UserLo
}
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 : '')
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>(() => {
if (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]
})
const publicInstance = ref<mastodon.v1.Instance | null>(null)
export const currentInstance = computed<null | mastodon.v1.Instance>(() => currentUser.value ? instances.value[currentUser.value.server] ?? null : publicInstance.value)
export const isGlitchEdition = computed(() => currentInstance.value?.version.includes('+glitch'))
const publicInstance = ref<ElkInstance | null>(null)
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 publicServer = ref('')
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>) =>
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 }) {
const route = useRoute()
const router = useRouter()
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,
})
export async function loginTo(masto: ElkMasto, user: Overwrite<UserLogin, { account?: mastodon.v1.AccountCredentials }>) {
const { client } = $(masto)
const instance = mastoLogin(masto, user)
if (!user?.token) {
publicServer.value = server
publicServer.value = user.server
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 {
try {
const [me, pushSubscription] = await Promise.all([
masto.v1.accounts.verifyCredentials(),
// if PWA is not enabled, don't get push subscription
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,
users.value.push({
...user,
account: me,
pushSubscription,
})
}
return masto
currentUserId.value = me.id
}
export function setAccountInfo(userId: string, account: mastodon.v1.AccountCredentials) {
const index = getUsersIndexByUserId(userId)
if (index === -1)
return false
users.value[index].account = account
return true
}
export async function pullMyAccountInfo() {
const account = await useMasto().v1.accounts.verifyCredentials()
export async function fetchAccountInfo(client: mastodon.Client, server: string) {
const account = await client.v1.accounts.verifyCredentials()
if (!account.acct.includes('@'))
account.acct = `${account.acct}@${currentInstance.value!.uri}`
setAccountInfo(currentUserId.value, account)
cacheAccount(account, currentServer.value, true)
account.acct = `${account.acct}@${server}`
cacheAccount(account, server, true)
return account
}
export function getUsersIndexByUserId(userId: string) {
return users.value.findIndex(u => u.account?.id === userId)
export async function refreshAccountInfo() {
const account = await fetchAccountInfo(useMastoClient(), currentServer.value)
currentUser.value!.account = account
return account
}
export async function removePushNotificationData(user: UserLogin, fromSWPushManager = true) {
@ -223,7 +199,23 @@ export async function removePushNotifications(user: UserLogin) {
return
// 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() {
@ -258,7 +250,7 @@ export async function signout() {
if (!currentUserId.value)
await useRouter().push('/')
await masto.loginTo(currentUser.value)
loginTo(masto, currentUser.value)
}
export function checkLogin() {
@ -320,57 +312,3 @@ export function clearUserLocalStorage(account?: mastodon.v1.Account) {
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 onHydrated = (cb: () => unknown) => {
watchOnce(isHydrated, () => cb(), { immediate: isHydrated.value })
}
/**
* ### 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 state = ref<'error' | 'reloading'>('error')
const masto = useMasto()
const reload = async () => {
state.value = 'reloading'
try {
if (!masto.loggedIn.value)
await masto.loginTo(currentUser.value)
clearError({ redirect: currentUser.value ? '/home' : `/${currentServer.value}/public/local` })
}
catch (err) {

View file

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

View file

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

View file

@ -2,23 +2,14 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
if (process.server)
return
const masto = useMasto()
// Skip running middleware before masto has been initialised
if (!masto)
return
if (!('server' in to.params))
return
const user = currentUser.value
const masto = useMasto()
if (!user) {
if (from.params.server !== to.params.server) {
await masto.loginTo({
server: to.params.server as string,
})
}
if (from.params.server !== to.params.server)
loginTo(masto, { server: to.params.server as string })
return
}
@ -49,11 +40,8 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
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
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])
return getStatusRoute(statuses[0])

View file

@ -15,13 +15,13 @@ const publishWidget = ref()
const { data: status, pending, refresh: refreshStatus } = useAsyncData(
`status:${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(
`context:${id}`,
async () => masto.v1.statuses.fetchContext(id),
{ watch: [isMastoInitialised], immediate: isMastoInitialised.value },
async () => client.v1.statuses.fetchContext(id),
{ watch: [isHydrated], immediate: isHydrated.value },
)
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 { 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)
onReactivated(() => {

View file

@ -6,7 +6,7 @@ const handle = $(computedEager(() => params.account as string))
definePageMeta({ name: 'account-followers' })
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)

View file

@ -6,7 +6,7 @@ const handle = $(computedEager(() => params.account as string))
definePageMeta({ name: 'account-following' })
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)

View file

@ -8,7 +8,7 @@ const { t } = useI18n()
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) {
useHeadFixed({

View file

@ -7,7 +7,7 @@ const handle = $(computedEager(() => params.account as string))
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) {
useHeadFixed({

View file

@ -7,7 +7,7 @@ const handle = $(computedEager(() => params.account as string))
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) {
useHeadFixed({

View file

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

View file

@ -3,7 +3,7 @@ import { STORAGE_KEY_HIDE_EXPLORE_POSTS_TIPS } from '~~/constants'
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)

View file

@ -3,7 +3,7 @@ import { STORAGE_KEY_HIDE_EXPLORE_NEWS_TIPS } from '~~/constants'
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)

View file

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

View file

@ -2,7 +2,7 @@
const { t } = useI18n()
// 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({
title: () => `${t('tab.for_you')} | ${t('nav.explore')}`,

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,5 +1,4 @@
import type { mastodon } from 'masto'
import type { Ref } from 'vue'
import type { MarkNonNullable, Mutable } from './utils'
export interface AppInfo {
@ -20,11 +19,6 @@ export interface UserLogin {
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 interface GroupedNotifications {