feat: search (#285)

This commit is contained in:
wheat 2022-12-17 16:35:07 -05:00 committed by GitHub
parent 5ff0900108
commit c1d1138742
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 252 additions and 6 deletions

View file

@ -0,0 +1,19 @@
<script setup lang="ts">
defineProps<{ hashtag: any }>()
</script>
<template>
<div flex flex-row items-center gap2>
<div w-12 h-12 rounded-full bg-active flex place-items-center place-content-center>
<div i-ri:hashtag text-secondary text-lg />
</div>
<div flex flex-col>
<span>
{{ hashtag.name }}
</span>
<span text-xs text-secondary>
{{ hashtag.following ? 'Following' : 'Not Following' }}
</span>
</div>
</div>
</template>

View file

@ -0,0 +1,26 @@
<script setup lang="ts">
import type { SearchResult } from './types'
const props = defineProps<{ result: SearchResult; active: boolean }>()
const el = ref<HTMLElement>()
watch(() => props.active, (active) => {
const _el = unrefElement(el)
if (active && _el)
_el.scrollIntoView({ block: 'nearest', inline: 'start' })
})
const onActivate = () => {
(document.activeElement as HTMLElement).blur()
}
</script>
<template>
<RouterLink ref="el" :to="result.to" py2 block px2 :aria-selected="active" :class="{ 'bg-active': active }" hover:bg-active @click="() => onActivate()">
<SearchHashtagInfo v-if="result.type === 'hashtag'" :hashtag="result.hashtag" />
<AccountInfo v-else-if="result.type === 'account'" :account="result.account" />
<div v-else-if="result.type === 'action'" text-center>
{{ result.action!.label }}
</div>
</RouterLink>
</template>

View file

@ -0,0 +1,13 @@
<template>
<div flex flex-col gap-2 px-4 py-3>
<div flex gap-4>
<div>
<div w-12 h-12 rounded-full class="skeleton-loading-bg" />
</div>
<div flex="~ col 1 gap-2" pb2 min-w-0>
<div flex class="skeleton-loading-bg" h-5 w-20 rounded />
<div flex class="skeleton-loading-bg" h-4 w-full rounded />
</div>
</div>
</div>
</template>

View file

@ -0,0 +1,92 @@
<script setup lang="ts">
const query = ref('')
const { accounts, hashtags, loading } = useSearch(query)
const index = ref(0)
const { t } = useI18n()
const el = ref<HTMLElement>()
const router = useRouter()
const { focused } = useFocusWithin(el)
const results = computed(() => {
if (query.value.length === 0)
return []
const results = [
...hashtags.value.slice(0, 3).map(hashtag => ({ type: 'hashtag', hashtag, to: `/tags/${hashtag.name}` })),
...accounts.value.map(account => ({ type: 'account', account, to: `/@${account.acct}` })),
// Disable until search page is implemented
// {
// type: 'action',
// to: `/search?q=${query.value}`,
// action: {
// label: `Search for ${query.value}`,
// },
// },
]
return results
})
// Reset index when results change
watch([results, focused], () => index.value = -1)
const shift = (delta: number) => index.value = (index.value + delta % results.value.length + results.value.length) % results.value.length
const activate = () => {
(document.activeElement as HTMLElement).blur()
const currentIndex = index.value
index.value = -1
if (query.value.length === 0)
return
// Disable until search page is implemented
// if (currentIndex === -1)
// router.push(`/search?q=${query.value}`)
router.push(results.value[currentIndex].to)
}
</script>
<template>
<div ref="el" relative px4 py2 group>
<div bg-base border="~ base" h10 rounded-full flex="~ row" items-center relative outline-primary outline-1 focus-within:outline transition-all transition-duration-500>
<div i-ri:search-2-line mx4 absolute pointer-events-none text-secondary mt="1px" />
<input
ref="input"
v-model="query"
h-full
pl-10
rounded-full
w-full
bg-transparent
outline="focus:none"
pr-4
:placeholder="`${t('nav_side.search')} Elk`"
pb="1px"
placeholder-text-secondary
@keydown.down.prevent="shift(1)"
@keydown.up.prevent="shift(-1)"
@keypress.enter="activate"
>
</div>
<!-- Results -->
<div p4 left-0 top-10 absolute w-full z10 group-focus-within="pointer-events-auto visible" invisible pointer-events-none>
<div w-full bg-base border="~ base" rounded max-h-100 overflow-auto py2>
<span v-if="query.length === 0" block text-center text-sm text-secondary>
{{ t('search.search_desc') }}
</span>
<template v-if="!loading">
<SearchResult v-for="(result, i) in results" :key="result.to" :active="index === parseInt(i.toString())" :result="result" :tabindex="focused ? 0 : -1" />
</template>
<div v-else>
<SearchResultSkeleton />
<SearchResultSkeleton />
<SearchResultSkeleton />
</div>
</div>
</div>
</div>
</template>

View file

@ -0,0 +1,12 @@
import type { Account } from 'masto'
export interface SearchResult {
type: 'account' | 'hashtag' | 'action'
to: string
label?: string
account?: Account
hashtag?: any
action?: {
label: string
}
}

68
composables/search.ts Normal file
View file

@ -0,0 +1,68 @@
import type { MaybeRef } from '@vueuse/core'
import type { Account, Status } from 'masto'
export interface UseSearchOptions {
type?: MaybeRef<'accounts' | 'hashtags' | 'statuses'>
}
export function useSearch(query: MaybeRef<string>, options?: UseSearchOptions) {
let paginator = useMasto().search({ q: unref(query), type: unref(options?.type) })
const done = ref(false)
const loading = ref(false)
const statuses = ref<Status[]>([])
const accounts = ref<Account[]>([])
const hashtags = ref<any[]>([])
debouncedWatch(() => unref(query), async () => {
if (!unref(query))
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.
*/
paginator = useMasto().search({ q: unref(query), type: unref(options?.type) })
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 () => {
if (!unref(query))
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,
}
}

View file

@ -25,6 +25,7 @@
<aside class="hidden md:none lg:block w-1/4 zen-hide">
<div sticky top-0 h-screen flex="~ col">
<slot name="right">
<SearchWidget v-if="isMastoInitialised" />
<UserSignInEntry v-if="isMastoInitialised && !currentUser" />
<div v-if="isMastoInitialised && currentUser" py6 px4 w-full flex="~" items-center justify-between>
<NuxtLink

View file

@ -96,7 +96,8 @@
"home": "Startseite",
"local": "Lokale Timeline",
"notifications": "Mitteilungen",
"profile": "Profil"
"profile": "Profil",
"search": "Suche"
},
"nav_user": {
"sign_in_desc": "Melde dich an, um Profilen oder Hashtags zu folgen, Beiträge zu favorisieren, zu teilen und zu beantworten oder von deinem Konto auf einem anderen Server aus zu interagieren."
@ -135,6 +136,8 @@
"edited": "Bearbeitet: {0}"
},
"tab": {
"accounts": "Benutzer",
"hashtags": "Hashtags",
"media": "Medien",
"notifications_all": "Alle",
"notifications_mention": "Erwähnungen",

View file

@ -131,7 +131,8 @@
"home": "Home",
"local": "Local",
"notifications": "Notifications",
"profile": "Profile"
"profile": "Profile",
"search": "Search"
},
"nav_user": {
"sign_in_desc": "Sign in to follow profiles or hashtags, favourite, share and reply to posts, or interact from your account on a different server."
@ -152,6 +153,9 @@
"replying": "Replying",
"the_thread": "the thread"
},
"search": {
"search_desc": "Search for people & hashtags"
},
"state": {
"edited": "(Edited)",
"editing": "Editing",
@ -184,6 +188,7 @@
"edited": "edited {0}"
},
"tab": {
"accounts": "Accounts",
"for_you": "For you",
"hashtags": "Hashtags",
"media": "Media",

View file

@ -128,7 +128,8 @@
"home": "Inicio",
"local": "Local",
"notifications": "Notificaciones",
"profile": "Perfil"
"profile": "Perfil",
"search": "Buscar"
},
"nav_user": {
"sign_in_desc": "Inicia sesión para seguir perfiles o hashtags, marcar como favorito, compartir and responder a publicaciones, o interactuar desde tu usuario con un servidor diferente."

View file

@ -131,7 +131,8 @@
"home": "Accueil",
"local": "Local",
"notifications": "Notifications",
"profile": "Profil"
"profile": "Profil",
"search": "Rechercher"
},
"nav_user": {
"sign_in_desc": "Connectez-vous pour suivre des profils ou des hashtags, mettre en favoris, partager et répondre à des messages, ou interagir à partir de votre compte sur un autre serveur..."

View file

@ -57,7 +57,8 @@
"home": "ホーム",
"local": "ローカル",
"notifications": "通知",
"profile": "プロフィール"
"profile": "プロフィール",
"search": "検索"
},
"nav_user": {
"sign_in_desc": "サインインすると、アカウントやハッシュタグをフォローしたり、お気に入りしたり、投稿を共有したり返信するほか、異なるサーバー上のあなたのアカウントから交流できます。"
@ -75,6 +76,8 @@
"uploading": "更新中..."
},
"tab": {
"accounts": "アカウント",
"hashtags": "ハッシュタグ",
"media": "メディア",
"posts": "投稿",
"posts_with_replies": "投稿と返信"

View file

@ -130,7 +130,8 @@
"home": "主页",
"local": "本地",
"notifications": "通知",
"profile": "个人资料"
"profile": "个人资料",
"search": "搜索"
},
"nav_user": {
"sign_in_desc": "登录后可关注其他人或标签、点赞、分享和回复帖文,或与不同服务器上的账号交互。"
@ -183,6 +184,7 @@
"edited": "在 {0} 编辑了"
},
"tab": {
"accounts": "账号",
"for_you": "推荐关注",
"hashtags": "话题标签",
"media": "媒体",