Files
dragonroll/frontend/app/components/viewer/topbar/TopSearchBar.vue
Gitea OpenCode Agent c6656fad3a
All checks were successful
Test / test (push) Successful in 2s
Fix issue #42: Improve search
2026-10-14 22:39:24 +00:00

383 lines
10 KiB
Vue

<script setup>
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import SearchIcon from 'pixelarticons/svg/search.svg'
import PlusIcon from 'pixelarticons/svg/plus.svg'
import NoteSearchResult from './SearchResult.vue';
import Server from '~/services/Server';
import { emitter } from '~/services/Emitter';
import { AnchorMap } from '~/services/Content.js';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
import { register, search as searchActions, execute as executeAction } from '~/services/ActionRegistry';
import { useCampaignService } from '~/services/Campaign.js';
const { Campaign } = useCampaignService();
const { t } = useI18n();
const inputText = ref('');
// Everything the palette searches: the campaign's notes, actors, items and maps.
const notes = ref([]);
const actors = ref([]);
const items = ref([]);
const maps = ref([]);
const showResults = ref(false);
const selectedIndex = ref(-1);
const focusInput = ref(null);
const campaignId = computed(() => Campaign.value?._id ?? Campaign.value?.id ?? null);
// The lists belong to one campaign; when another one opens they are dropped and refetched.
watch(campaignId, () => {
notes.value = [];
actors.value = [];
items.value = [];
maps.value = [];
});
// ---- Keyboard shortcut to open search ----
function globalKeydown(e) {
const modKey = e.metaKey || e.ctrlKey;
if ((modKey && e.key === 'k') || (e.key === '/' && !isInputFocused())) {
e.preventDefault();
focusInput.value?.focus();
}
if (e.key === 'Escape' && showResults.value) {
closeResults();
}
}
function isInputFocused() {
const tag = document.activeElement?.tagName.toLowerCase();
return tag === 'input' || tag === 'textarea' || document.activeElement?.isContentEditable;
}
// ---- Registration of create-note action (extensibile for future commands) ----
function registerCreateNoteAction() {
const action = {
id: 'create_note',
label: 'New note',
description: 'Create a new note in the current campaign',
execute: () => {
if (!Campaign.value) return;
const campaignId = Campaign.value?._id ?? Campaign.value?.id;
CreateWindow('new_note', { campaign: campaignId });
}
};
register(action);
}
// ---- Campaign entries to search ----
// The same accent- and case-insensitive normalisation the action filter uses, so a match is
// never hidden by how the name was written.
function normalize(text) {
return (text || '').normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
}
async function fetchList(path, key) {
try {
const response = await Server().get(path, { params: { campaign: campaignId.value } });
if (response.data.status !== 'ok') return [];
return response.data[key] ?? [];
} catch (err) {
return [];
}
}
async function fetchSearchEntries() {
if (!campaignId.value) return;
// /note/all covers notes nested in folders too, unlike the sidebar's /note/list.
const [allNotes, fetchedActors, fetchedItems, fetchedMaps] = await Promise.all([
fetchList('/note/all', 'notes'),
fetchList('/actor/list', 'actors'),
fetchList('/item/list', 'items'),
fetchList('/map/list', 'maps')
]);
notes.value = allNotes.map(n => ({
key: n._id,
title: n.title || 'Untitled',
date: n.date
}));
actors.value = fetchedActors;
items.value = fetchedItems;
maps.value = fetchedMaps;
}
// ---- Unified results: notes, actors, items, maps + command actions ----
function getCombinedResults(query) {
const combined = [];
const q = normalize(query);
function pushMatches(list, type, getName) {
for (const data of list) {
if (q && !normalize(getName(data)).includes(q)) continue;
combined.push({ type, data });
}
}
pushMatches(notes.value, 'note', n => n.title);
pushMatches(actors.value, 'actor', a => a.name);
pushMatches(items.value, 'item', i => i.name);
pushMatches(maps.value, 'map', m => m.name);
// Command actions match on their label and description themselves.
for (const action of searchActions(query ?? '')) {
combined.push({ type: 'action', data: action });
}
return combined;
}
// Each result type renders like the sidebar row of that entry: the section's icon and name.
const resultIcons = {
note: '/icons/iconoir/regular/book.svg',
actor: '/icons/iconoir/regular/user.svg',
item: '/icons/iconoir/regular/box.svg',
map: '/icons/iconoir/regular/map.svg'
};
function resultTitle(item) {
if (item.type === 'action') return item.data.label;
return item.data.title || item.data.name || 'Untitled';
}
function resultSubtitle(item) {
if (item.type === 'action') return item.data.description;
return t(`campaigns.sections.${item.type}s`);
}
function resultIcon(item) {
return item.type === 'action' ? PlusIcon : resultIcons[item.type];
}
// ---- Opening a result, the way the sidebar opens that kind of entry ----
async function openNote(note) {
closeResults();
// /note/all never carries content; retrieve the note to open it with its text.
try {
const response = await Server().get(`/note/retrieve/${note.key}`);
if (response.data.status !== 'ok' || !response.data.note) return;
const full = response.data.note;
emitter.emit('push-note', { key: full._id, title: full.title, text: full.content ?? '', date: full.date });
} catch (err) {}
}
// A character or an item replaces the sheet window that is already open.
async function openActor(actor) {
closeResults();
const existingWindowId = GetFirstWindowId('character_sheet');
if (existingWindowId !== undefined) {
ClearWindow({ id: existingWindowId });
await nextTick();
}
CreateWindow('character_sheet', { actor });
}
async function openItem(item) {
closeResults();
const existingWindowId = GetFirstWindowId('item_sheet');
if (existingWindowId !== undefined) {
ClearWindow({ id: existingWindowId });
await nextTick();
}
CreateWindow('item_sheet', { item });
}
// Maps anchor on the note container instead of opening a window, like from the sidebar.
function openMap(map) {
closeResults();
const floatingViewer = GetFirstWindowId('map_viewer');
if (floatingViewer !== undefined) ClearWindow({ id: floatingViewer });
AnchorMap(map);
}
function openResult(item) {
if (!item) return;
if (item.type === 'note') openNote(item.data);
else if (item.type === 'actor') openActor(item.data);
else if (item.type === 'item') openItem(item.data);
else if (item.type === 'map') openMap(item.data);
else {
executeAction(item.data.id);
closeResults();
}
}
// ---- Input handling ----
function onInput(event) {
inputText.value = event.target.value;
selectedIndex.value = -1;
showResults.value = true;
}
function onFocus() {
showResults.value = true;
// Foundry keeps syncing entries into the campaign in the background: refresh every time the
// palette is opened so it never offers stale results.
if (campaignId.value) fetchSearchEntries();
}
function onBlur() {
// Delay closing to allow click on results
setTimeout(() => {
closeResults();
}, 150);
}
function onKeydown(event) {
const combined = getCombinedResults(inputText.value);
if (event.key === 'ArrowDown') {
event.preventDefault();
selectedIndex.value = Math.min(selectedIndex.value + 1, combined.length - 1);
return;
}
if (event.key === 'ArrowUp') {
event.preventDefault();
selectedIndex.value = Math.max(selectedIndex.value - 1, 0);
return;
}
if (event.key === 'Enter') {
event.preventDefault();
if (selectedIndex.value >= 0) {
openResult(combined[selectedIndex.value]);
}
return;
}
if (event.key === 'Escape') {
closeResults();
}
}
function closeResults() {
showResults.value = false;
selectedIndex.value = -1;
inputText.value = '';
}
// ---- Clean up register action on mount/unmount ----
onMounted(() => {
document.addEventListener('keydown', globalKeydown);
registerCreateNoteAction();
});
onUnmounted(() => {
document.removeEventListener('keydown', globalKeydown);
});
</script>
<template>
<div class="top-search-container">
<div class="top-search-box">
<img class="icon search-icon" :src="SearchIcon" alt="" aria-hidden="true">
<input
ref="focusInput"
type="text"
class="search-prompt"
placeholder="Search or press Cmd+K..."
v-model="inputText"
@input="onInput"
@focus="onFocus"
@blur="onBlur"
@keydown="onKeydown"
autocomplete="off"
spellcheck="false"
>
</div>
<div class="search-container" v-if="showResults">
<template v-if="getCombinedResults(inputText).length === 0">
<div class="search-empty">No results found</div>
</template>
<div class="search-container-list">
<NoteSearchResult
v-for="(item, index) in getCombinedResults(inputText)"
:key="item.type + '-' + (item.data.key || item.data._id || item.data.id) + '-' + index"
:title="resultTitle(item)"
:subtitle="resultSubtitle(item)"
:icon="resultIcon(item)"
:class="{ selected: index === selectedIndex }"
@click.stop.prevent="openResult(item)"
/>
</div>
</div>
</div>
</template>
<style scoped>
.top-search-container {
height: 100%;
align-items: center;
display: flex;
position: relative;
}
.top-search-box {
align-items: center;
display: flex;
background-color: var(--color-search-background);
padding: 2px;
border-radius: 5px;
}
.search-prompt {
border: none;
padding: 5px;
width: 30vw;
max-width: 400px;
background: none;
margin-left: -5px;
font-family: inherit;
}
.search-prompt:focus {
outline: none;
}
.search-icon {
padding: 5px;
filter: invert(var(--color-icon-invert));
}
.search-container {
position: absolute;
background-color: var(--color-search-background-container);
top: 45px;
margin-left: auto;
margin-right: auto;
max-width: 600px;
max-height: 400px;
overflow-y: auto;
left: 0;
right: 0;
backdrop-filter: blur(15px);
border-radius: 10px;
width: calc(30vw + 400px);
min-width: 320px;
z-index: 99999;
display: flex;
flex-direction: column;
}
.search-container-list {
display: flex;
flex-direction: column;
padding: 4px;
}
.search-empty {
padding: 16px;
text-align: center;
opacity: 0.5;
font-size: 14px;
}
</style>