Fix issue #42: Improve search
All checks were successful
Test / test (push) Successful in 2s
All checks were successful
Test / test (push) Successful in 2s
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
<script setup>
|
||||
defineProps({
|
||||
const props = defineProps({
|
||||
title: { type: String, default: '' },
|
||||
subtitle: { type: String, default: '' },
|
||||
link: { type: String, default: '' },
|
||||
|
||||
@@ -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;
|
||||
try {
|
||||
const response = await Server().get('/note/list', { params: { campaign: campaignId } });
|
||||
if (response.data.status !== 'ok') {
|
||||
notes.value = [];
|
||||
return;
|
||||
// ---- 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();
|
||||
}
|
||||
notes.value = response.data.notes.map(n => ({
|
||||
|
||||
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
|
||||
}));
|
||||
} catch (err) {
|
||||
notes.value = [];
|
||||
}
|
||||
actors.value = fetchedActors;
|
||||
items.value = fetchedItems;
|
||||
maps.value = fetchedMaps;
|
||||
}
|
||||
|
||||
function openNote(note) {
|
||||
emitter.emit('push-note', note);
|
||||
closeResults();
|
||||
}
|
||||
|
||||
// ---- 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();
|
||||
|
||||
// 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);
|
||||
});
|
||||
|
||||
for (const note of matchingNotes) {
|
||||
combined.push({ type: 'note', data: note });
|
||||
function pushMatches(list, type, getName) {
|
||||
for (const data of list) {
|
||||
if (q && !normalize(getName(data)).includes(q)) continue;
|
||||
combined.push({ type, data });
|
||||
}
|
||||
}
|
||||
|
||||
// Search command actions
|
||||
const matchedActions = searchActions(query);
|
||||
for (const action of matchedActions) {
|
||||
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 });
|
||||
}
|
||||
} 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 });
|
||||
}
|
||||
}
|
||||
|
||||
return combined;
|
||||
}
|
||||
|
||||
// ---- Input handling ----
|
||||
function onInput(event) {
|
||||
const query = event.target.value;
|
||||
inputText.value = query;
|
||||
selectedIndex.value = -1;
|
||||
// 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'
|
||||
};
|
||||
|
||||
if (!query || query.trim() === '') {
|
||||
showResults.value = false;
|
||||
return;
|
||||
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() {
|
||||
if (notes.value.length === 0) {
|
||||
fetchNotes().then(() => {
|
||||
showResults.value = true;
|
||||
});
|
||||
} else {
|
||||
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>
|
||||
|
||||
97
tests/search-everywhere.test.js
Normal file
97
tests/search-everywhere.test.js
Normal file
@@ -0,0 +1,97 @@
|
||||
// Tests for Syndria98/dragonroll#42: the Ctrl+K search only looked at notes; it now searches the
|
||||
// whole campaign — notes (nested in folders included), actors, items and maps — and selecting a
|
||||
// result opens that entry the same way the campaign sidebar opens it.
|
||||
//
|
||||
// The repository root installs no dependencies, so these checks read the search component's
|
||||
// source, like tests/map-viewer.test.js reads its window.
|
||||
//
|
||||
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||
|
||||
const searchSource = read("frontend", "app", "components", "viewer", "topbar", "TopSearchBar.vue");
|
||||
const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js");
|
||||
|
||||
test("the search fetches notes, actors, items and maps of the campaign", () => {
|
||||
for (const [route, key] of [
|
||||
["/note/all", "notes"],
|
||||
["/actor/list", "actors"],
|
||||
["/item/list", "items"],
|
||||
["/map/list", "maps"],
|
||||
]) {
|
||||
assert.ok(searchSource.includes(`'${route}'`), `expected the search to fetch ${route}`);
|
||||
assert.ok(searchSource.includes(`'${key}'`), `expected the ${route} response key '${key}' to be read`);
|
||||
}
|
||||
// every list is fetched scoped to the current campaign
|
||||
assert.match(searchSource, /params:\s*\{\s*campaign:\s*campaignId\.value\s*\}/);
|
||||
});
|
||||
|
||||
test("every entry list is matched against the query, accent- and case-insensitively", () => {
|
||||
// one shared normalisation like the action registry's own filter uses
|
||||
assert.match(searchSource, /normalize\("NFD"\)\.replace\(\/\[\\u0300-\\u036f\]\/g,\s*""\)\.toLowerCase\(\)/);
|
||||
// notes by title, actors / items / maps by name
|
||||
for (const call of [
|
||||
String.raw`pushMatches\(notes\.value,\s*'note',\s*n => n\.title\)`,
|
||||
String.raw`pushMatches\(actors\.value,\s*'actor',\s*a => a\.name\)`,
|
||||
String.raw`pushMatches\(items\.value,\s*'item',\s*i => i\.name\)`,
|
||||
String.raw`pushMatches\(maps\.value,\s*'map',\s*m => m\.name\)`,
|
||||
]) {
|
||||
assert.match(searchSource, new RegExp(call));
|
||||
}
|
||||
// command actions keep matching through the registry
|
||||
assert.match(searchSource, /searchActions\(query \?\? ''\)/);
|
||||
});
|
||||
|
||||
test("selecting a result opens each entry type the way the sidebar opens it", () => {
|
||||
// a note opens in the note column, with its content retrieved (/note/all never carries it)
|
||||
assert.match(searchSource, /get\(`\/note\/retrieve\/\$\{note\.key\}`\)/);
|
||||
assert.match(searchSource, /emitter\.emit\('push-note',\s*\{ key: full\._id, title: full\.title, text: full\.content \?\? ''/);
|
||||
// a character replaces the open sheet window
|
||||
assert.match(searchSource, /GetFirstWindowId\('character_sheet'\)/);
|
||||
assert.match(searchSource, /CreateWindow\('character_sheet',\s*\{ actor \}\)/);
|
||||
// an item replaces the open item window
|
||||
assert.match(searchSource, /GetFirstWindowId\('item_sheet'\)/);
|
||||
assert.match(searchSource, /CreateWindow\('item_sheet',\s*\{ item \}\)/);
|
||||
// a map anchors on the note container, clearing a floating viewer first
|
||||
assert.match(searchSource, /GetFirstWindowId\('map_viewer'\)/);
|
||||
assert.match(searchSource, /AnchorMap\(map\)/);
|
||||
// a command action still executes
|
||||
assert.match(searchSource, /executeAction\(item\.data\.id\)/);
|
||||
|
||||
// the windows these opens use are all registered
|
||||
for (const type of ["character_sheet", "item_sheet"]) {
|
||||
assert.match(windowDefsSource, new RegExp(`${type}:\\s*\\{`));
|
||||
}
|
||||
});
|
||||
|
||||
test("keyboard Enter and clicking share one dispatcher over the combined results", () => {
|
||||
// a single openResult handles every type, keyed off the result's type tag
|
||||
assert.match(searchSource, /function openResult\(item\)[\s\S]*item\.type === 'note'[\s\S]*item\.type === 'actor'[\s\S]*item\.type === 'item'[\s\S]*item\.type === 'map'/);
|
||||
// Enter on the selected row and a click on a row both go through it
|
||||
assert.match(searchSource, /if \(event\.key === 'Enter'\)[\s\S]*?openResult\(combined\[selectedIndex\.value\]\)/);
|
||||
assert.match(searchSource, /@click\.stop\.prevent="openResult\(item\)"/);
|
||||
});
|
||||
|
||||
test("the palette shows what each result is and stays fresh", () => {
|
||||
// every result carries its section's icon and label
|
||||
for (const icon of ["book.svg", "user.svg", "box.svg", "map.svg"]) {
|
||||
assert.ok(searchSource.includes(`/icons/iconoir/regular/${icon}`), `expected an icon per entry type (${icon})`);
|
||||
}
|
||||
assert.match(searchSource, /t\(`campaigns\.sections\.\$\{item\.type\}s`\)/);
|
||||
// the section labels come from i18n: they exist in every locale
|
||||
for (const locale of ["en", "es", "ca"]) {
|
||||
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
|
||||
for (const key of ["notes", "actors", "items", "maps"]) {
|
||||
assert.ok(campaigns.sections?.[key], `${locale} is missing campaigns.sections.${key}`);
|
||||
}
|
||||
}
|
||||
// refetched when the palette opens (Foundry syncs entries in the background)...
|
||||
assert.match(searchSource, /function onFocus\(\)[\s\S]*?fetchSearchEntries\(\)/);
|
||||
// ...and dropped when another campaign becomes the current one
|
||||
assert.match(searchSource, /watch\(campaignId,\s*\(\)\s*=>\s*\{[^}]*notes\.value = \[\][^}]*actors\.value = \[\][^}]*items\.value = \[\][^}]*maps\.value = \[\]/);
|
||||
});
|
||||
Reference in New Issue
Block a user