Merge branch 'master' into ai/issue-44
Some checks failed
Test / test (push) Failing after 2s

This commit is contained in:
2026-10-15 10:39:41 +00:00
3 changed files with 254 additions and 97 deletions

View File

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

View File

@@ -1,24 +1,42 @@
<script setup> <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 SearchIcon from 'pixelarticons/svg/search.svg'
import PlusIcon from 'pixelarticons/svg/plus.svg' import PlusIcon from 'pixelarticons/svg/plus.svg'
import NoteSearchResult from './SearchResult.vue'; import NoteSearchResult from './SearchResult.vue';
import Server from '~/services/Server'; import Server from '~/services/Server';
import { emitter } from '~/services/Emitter'; 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 { register, search as searchActions, execute as executeAction } from '~/services/ActionRegistry';
import { useCampaignService } from '~/services/Campaign.js'; import { useCampaignService } from '~/services/Campaign.js';
const { Campaign } = useCampaignService(); const { Campaign } = useCampaignService();
const { t } = useI18n();
const inputText = ref(''); const inputText = ref('');
// Everything the palette searches: the campaign's notes, actors, items and maps.
const notes = ref([]); const notes = ref([]);
const actors = ref([]);
const items = ref([]);
const maps = ref([]);
const showResults = ref(false); const showResults = ref(false);
const selectedIndex = ref(-1); const selectedIndex = ref(-1);
const focusInput = ref(null); 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 ---- // ---- Keyboard shortcut to open search ----
function globalKeydown(e) { function globalKeydown(e) {
const modKey = e.metaKey || e.ctrlKey; const modKey = e.metaKey || e.ctrlKey;
@@ -51,100 +69,166 @@ function registerCreateNoteAction() {
register(action); register(action);
} }
// ---- Note search ---- // ---- Campaign entries to search ----
async function fetchNotes() { // The same accent- and case-insensitive normalisation the action filter uses, so a match is
if (!Campaign.value) return; // never hidden by how the name was written.
function normalize(text) {
const campaignId = Campaign.value?._id ?? Campaign.value?.id; return (text || '').normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
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 => ({
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, key: n._id,
title: n.title || 'Untitled', title: n.title || 'Untitled',
date: n.date date: n.date
})); }));
} catch (err) { actors.value = fetchedActors;
notes.value = []; items.value = fetchedItems;
} maps.value = fetchedMaps;
} }
function openNote(note) { // ---- Unified results: notes, actors, items, maps + command actions ----
emitter.emit('push-note', note);
closeResults();
}
// ---- Unified results: notes + command actions ----
function getCombinedResults(query) { function getCombinedResults(query) {
const combined = []; const combined = [];
const q = normalize(query);
if (query && query.trim().length > 0) { function pushMatches(list, type, getName) {
const q = query.normalize("NFD").replace(/[\u036f]/g, "").toLowerCase().trim(); for (const data of list) {
if (q && !normalize(getName(data)).includes(q)) continue;
// Filter notes that match the query text combined.push({ type, data });
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 });
} }
// Search command actions pushMatches(notes.value, 'note', n => n.title);
const matchedActions = searchActions(query); pushMatches(actors.value, 'actor', a => a.name);
for (const action of matchedActions) { 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 }); 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; return combined;
} }
// ---- Input handling ---- // Each result type renders like the sidebar row of that entry: the section's icon and name.
function onInput(event) { const resultIcons = {
const query = event.target.value; note: '/icons/iconoir/regular/book.svg',
inputText.value = query; actor: '/icons/iconoir/regular/user.svg',
selectedIndex.value = -1; item: '/icons/iconoir/regular/box.svg',
map: '/icons/iconoir/regular/map.svg'
};
if (!query || query.trim() === '') { function resultTitle(item) {
showResults.value = false; if (item.type === 'action') return item.data.label;
return; 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; showResults.value = true;
} }
function onFocus() { function onFocus() {
if (notes.value.length === 0) {
fetchNotes().then(() => {
showResults.value = true; showResults.value = true;
}); // Foundry keeps syncing entries into the campaign in the background: refresh every time the
} else { // palette is opened so it never offers stale results.
showResults.value = true; if (campaignId.value) fetchSearchEntries();
}
} }
function onBlur(event) { function onBlur() {
// Delay closing to allow click on results // Delay closing to allow click on results
setTimeout(() => { setTimeout(() => {
closeResults(); closeResults();
}, 150); }, 150);
} }
async function onKeydown(event) { function onKeydown(event) {
const combined = getCombinedResults(inputText.value); const combined = getCombinedResults(inputText.value);
if (event.key === 'ArrowDown') { if (event.key === 'ArrowDown') {
@@ -162,16 +246,9 @@ async function onKeydown(event) {
if (event.key === 'Enter') { if (event.key === 'Enter') {
event.preventDefault(); event.preventDefault();
if (selectedIndex.value >= 0) { if (selectedIndex.value >= 0) {
const item = combined[selectedIndex.value]; openResult(combined[selectedIndex.value]);
if (!item) return;
if (item.type === 'note') {
openNote(item.data);
} else if (item.type === 'action') {
executeAction(item.data.id);
closeResults();
}
} }
return;
} }
if (event.key === 'Escape') { 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() { function closeResults() {
showResults.value = false; showResults.value = false;
selectedIndex.value = -1; selectedIndex.value = -1;
@@ -231,21 +293,19 @@ onUnmounted(() => {
</div> </div>
<div class="search-container" v-if="showResults"> <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> <div class="search-empty">No results found</div>
</template> </template>
<div class="search-container-list"> <div class="search-container-list">
<NoteSearchResult <NoteSearchResult
v-for="(item, index) in getCombinedResults(inputText)" v-for="(item, index) in getCombinedResults(inputText)"
:key="(item.data.key || item.data.id) + '-' + index" :key="item.type + '-' + (item.data.key || item.data._id || item.data.id) + '-' + index"
:title="item.type === 'note' ? item.data.title : item.data.label" :title="resultTitle(item)"
:subtitle="item.type === 'action' ? item.data.description : ''" :subtitle="resultSubtitle(item)"
:link="item.type === 'note' ? item.data.key : null" :icon="resultIcon(item)"
:icon="item.type === 'action' ? PlusIcon : ''"
:class="{ selected: index === selectedIndex }" :class="{ selected: index === selectedIndex }"
@select="onSelect" @click.stop.prevent="openResult(item)"
@click.stop.prevent="() => { if (item.type === 'note') openNote(item.data); else handleActionSelect(item.data); }"
/> />
</div> </div>
</div> </div>

View 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 = \[\]/);
});