504 lines
16 KiB
Vue
504 lines
16 KiB
Vue
<script setup lang="ts">
|
|
import { computed, ref, watch, onMounted, onBeforeUnmount } from 'vue'
|
|
import { breakpointsTailwind, useDebounce } from '@vueuse/core'
|
|
import EntrelineaDetail from '~/components/entrelineas/EntrelineaDetail.vue'
|
|
import { useFavoritesStore } from '~/stores/favorites'
|
|
import type { SearchHit } from '~/types'
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* CONFIGURACIÓN — lo único que necesitas tocar */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
/** Nombre de la colección de Typesense a consultar. */
|
|
const COLLECTION = 'entrelineas'
|
|
|
|
/** Campos por los que se hará el match de la búsqueda (separados por coma). */
|
|
const QUERY_BY = 'text'
|
|
|
|
/** Campos a traer en cada hit (separados por coma). Usa '*' para traerlos todos. */
|
|
const INCLUDE_FIELDS = '*'
|
|
|
|
/** Filtros adicionales (sintaxis filter_by de Typesense) a combinar con el
|
|
* filtro automático por idioma. Ej: 'page:>10', 'origin:=Nota'.
|
|
* Dejar vacío si no se necesita nada extra — el filtro por `locale` se
|
|
* añade siempre a partir del idioma actual de i18n. */
|
|
const EXTRA_FILTER_BY = ''
|
|
|
|
/** Cantidad de resultados por página. */
|
|
const PAGE_SIZE = 15
|
|
|
|
/** Identificador de la colección para el store de favoritos.
|
|
* Vale cualquier string único entre buscadores. */
|
|
const FAVORITES_COLLECTION = 'entrelineas'
|
|
|
|
// Nota: la base de ImageKit y los presets de transformación viven en
|
|
// `~/utils/entrelineaImage.ts` (auto-importado). Ahí se cambia si toca
|
|
// migrar de cuenta o ajustar tamaños.
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Estado */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
const { $i18n } = useNuxtApp()
|
|
const t = $i18n.t
|
|
|
|
// `locale` es reactivo: cambia cuando el usuario usa el switch de idiomas.
|
|
// Lo usamos para construir dinámicamente el `filter_by` de Typesense.
|
|
const { locale } = useI18n()
|
|
|
|
/** Filtro completo que mandamos a Typesense — locale dinámico + lo que el
|
|
* usuario haya puesto en `EXTRA_FILTER_BY`. Es un computed para que se
|
|
* reevalúe automáticamente cuando cambia el idioma. */
|
|
const filterBy = computed(() => {
|
|
const localeFilter = `locale:=${locale.value}`
|
|
return EXTRA_FILTER_BY ? `${localeFilter} && ${EXTRA_FILTER_BY}` : localeFilter
|
|
})
|
|
|
|
const REQUEST_TIMEOUT_MS = 15000
|
|
|
|
const query = ref('')
|
|
const debouncedQuery = useDebounce(query, 150)
|
|
|
|
const loading = ref(false)
|
|
const loadingMore = ref(false)
|
|
const errorMsg = ref<string | null>(null)
|
|
|
|
interface EntrelineaDoc {
|
|
id?: string
|
|
image?: string
|
|
link?: string
|
|
locale?: string
|
|
page?: number | string
|
|
text?: string
|
|
[key: string]: unknown
|
|
}
|
|
|
|
interface TypesenseHighlight {
|
|
field?: string
|
|
snippet?: string
|
|
value?: string
|
|
matched_tokens?: string[]
|
|
}
|
|
|
|
interface TypesenseHit {
|
|
document: EntrelineaDoc
|
|
highlights?: TypesenseHighlight[]
|
|
highlight?: Record<string, { snippet?: string, value?: string }>
|
|
text_match?: number
|
|
}
|
|
|
|
interface TypesenseSearchResponse {
|
|
found: number
|
|
out_of?: number
|
|
page?: number
|
|
hits?: TypesenseHit[]
|
|
}
|
|
|
|
const hits = ref<TypesenseHit[]>([])
|
|
const total = ref(0)
|
|
const currentPage = ref(1)
|
|
|
|
const hasMore = computed(() => hits.value.length < total.value)
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Búsqueda */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
// Usamos `documentsApi.multiSearch` (POST con body JSON) en vez de
|
|
// `searchCollection` porque el wrapper auto-generado del módulo serializa mal
|
|
// los parámetros del GET y Typesense responde con error.
|
|
const { documentsApi } = useTypesenseApi()
|
|
|
|
let searchSeq = 0
|
|
let timeoutId: ReturnType<typeof setTimeout> | null = null
|
|
|
|
async function runSearch(q: string, append = false) {
|
|
const seq = ++searchSeq
|
|
if (append) loadingMore.value = true
|
|
else loading.value = true
|
|
errorMsg.value = null
|
|
|
|
if (timeoutId) clearTimeout(timeoutId)
|
|
// Safety net: si la red se cuelga, sacamos los spinners igualmente.
|
|
timeoutId = setTimeout(() => {
|
|
if (seq === searchSeq) {
|
|
loading.value = false
|
|
loadingMore.value = false
|
|
errorMsg.value = 'La búsqueda tardó demasiado. Inténtalo de nuevo.'
|
|
}
|
|
}, REQUEST_TIMEOUT_MS)
|
|
|
|
const page = append ? currentPage.value + 1 : 1
|
|
|
|
try {
|
|
const multi = await documentsApi.multiSearch({
|
|
// Parámetros comunes a todas las búsquedas; vacío porque cada búsqueda
|
|
// ya lleva los suyos. El codegen exige el campo aunque no se use.
|
|
multiSearchParameters: {},
|
|
multiSearchSearchesParameter: {
|
|
searches: [{
|
|
// ⚠️ El serializer del módulo (MultiSearchCollectionParametersToJSON)
|
|
// espera las claves en camelCase y las traduce a snake_case antes
|
|
// de mandar el body. Si pasas snake_case directamente las ignora
|
|
// silenciosamente y Typesense recibe la búsqueda sin filtros.
|
|
collection: COLLECTION,
|
|
q: q || '*',
|
|
queryBy: QUERY_BY,
|
|
includeFields: INCLUDE_FIELDS,
|
|
filterBy: filterBy.value,
|
|
perPage: PAGE_SIZE,
|
|
page,
|
|
// Resaltado nativo de Typesense — devuelve `value` con los matches
|
|
// envueltos en <mark class="search-match"> para que estilemos en
|
|
// CSS junto con los otros buscadores (ya hay regla global).
|
|
highlightFullFields: QUERY_BY,
|
|
highlightFields: QUERY_BY,
|
|
highlightStartTag: '<mark class="search-match">',
|
|
highlightEndTag: '</mark>'
|
|
}]
|
|
}
|
|
})
|
|
|
|
// Si arrancó otra búsqueda mientras esta venía en camino, descartamos.
|
|
if (seq !== searchSeq) return
|
|
|
|
const res = (multi?.results?.[0] ?? {}) as TypesenseSearchResponse
|
|
const newHits = res?.hits ?? []
|
|
hits.value = append ? hits.value.concat(newHits) : newHits
|
|
total.value = res?.found ?? hits.value.length
|
|
currentPage.value = page
|
|
} catch (err: unknown) {
|
|
if (seq !== searchSeq) return
|
|
console.error('Typesense error', err)
|
|
errorMsg.value = (err as Error)?.message || 'Error al buscar.'
|
|
if (!append) {
|
|
hits.value = []
|
|
total.value = 0
|
|
}
|
|
} finally {
|
|
if (seq === searchSeq) {
|
|
if (timeoutId) clearTimeout(timeoutId)
|
|
loading.value = false
|
|
loadingMore.value = false
|
|
}
|
|
}
|
|
}
|
|
|
|
function loadMore() {
|
|
if (loadingMore.value || loading.value || !hasMore.value) return
|
|
runSearch(query.value, true)
|
|
}
|
|
|
|
function retry() {
|
|
runSearch(query.value, false)
|
|
}
|
|
|
|
onMounted(() => runSearch(''))
|
|
|
|
onBeforeUnmount(() => {
|
|
if (timeoutId) clearTimeout(timeoutId)
|
|
})
|
|
|
|
watch(debouncedQuery, (q) => {
|
|
hits.value = []
|
|
total.value = 0
|
|
currentPage.value = 1
|
|
runSearch(q, false)
|
|
})
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Selección / panel de detalle */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
const selected = ref<EntrelineaDoc | null>(null)
|
|
|
|
const isPanelOpen = computed({
|
|
get() { return !!selected.value },
|
|
set(v: boolean) { if (!v) selected.value = null }
|
|
})
|
|
|
|
// Si el listado se actualiza y el seleccionado ya no está, cerramos el panel.
|
|
watch(hits, () => {
|
|
if (!selected.value) return
|
|
const stillThere = hits.value.find(h => h.document.id === selected.value?.id)
|
|
if (!stillThere) selected.value = null
|
|
})
|
|
|
|
const breakpoints = useBreakpoints(breakpointsTailwind)
|
|
const isMobile = breakpoints.smaller('lg')
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Favoritos */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
const favorites = useFavoritesStore()
|
|
const toast = useToast()
|
|
|
|
/** Adapta el documento de Typesense al shape SearchHit que pide el store
|
|
* de favoritos (que se reusa entre todos los buscadores). */
|
|
function toSearchHit(doc: EntrelineaDoc): SearchHit {
|
|
const id = doc.id || ''
|
|
return {
|
|
_id: id,
|
|
id,
|
|
title: id || 'Entrelínea',
|
|
body: doc.text,
|
|
...doc
|
|
}
|
|
}
|
|
|
|
function isFav(doc: EntrelineaDoc): boolean {
|
|
if (!doc?.id) return false
|
|
return favorites.isFavorite(FAVORITES_COLLECTION, doc.id)
|
|
}
|
|
|
|
function toggleFavorite(doc: EntrelineaDoc, ev?: Event) {
|
|
// Evita que el click en la estrella abra el detalle.
|
|
ev?.stopPropagation()
|
|
if (!doc?.id) return
|
|
const wasFav = isFav(doc)
|
|
favorites.toggle(FAVORITES_COLLECTION, toSearchHit(doc))
|
|
toast.add({
|
|
title: wasFav ? 'Eliminado de tu lista' : 'Guardado en tu lista',
|
|
description: doc.id,
|
|
icon: wasFav ? 'i-lucide-bookmark-x' : 'i-lucide-bookmark-check',
|
|
color: wasFav ? 'neutral' : 'primary',
|
|
duration: 1800
|
|
})
|
|
}
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Helpers de presentación */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
/** Devuelve el snippet o value resaltado por Typesense para un campo, o null
|
|
* si no hay match. Se prefiere `snippet` (más corto, recortado alrededor del
|
|
* match) sobre `value` (campo completo) para no inflar la fila. */
|
|
function highlightedFor(hit: TypesenseHit, field: string): string | null {
|
|
const fromArr = hit.highlights?.find(h => h.field === field)
|
|
if (fromArr?.snippet) return fromArr.snippet
|
|
if (fromArr?.value) return fromArr.value
|
|
// Algunas versiones devuelven `highlight: { field: { snippet, value } }`.
|
|
const fromObj = hit.highlight?.[field]
|
|
if (fromObj?.snippet) return fromObj.snippet
|
|
if (fromObj?.value) return fromObj.value
|
|
return null
|
|
}
|
|
</script>
|
|
|
|
<template>
|
|
<UDashboardPanel
|
|
id="entrelineas-list"
|
|
:default-size="32"
|
|
:min-size="24"
|
|
:max-size="45"
|
|
resizable
|
|
>
|
|
<UDashboardNavbar :title="t('nav.between_the_lines')">
|
|
<template #leading>
|
|
<UDashboardSidebarCollapse />
|
|
</template>
|
|
|
|
<template #trailing>
|
|
<UBadge :label="total" variant="subtle" />
|
|
</template>
|
|
</UDashboardNavbar>
|
|
|
|
<div class="px-4 sm:px-6 py-3 border-b border-default">
|
|
<UInput
|
|
v-model="query"
|
|
icon="i-lucide-search"
|
|
:placeholder="t('Search.placeholder')"
|
|
:loading="loading"
|
|
size="md"
|
|
class="w-full"
|
|
/>
|
|
<p class="mt-1.5 flex items-center gap-1 text-[11px] text-dimmed">
|
|
<UIcon name="i-lucide-database" class="size-3" />
|
|
<span>
|
|
<code class="text-toned">{{ COLLECTION }}</code>
|
|
·
|
|
<code class="text-toned">{{ QUERY_BY }}</code>
|
|
·
|
|
<code class="text-toned">{{ FILTER_BY }}</code>
|
|
</span>
|
|
</p>
|
|
</div>
|
|
|
|
<UAlert
|
|
v-if="errorMsg"
|
|
:title="errorMsg"
|
|
color="error"
|
|
variant="subtle"
|
|
icon="i-lucide-triangle-alert"
|
|
class="mx-4 my-2"
|
|
:actions="[{ label: 'Reintentar', color: 'neutral', variant: 'outline', onClick: retry }]"
|
|
/>
|
|
|
|
<div class="overflow-y-auto divide-y divide-default flex-1">
|
|
<div
|
|
v-if="loading && !hits.length"
|
|
class="flex items-center justify-center gap-2 py-16 text-sm text-muted"
|
|
>
|
|
<UIcon name="i-lucide-loader-circle" class="size-4 animate-spin" />
|
|
Buscando...
|
|
</div>
|
|
|
|
<div
|
|
v-else-if="!hits.length"
|
|
class="flex flex-col items-center justify-center gap-2 py-16 text-dimmed text-sm"
|
|
>
|
|
<UIcon name="i-lucide-inbox" class="size-10" />
|
|
<p>{{ query ? `Sin coincidencias para "${query}"` : 'Sin resultados' }}</p>
|
|
</div>
|
|
|
|
<div
|
|
v-for="(hit, index) in hits"
|
|
:key="hit.document.id ?? index"
|
|
class="p-4 sm:px-6 text-sm cursor-pointer transition-colors border-b-2"
|
|
:class="[
|
|
selected && selected.id === hit.document.id
|
|
? 'bg-primary/10 text-highlighted'
|
|
: 'border-gray-200 text-toned hover:bg-primary/5'
|
|
]"
|
|
@click="selected = hit.document"
|
|
>
|
|
<div class="flex items-start justify-between gap-2 mb-1">
|
|
<!-- Título pequeño = Origin (cae al id si no hay origin para no
|
|
dejar la fila huérfana). -->
|
|
<div class="min-w-0 flex-1 flex gap-2">
|
|
<UBadge
|
|
v-if="hit.document?.studies?.[0]?.date"
|
|
:label="hit.document?.studies?.[0]?.date"
|
|
size="sm"
|
|
variant="subtle"
|
|
color="info"
|
|
class="mb-1 uppercase"
|
|
/>
|
|
<UBadge
|
|
v-if="hit.document?.page"
|
|
:label="`Página ${hit.document?.page}`"
|
|
size="sm"
|
|
variant="subtle"
|
|
color="error"
|
|
class="mb-1 uppercase"
|
|
/>
|
|
<UBadge
|
|
v-if="hit.document?.filter"
|
|
:label="hit.document?.filter"
|
|
size="sm"
|
|
variant="subtle"
|
|
color="neutral"
|
|
class="mb-1 uppercase"
|
|
/>
|
|
<UBadge
|
|
v-if="hit.document?.type"
|
|
:label="hit.document?.type"
|
|
size="sm"
|
|
variant="subtle"
|
|
color="neutral"
|
|
class="mb-1 uppercase"
|
|
/>
|
|
</div>
|
|
<UTooltip :text="isFav(hit.document) ? 'Quitar de mi lista' : 'Guardar en mi lista'">
|
|
<UButton
|
|
:icon="isFav(hit.document) ? 'i-lucide-bookmark-check' : 'i-lucide-bookmark-plus'"
|
|
:color="isFav(hit.document) ? 'primary' : 'neutral'"
|
|
variant="ghost"
|
|
size="xs"
|
|
:aria-label="isFav(hit.document) ? 'Quitar de mi lista' : 'Guardar en mi lista'"
|
|
@click="(ev: MouseEvent) => toggleFavorite(hit.document, ev)"
|
|
/>
|
|
</UTooltip>
|
|
</div>
|
|
|
|
<div class="text-sm font-semibold tracking-wide truncate mb-2">
|
|
{{ (hit.document?.studies?.[0]?.title as string) || hit.document.id || `entrelinea_${index}` }}
|
|
</div>
|
|
|
|
<!-- La entrelínea (text). Si Typesense devolvió un snippet con
|
|
highlight, lo pintamos con v-html para que aparezca el <mark>;
|
|
si no, mostramos el HTML crudo de `text`. -->
|
|
<div
|
|
v-if="highlightedFor(hit, 'text') || hit.document.text"
|
|
class="snippet-html text-sm text-toned line-clamp-3"
|
|
v-html="highlightedFor(hit, 'text') || hit.document.text"
|
|
/>
|
|
|
|
<USeparator class="my-2"/>
|
|
|
|
<div class="text-xs text-dimmed">
|
|
{{ hit.document?.origin }}
|
|
</div>
|
|
</div>
|
|
|
|
<div
|
|
v-if="hasMore && !loading"
|
|
class="p-4 flex justify-center"
|
|
>
|
|
<UButton
|
|
variant="outline"
|
|
color="neutral"
|
|
size="sm"
|
|
:loading="loadingMore"
|
|
@click="loadMore"
|
|
>
|
|
Cargar más
|
|
</UButton>
|
|
</div>
|
|
|
|
<div
|
|
v-else-if="hits.length && !hasMore && !loading"
|
|
class="py-3 text-center text-xs text-dimmed"
|
|
>
|
|
No hay más resultados
|
|
</div>
|
|
</div>
|
|
</UDashboardPanel>
|
|
|
|
<!-- Panel de detalle (escritorio) -->
|
|
<EntrelineaDetail
|
|
v-if="selected && !isMobile"
|
|
:document="selected"
|
|
:collection="FAVORITES_COLLECTION"
|
|
:highlighted-text="selected.id ? (hits.find(h => h.document.id === selected!.id)?.highlights?.find(hl => hl.field === 'text')?.value ?? null) : null"
|
|
@close="selected = null"
|
|
/>
|
|
<div v-else-if="!isMobile" class="hidden lg:flex flex-1 items-center justify-center">
|
|
<div class="flex flex-col items-center gap-2 text-dimmed">
|
|
<UIcon name="i-lucide-mouse-pointer-click" class="size-16" />
|
|
<p class="text-sm">
|
|
Selecciona una entrelínea para ver el detalle
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Panel de detalle (móvil) -->
|
|
<ClientOnly>
|
|
<USlideover v-if="isMobile" v-model:open="isPanelOpen">
|
|
<template #content>
|
|
<EntrelineaDetail
|
|
v-if="selected"
|
|
:document="selected"
|
|
:collection="FAVORITES_COLLECTION"
|
|
:highlighted-text="selected.id ? (hits.find(h => h.document.id === selected!.id)?.highlights?.find(hl => hl.field === 'text')?.value ?? null) : null"
|
|
@close="selected = null"
|
|
/>
|
|
</template>
|
|
</USlideover>
|
|
</ClientOnly>
|
|
</template>
|
|
|
|
<style scoped>
|
|
/* El estilo del <mark class="search-match"> ya está definido globalmente en
|
|
`assets/css/main.css`. Aquí sólo nos aseguramos de que las etiquetas
|
|
inline dentro del snippet (mark, strong, em, etc.) no rompan el layout. */
|
|
.snippet-html :deep(p) {
|
|
display: inline;
|
|
margin: 0;
|
|
}
|
|
.snippet-html :deep(br) {
|
|
display: none;
|
|
}
|
|
</style>
|