1
0
Fork 1
mirror of https://github.com/elk-zone/elk.git synced 2024-11-12 20:09:59 +00:00

refactor: inject masto instance via nuxt app (#134)

This commit is contained in:
Daniel Roe 2022-11-26 15:42:58 +00:00 committed by GitHub
parent 5c60497421
commit 39b005899e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
26 changed files with 67 additions and 48 deletions

View file

@ -11,7 +11,7 @@ let relationship = $(useRelationship(account))
async function toggleFollow() {
relationship!.following = !relationship!.following
try {
relationship = await masto.accounts[relationship!.following ? 'follow' : 'unfollow'](account.id)
relationship = await useMasto().accounts[relationship!.following ? 'follow' : 'unfollow'](account.id)
}
catch {
// TODO error handling

View file

@ -13,24 +13,24 @@ const toggleMute = async () => {
relationship!.muting = !relationship!.muting
relationship = relationship!.muting
? await masto.accounts.mute(account.id, {
? await useMasto().accounts.mute(account.id, {
// TODO support more options
})
: await masto.accounts.unmute(account.id)
: await useMasto().accounts.unmute(account.id)
}
const toggleBlockUser = async () => {
// TODO: Add confirmation
relationship!.blocking = !relationship!.blocking
relationship = await masto.accounts[relationship!.blocking ? 'block' : 'unblock'](account.id)
relationship = await useMasto().accounts[relationship!.blocking ? 'block' : 'unblock'](account.id)
}
const toggleBlockDomain = async () => {
// TODO: Add confirmation
relationship!.domainBlocking = !relationship!.domainBlocking
await masto.domainBlocks[relationship!.domainBlocking ? 'block' : 'unblock'](getServerName(account))
await useMasto().domainBlocks[relationship!.domainBlocking ? 'block' : 'unblock'](getServerName(account))
}
</script>

View file

@ -76,7 +76,7 @@ async function toggleSensitive() {
async function uploadAttachments(files: File[]) {
isUploading = true
for (const file of files) {
const attachment = await masto.mediaAttachments.create({
const attachment = await useMasto().mediaAttachments.create({
file,
})
draft.attachments.push(attachment)
@ -114,9 +114,9 @@ async function publish() {
isSending = true
if (!draft.editingStatus)
await masto.statuses.create(payload)
await useMasto().statuses.create(payload)
else
await masto.statuses.update(draft.editingStatus.id, payload)
await useMasto().statuses.update(draft.editingStatus.id, payload)
draft = getDefaultDraft({ inReplyToId })
isPublishDialogOpen.value = false

View file

@ -43,7 +43,7 @@ async function toggleStatusAction(action: Action, newStatus: Promise<Status>, co
}
const toggleReblog = () => toggleStatusAction(
'reblogged',
masto.statuses[status.reblogged ? 'unreblog' : 'reblog'](status.id).then((res) => {
useMasto().statuses[status.reblogged ? 'unreblog' : 'reblog'](status.id).then((res) => {
if (status.reblogged)
// returns the original status
return res.reblog!
@ -54,17 +54,17 @@ const toggleReblog = () => toggleStatusAction(
const toggleFavourite = () => toggleStatusAction(
'favourited',
masto.statuses[status.favourited ? 'unfavourite' : 'favourite'](status.id),
useMasto().statuses[status.favourited ? 'unfavourite' : 'favourite'](status.id),
'favouritesCount',
)
const toggleBookmark = () => toggleStatusAction(
'bookmarked',
masto.statuses[status.bookmarked ? 'unbookmark' : 'bookmark'](status.id),
useMasto().statuses[status.bookmarked ? 'unbookmark' : 'bookmark'](status.id),
)
const togglePin = async () => toggleStatusAction(
'pinned',
masto.statuses[status.pinned ? 'unpin' : 'pin'](status.id),
useMasto().statuses[status.pinned ? 'unpin' : 'pin'](status.id),
)
const { toggle: _toggleTranslation, translation, enabled: isTranslationEnabled } = useTranslation(_status)
@ -80,7 +80,7 @@ const copyLink = async () => {
const deleteStatus = async () => {
// TODO confirm to delete
await masto.statuses.remove(status.id)
await useMasto().statuses.remove(status.id)
if (route.name === '@user-post')
router.back()
@ -90,7 +90,7 @@ const deleteStatus = async () => {
const deleteAndRedraft = async () => {
// TODO confirm to delete
const { text } = await masto.statuses.remove(status.id)
const { text } = await useMasto().statuses.remove(status.id)
if (!dialogDraft.isEmpty) {
// TODO confirm to overwrite

View file

@ -5,7 +5,7 @@ const { status } = defineProps<{
status: Status
}>()
const { data: statusEdits } = useAsyncData(`status:history:${status.id}`, () => masto.statuses.fetchHistory(status.id).then(res => res.reverse()))
const { data: statusEdits } = useAsyncData(`status:history:${status.id}`, () => useMasto().statuses.fetchHistory(status.id).then(res => res.reverse()))
const showHistory = (edit: StatusEdit) => {
openEditHistoryDialog(edit)

View file

@ -19,7 +19,7 @@ export function fetchStatus(id: string): Promise<Status> {
const cached = cache.get(key)
if (cached)
return cached
const promise = masto.statuses.fetch(id)
const promise = useMasto().statuses.fetch(id)
.then((status) => {
cacheStatus(status)
return status
@ -33,7 +33,7 @@ export function fetchAccount(id: string): Promise<Account> {
const cached = cache.get(key)
if (cached)
return cached
const promise = masto.accounts.fetch(id)
const promise = useMasto().accounts.fetch(id)
.then((account) => {
cacheAccount(account, true)
return account
@ -47,7 +47,7 @@ export async function fetchAccountByName(acct: string): Promise<Account> {
const cached = cache.get(key)
if (cached)
return cached
const account = masto.accounts.lookup({ acct })
const account = useMasto().accounts.lookup({ acct })
.then((r) => {
cacheAccount(r, true)
return r

View file

@ -1,9 +1 @@
import { login } from 'masto'
import { currentUser } from './users'
import { DEFAULT_SERVER } from '~/constants'
// TODO: improve upsteam to make this synchronous (delayed auth)
export const masto = await login({
url: `https://${currentUser.value?.server || DEFAULT_SERVER}`,
accessToken: currentUser.value?.token || undefined,
})
export const useMasto = () => useNuxtApp().$masto

View file

@ -112,7 +112,7 @@ async function fetchRelationships() {
const requested = Array.from(requestedRelationships.entries())
requestedRelationships.clear()
const relationships = await masto.accounts.fetchRelationships(requested.map(([id]) => id))
const relationships = await useMasto().accounts.fetchRelationships(requested.map(([id]) => id))
for (let i = 0; i < requested.length; i++)
requested[i][1].value = relationships[i]
}

View file

@ -12,7 +12,7 @@ export const MentionSuggestion: Partial<SuggestionOptions> = {
if (query.length === 0)
return []
const mentionPaginator = masto.search({ q: query, type: 'accounts', limit: 25, resolve: true })
const mentionPaginator = useMasto().search({ q: query, type: 'accounts', limit: 25, resolve: true })
const results = await mentionPaginator.next()
return results.value.accounts

View file

@ -40,12 +40,12 @@ export async function loginTo(user: UserLogin & { account?: AccountCredentials }
url: `https://${user.server}`,
accessToken: user.token,
})
const me = await masto.accounts.verifyCredentials()
const me = await useMasto().accounts.verifyCredentials()
user.account = me
users.value.push(user)
currentUserId.value = me.id
servers.value[me.id] = await masto.instances.fetch()
servers.value[me.id] = await useMasto().instances.fetch()
await reloadPage()
return true
}

View file

@ -6,7 +6,7 @@ const id = $computed(() => route.params.status as string)
const main = ref<Component | null>(null)
const status = window.history.state?.status ?? await fetchStatus(id)
const { data: context } = useAsyncData(`context:${id}`, () => masto.statuses.fetchContext(id))
const { data: context } = useAsyncData(`context:${id}`, () => useMasto().statuses.fetchContext(id))
const unsubscribe = watch(context, async (context) => {
if (context) {
const statusElement = document.querySelector(`#status-${id}`)

View file

@ -3,7 +3,7 @@ const params = useRoute().params
const accountName = $computed(() => params.account as string)
const account = await fetchAccountByName(accountName)
const paginator = account ? masto.accounts.getFollowersIterable(account.id, {}) : null
const paginator = account ? useMasto().accounts.getFollowersIterable(account.id, {}) : null
</script>
<template>

View file

@ -3,7 +3,7 @@ const params = useRoute().params
const accountName = $computed(() => params.account as string)
const account = await fetchAccountByName(accountName)
const paginator = account ? masto.accounts.getFollowingIterable(account.id, {}) : null
const paginator = account ? useMasto().accounts.getFollowingIterable(account.id, {}) : null
</script>
<template>

View file

@ -8,8 +8,8 @@ const tabNames = ['Posts', 'Posts and replies'] as const
// Don't use local storage because it is better to default to Posts every time you visit a user's profile.
const tab = $ref('Posts')
const paginatorPosts = masto.accounts.getStatusesIterable(account.id, { excludeReplies: true })
const paginatorPostsWithReply = masto.accounts.getStatusesIterable(account.id, { excludeReplies: false })
const paginatorPosts = useMasto().accounts.getStatusesIterable(account.id, { excludeReplies: true })
const paginatorPostsWithReply = useMasto().accounts.getStatusesIterable(account.id, { excludeReplies: false })
const paginator = $computed(() => {
return tab === 'Posts' ? paginatorPosts : paginatorPostsWithReply

View file

@ -3,7 +3,7 @@ definePageMeta({
middleware: 'auth',
})
const paginator = masto.blocks.getIterator()
const paginator = useMasto().blocks.getIterator()
useHead({
title: 'Blocked users',

View file

@ -3,7 +3,7 @@ definePageMeta({
middleware: 'auth',
})
const paginator = masto.bookmarks.getIterator()
const paginator = useMasto().bookmarks.getIterator()
useHead({
title: 'Bookmarks',

View file

@ -3,7 +3,7 @@ definePageMeta({
middleware: 'auth',
})
const paginator = masto.conversations.getIterator()
const paginator = useMasto().conversations.getIterator()
useHead({
title: 'Conversations',

View file

@ -3,14 +3,14 @@ definePageMeta({
middleware: 'auth',
})
const paginator = masto.domainBlocks.getIterator()
const paginator = useMasto().domainBlocks.getIterator()
useHead({
title: 'Blocked domains',
})
const unblock = async (domain: string) => {
await masto.domainBlocks.unblock(domain)
await useMasto().domainBlocks.unblock(domain)
}
</script>

View file

@ -1,5 +1,5 @@
<script setup lang="ts">
const paginator = masto.trends.getStatuses()
const paginator = useMasto().trends.getStatuses()
useHead({
title: 'Explore',

View file

@ -3,7 +3,7 @@ definePageMeta({
middleware: 'auth',
})
const paginator = masto.favourites.getIterator()
const paginator = useMasto().favourites.getIterator()
useHead({
title: 'Favourites',

View file

@ -3,7 +3,7 @@ definePageMeta({
middleware: 'auth',
})
const paginator = masto.timelines.getHomeIterable()
const paginator = useMasto().timelines.getHomeIterable()
</script>
<template>

View file

@ -3,7 +3,7 @@ definePageMeta({
middleware: 'auth',
})
const paginator = masto.mutes.getIterator()
const paginator = useMasto().mutes.getIterator()
useHead({
title: 'Muted users',

View file

@ -9,7 +9,7 @@ const tabNames = ['All', 'Mentions'] as const
const tab = $(useLocalStorage<typeof tabNames[number]>(STORAGE_KEY_NOTIFY_TAB, 'All'))
const paginator = $computed(() => {
return masto.notifications.getIterator(tab === 'All' ? undefined : { types: ['mention'] })
return useMasto().notifications.getIterator(tab === 'All' ? undefined : { types: ['mention'] })
})
useHead({

View file

@ -3,7 +3,7 @@ definePageMeta({
middleware: 'auth',
})
const paginator = masto.accounts.getStatusesIterable(currentUser.value!.account.id, { pinned: true })
const paginator = useMasto().accounts.getStatusesIterable(currentUser.value!.account.id, { pinned: true })
useHead({
title: 'Pinned',

View file

@ -2,7 +2,7 @@
const params = useRoute().params
const tag = $computed(() => params.tag as string)
const paginator = masto.timelines.getHashtagIterable(tag)
const paginator = useMasto().timelines.getHashtagIterable(tag)
useHead({
title: `#${tag}`,

27
plugins/masto.ts Normal file
View file

@ -0,0 +1,27 @@
import { login } from 'masto'
import { currentUser } from '../composables/users'
import { DEFAULT_SERVER } from '~/constants'
export default defineNuxtPlugin(async () => {
try {
// TODO: improve upstream to make this synchronous (delayed auth)
const masto = await login({
url: `https://${currentUser.value?.server || DEFAULT_SERVER}`,
accessToken: currentUser.value?.token || undefined,
})
return {
provide: {
masto,
},
}
}
catch {
// TODO: handle error
// Show error page when Mastodon server is down
throw createError({
fatal: true,
statusMessage: 'Could not log into account.',
})
}
})