Fix issue #42: Improve search
All checks were successful
Test / test (push) Successful in 2s

This commit is contained in:
Gitea OpenCode Agent
2026-10-14 22:39:24 +00:00
parent 4d532d10ae
commit c6656fad3a
3 changed files with 254 additions and 97 deletions

View File

@@ -1,5 +1,5 @@
<script setup>
defineProps({
const props = defineProps({
title: { type: String, default: '' },
subtitle: { type: String, default: '' },
link: { type: String, default: '' },

View File

@@ -1,24 +1,42 @@
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
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 { CreateWindow } from '~/services/Windows';
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;
@@ -51,100 +69,166 @@ function registerCreateNoteAction() {
register(action);
}
// ---- Note search ----
async function fetchNotes() {
if (!Campaign.value) return;
const campaignId = Campaign.value?._id ?? Campaign.value?.id;
// ---- 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('/note/list', { params: { campaign: campaignId } });
if (response.data.status !== 'ok') {
notes.value = [];
return;
}
notes.value = response.data.notes.map(n => ({
key: n._id,
title: n.title || 'Untitled',
date: n.date
}));
const response = await Server().get(path, { params: { campaign: campaignId.value } });
if (response.data.status !== 'ok') return [];
return response.data[key] ?? [];
} catch (err) {
notes.value = [];
return [];
}
}
function openNote(note) {
emitter.emit('push-note', note);
closeResults();
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 + command actions ----
// ---- Unified results: notes, actors, items, maps + command actions ----
function getCombinedResults(query) {
const combined = [];
const q = normalize(query);
if (query && query.trim().length > 0) {
const q = query.normalize("NFD").replace(/[\u036f]/g, "").toLowerCase().trim();
function pushMatches(list, type, getName) {
for (const data of list) {
if (q && !normalize(getName(data)).includes(q)) continue;
combined.push({ type, data });
}
}
// Filter notes that match the query text
const matchingNotes = notes.value.filter(note => {
const title = (note.title || '').normalize("NFD").replace(/[\u036f]/g, "").toLowerCase();
return title.includes(q);
});
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);
for (const note of matchingNotes) {
combined.push({ type: 'note', data: note });
}
// Search command actions
const matchedActions = searchActions(query);
for (const action of matchedActions) {
combined.push({ type: 'action', data: action });
}
} else if (query === '' || query === null) {
// Empty query - show all notes + all actions
for (const note of notes.value) {
combined.push({ type: 'note', data: note });
}
const allActions = searchActions('');
for (const action of allActions) {
combined.push({ type: 'action', data: action });
}
// 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) {
const query = event.target.value;
inputText.value = query;
inputText.value = event.target.value;
selectedIndex.value = -1;
if (!query || query.trim() === '') {
showResults.value = false;
return;
}
showResults.value = true;
}
function onFocus() {
if (notes.value.length === 0) {
fetchNotes().then(() => {
showResults.value = true;
});
} else {
showResults.value = true;
}
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(event) {
function onBlur() {
// Delay closing to allow click on results
setTimeout(() => {
closeResults();
}, 150);
}
async function onKeydown(event) {
function onKeydown(event) {
const combined = getCombinedResults(inputText.value);
if (event.key === 'ArrowDown') {
@@ -162,16 +246,9 @@ async function onKeydown(event) {
if (event.key === 'Enter') {
event.preventDefault();
if (selectedIndex.value >= 0) {
const item = combined[selectedIndex.value];
if (!item) return;
if (item.type === 'note') {
openNote(item.data);
} else if (item.type === 'action') {
executeAction(item.data.id);
closeResults();
}
openResult(combined[selectedIndex.value]);
}
return;
}
if (event.key === 'Escape') {
@@ -179,21 +256,6 @@ async function onKeydown(event) {
}
}
function onSelect(result) {
if (!result) return;
if (result.link) {
const note = notes.value.find(n => n.key === result.link);
if (note) openNote(note);
}
closeResults();
}
function handleActionSelect(actionData) {
executeAction(actionData.id);
closeResults();
}
function closeResults() {
showResults.value = false;
selectedIndex.value = -1;
@@ -231,21 +293,19 @@ onUnmounted(() => {
</div>
<div class="search-container" v-if="showResults">
<template v-if="getCombinedResults(inputText).length === 0 && inputText.trim()">
<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.data.key || item.data.id) + '-' + index"
:title="item.type === 'note' ? item.data.title : item.data.label"
:subtitle="item.type === 'action' ? item.data.description : ''"
:link="item.type === 'note' ? item.data.key : null"
:icon="item.type === 'action' ? PlusIcon : ''"
: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 }"
@select="onSelect"
@click.stop.prevent="() => { if (item.type === 'note') openNote(item.data); else handleActionSelect(item.data); }"
@click.stop.prevent="openResult(item)"
/>
</div>
</div>