elk/composables/masto/search.ts

71 lines
2 KiB
TypeScript
Raw Normal View History

2022-12-17 21:35:07 +00:00
import type { MaybeRef } from '@vueuse/core'
2022-12-22 10:34:35 +00:00
import type { Account, Paginator, Results, SearchParams, Status } from 'masto'
2022-12-17 21:35:07 +00:00
export interface UseSearchOptions {
type?: MaybeRef<'accounts' | 'hashtags' | 'statuses'>
}
export function useSearch(query: MaybeRef<string>, options?: UseSearchOptions) {
const done = ref(false)
const masto = useMasto()
2022-12-17 21:35:07 +00:00
const loading = ref(false)
const statuses = ref<Status[]>([])
const accounts = ref<Account[]>([])
const hashtags = ref<any[]>([])
2022-12-22 10:34:35 +00:00
let paginator: Paginator<SearchParams, Results> | undefined
2022-12-17 21:35:07 +00:00
debouncedWatch(() => unref(query), async () => {
2022-12-22 10:34:35 +00:00
if (!unref(query) || !isMastoInitialised.value)
2022-12-17 21:35:07 +00:00
return
loading.value = true
/**
* 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.
*/
2023-01-03 02:14:54 +00:00
paginator = masto.search({ q: unref(query), resolve: !isGuest.value, type: unref(options?.type) })
2022-12-17 21:35:07 +00:00
const nextResults = await paginator.next()
done.value = nextResults.done || false
statuses.value = nextResults.value?.statuses || []
accounts.value = nextResults.value?.accounts || []
hashtags.value = nextResults.value?.hashtags || []
loading.value = false
}, { debounce: 500 })
const next = async () => {
2022-12-22 10:34:35 +00:00
if (!unref(query) || !isMastoInitialised.value || !paginator)
2022-12-17 21:35:07 +00:00
return
loading.value = true
const nextResults = await paginator.next()
loading.value = false
done.value = nextResults.done || false
statuses.value = [
...statuses.value,
...(nextResults.value.statuses || []),
]
accounts.value = [
...statuses.value,
...(nextResults.value.accounts || []),
]
hashtags.value = [
...statuses.value,
...(nextResults.value.statuses || []),
]
}
return {
accounts,
hashtags,
statuses,
loading: readonly(loading),
next,
}
}