Files
dragonroll/frontend/app/components/partials/ContentSidebar.vue
Aran Roig 1402045001
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m51s
Foundry and discord bot
2026-10-11 22:26:29 +02:00

587 lines
22 KiB
Vue

<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useCampaignService } from '~/services/Campaign.js';
import { emitter } from '~/services/Emitter';
import Server from '~/services/Server';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
import NestedNoteList from './NestedNoteList.vue';
const { Campaign } = useCampaignService();
const { t } = useI18n();
const notes = ref([]);
const folders = ref([]);
const actors = ref([]);
const items = ref([]);
const loadingNotes = ref(false);
const loadingEntries = ref(false);
const notesError = ref('');
const entriesError = ref('');
const sidebarCollapsed = ref(false);
const activeSection = ref('notes');
const isDragOverSidebar = ref(false);
const expandedFolderIds = ref([]);
const expandedEntryIds = ref([]);
const nestedNoteListRef = ref(null);
let actorRefreshInterval;
async function handleSidebarDrop(event) {
if (activeSection.value !== 'notes') return;
const noteKey = event.dataTransfer.getData('text/plain');
if (!noteKey) return;
try {
await Server().post('/note/update', { id: noteKey, folder: null });
if (nestedNoteListRef.value) {
nestedNoteListRef.value.clearCacheAndReloadExpanded();
} else {
fetchCampaignNotes();
}
} catch (e) {}
}
function toggleExpandedFolder(folderId) {
const arr = expandedFolderIds.value;
const idx = arr.indexOf(folderId);
if (idx !== -1) {
arr.splice(idx, 1);
} else {
arr.push(folderId);
}
}
function isFolderExpanded(folderId) {
return expandedFolderIds.value.includes(folderId);
}
function openNote(note) {
emitter.emit('push-note', note);
}
function handleNoteCreated(note) {
if (!note) return;
const noteCampaignId = note.campaign?._id ?? note.campaign ?? null;
if (campaignId.value && noteCampaignId && noteCampaignId !== campaignId.value) return;
const createdNote = {
key: note._id,
title: note.title,
text: note.content ?? '',
date: note.date
};
notes.value = notes.value.filter((currentNote) => currentNote.key !== createdNote.key);
// Notes created inside a folder are added by NestedNoteList's own cache handler
const noteFolderId = note.folder?._id ?? note.folder ?? null;
if (!noteFolderId) {
notes.value.unshift(createdNote);
}
openNote(createdNote);
}
function handleNoteRenamed(data) {
const note = notes.value.find(n => n.key === data.key);
if (note) {
note.title = data.title;
}
emitter.emit('title-updated', { key: data.key, title: data.title });
}
function handleNoteDeleted(noteKey) {
notes.value = notes.value.filter(n => n.key !== noteKey);
}
function handleFolderSaved() {
fetchCampaignNotes();
}
function handleFolderDeleted(folderId) {
expandedFolderIds.value = expandedFolderIds.value.filter((id) => id !== folderId);
}
function handleCampaignEntryCreated({ entityType, entry }) {
if (!entry || (entry.campaign && String(entry.campaign) !== String(campaignId.value))) return;
const list = entityType === 'actor' ? actors : items;
list.value = [...list.value.filter((current) => current._id !== entry._id), entry]
.sort((a, b) => a.name.localeCompare(b.name));
}
function handleCampaignEntryUpdated({ entityType, entry }) {
if (!entry) return;
const list = entityType === 'actor' ? actors : items;
list.value = list.value.map((current) => current._id === entry._id ? entry : current)
.sort((a, b) => a.name.localeCompare(b.name));
}
const campaignId = computed(() => {
return Campaign.value?._id ?? Campaign.value?.id ?? null;
});
async function fetchCampaignNotes() {
if (!campaignId.value) {
notes.value = [];
folders.value = [];
notesError.value = '';
return;
}
loadingNotes.value = true;
notesError.value = '';
try {
const response = await Server().get('/note/list', { params: { campaign: campaignId.value } });
if (response.data.status !== 'ok') {
notes.value = [];
folders.value = [];
notesError.value = response.data.msg ?? 'Unable to load notes.';
return;
}
folders.value = response.data.folders.map((folder) => ({
_id: folder._id, name: folder.name, date: folder.date
}));
notes.value = response.data.notes.map((note) => {
return { key: note._id, title: note.title, text: note.content ?? '', date: note.date };
});
} catch (error) {
notes.value = [];
folders.value = [];
notesError.value = 'Unable to load notes.';
} finally {
loadingNotes.value = false;
}
}
async function fetchCampaignEntries(entityType = activeSection.value, silent = false) {
if (!campaignId.value || !['actors', 'items'].includes(entityType)) return;
if (!silent) {
loadingEntries.value = true;
entriesError.value = '';
}
try {
const collection = entityType === 'actors' ? 'actor' : 'item';
const response = await Server().get(`/${collection}/list`, { params: { campaign: campaignId.value } });
if (response.data.status !== 'ok') {
if (!silent) entriesError.value = response.data.msg ?? t('campaigns.errors.load');
return;
}
if (entityType === 'actors') {
const previousById = new Map(actors.value.map((actor) => [actor._id, actor]));
actors.value = response.data.actors;
for (const actor of actors.value) {
const previous = previousById.get(actor._id);
if (previous && JSON.stringify(previous) !== JSON.stringify(actor)) {
emitter.emit('campaign-entry-updated', { entityType: 'actor', entry: actor });
}
}
} else {
items.value = response.data.items;
}
} catch (error) {
if (!silent) entriesError.value = t('campaigns.errors.load');
} finally {
if (!silent) loadingEntries.value = false;
}
}
function selectSection(section) {
activeSection.value = section;
if (section === 'actors' || section === 'items') fetchCampaignEntries(section);
}
function createEntry(entityType) {
if (!campaignId.value) return;
CreateWindow('create_campaign_entry', { entityType, campaign: campaignId.value });
}
function entrySummary(actor) {
const bits = [t(`campaigns.actor.types.${actor.type}`)];
if (actor.species) bits.push(actor.species);
if (actor.className) bits.push(actor.className);
if (actor.level) bits.push(`${t('campaigns.actor.level-short')} ${actor.level}`);
if (actor.challengeRating) bits.push(`${t('campaigns.actor.cr-short')} ${actor.challengeRating}`);
return bits.join(' · ');
}
function itemSummary(item) {
return `${t(`campaigns.item.categories.${item.category}`)} · ${t(`campaigns.item.rarities.${item.rarity}`)} · ${t('campaigns.item.quantity-short')} ${item.quantity}`;
}
function showEntryMenu(entry, entityType) {
const collection = entityType === 'actor' ? 'actor' : 'item';
ShowContextMenu([{
name: t('campaigns.actions.delete'),
icon: '/icons/iconoir/regular/trash.svg',
action: async () => {
try {
const response = await Server().post(`/${collection}/delete`, { id: entry._id });
if (response.data.status === 'ok') {
if (entityType === 'actor') actors.value = actors.value.filter((actor) => actor._id !== entry._id);
else items.value = items.value.filter((item) => item._id !== entry._id);
}
} catch (error) {} finally { HideContextMenu(); }
}
}]);
}
function toggleEntryDetails(entryId) {
expandedEntryIds.value = expandedEntryIds.value.includes(entryId)
? expandedEntryIds.value.filter((id) => id !== entryId)
: [...expandedEntryIds.value, entryId];
}
async function openCharacterSheet(actor) {
const existingWindowId = GetFirstWindowId('character_sheet');
if (existingWindowId !== undefined) {
ClearWindow({ id: existingWindowId });
await nextTick();
}
CreateWindow('character_sheet', { actor });
}
function createNote() {
if (!Campaign.value) return;
CreateWindow('new_note', { campaign: campaignId.value });
}
function createFolder() {
CreateWindow('new_folder', { campaign: campaignId.value });
}
function toggleSidebar() {
sidebarCollapsed.value = !sidebarCollapsed.value;
}
const rootNotes = computed(() => notes.value.filter(n => !n._folder));
watch(campaignId, (newVal) => {
if (newVal) {
actors.value = [];
items.value = [];
fetchCampaignNotes();
if (activeSection.value === 'actors' || activeSection.value === 'items') fetchCampaignEntries(activeSection.value);
} else {
notes.value = [];
folders.value = [];
actors.value = [];
items.value = [];
notesError.value = '';
entriesError.value = '';
}
});
onMounted(() => {
emitter.on('note-created', handleNoteCreated);
emitter.on('note-renamed', handleNoteRenamed);
emitter.on('delete-note', handleNoteDeleted);
emitter.on('folder-saved', handleFolderSaved);
emitter.on('folder-deleted', handleFolderDeleted);
emitter.on('campaign-entry-created', handleCampaignEntryCreated);
emitter.on('campaign-entry-updated', handleCampaignEntryUpdated);
if (campaignId.value) {
fetchCampaignNotes();
}
actorRefreshInterval = setInterval(() => {
if (activeSection.value === 'actors' && campaignId.value) fetchCampaignEntries('actors', true);
}, 5000);
});
onBeforeUnmount(() => {
clearInterval(actorRefreshInterval);
emitter.off('note-created', handleNoteCreated);
emitter.off('note-renamed', handleNoteRenamed);
emitter.off('delete-note', handleNoteDeleted);
emitter.off('folder-saved', handleFolderSaved);
emitter.off('folder-deleted', handleFolderDeleted);
emitter.off('campaign-entry-created', handleCampaignEntryCreated);
emitter.off('campaign-entry-updated', handleCampaignEntryUpdated);
});
</script>
<template>
<div class="sidebar-shell">
<nav class="sidebar-actions" aria-label="Campaign tools">
<button
class="sidebar-action"
type="button"
@click="toggleSidebar"
:aria-expanded="(!sidebarCollapsed).toString()"
aria-controls="campaign-section-list"
:title="sidebarCollapsed ? t('campaigns.actions.expand-sidebar') : t('campaigns.actions.collapse-sidebar')"
:aria-label="sidebarCollapsed ? t('campaigns.actions.expand-sidebar') : t('campaigns.actions.collapse-sidebar')"
>
<img
class="sidebar-action-icon"
:src="sidebarCollapsed ? '/icons/iconoir/regular/nav-arrow-right.svg' : '/icons/iconoir/regular/nav-arrow-left.svg'"
alt=""
aria-hidden="true"
>
</button>
<button
class="sidebar-action"
:class="{ selected: activeSection === 'notes' }"
type="button" @click="selectSection('notes')"
:title="t('campaigns.sections.notes')" :aria-label="t('campaigns.sections.notes')"
:aria-pressed="(activeSection === 'notes').toString()"
>
<img class="sidebar-action-icon" src="/icons/iconoir/regular/book.svg" alt="" aria-hidden="true">
</button>
<button
class="sidebar-action"
:class="{ selected: activeSection === 'actors' }"
type="button" @click="selectSection('actors')"
:title="t('campaigns.sections.actors')" :aria-label="t('campaigns.sections.actors')"
:aria-pressed="(activeSection === 'actors').toString()"
>
<img class="sidebar-action-icon" src="/icons/iconoir/regular/user.svg" alt="" aria-hidden="true">
</button>
<button
class="sidebar-action"
:class="{ selected: activeSection === 'items' }"
type="button" @click="selectSection('items')"
:title="t('campaigns.sections.items')" :aria-label="t('campaigns.sections.items')"
:aria-pressed="(activeSection === 'items').toString()"
>
<img class="sidebar-action-icon" src="/icons/iconoir/regular/box.svg" alt="" aria-hidden="true">
</button>
</nav>
<aside class="notes-sidebar" :class="{ collapsed: sidebarCollapsed }">
<div class="sidebar-header">
<div class="sidebar-copy">
<span class="sidebar-eyebrow">{{ t('campaigns.sidebar-label') }}</span>
<strong class="sidebar-title">{{ t(`campaigns.sections.${activeSection}`) }}</strong>
</div>
<div class="sidebar-header-actions">
<template v-if="activeSection === 'notes'">
<button class="sidebar-action" type="button" @click="createNote" :disabled="!Campaign" :title="t('campaigns.actions.new-note')" :aria-label="t('campaigns.actions.new-note')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/plus.svg" alt="" aria-hidden="true">
</button>
<button class="sidebar-action" type="button" @click="createFolder" :disabled="!Campaign" :title="t('campaigns.actions.new-folder')" :aria-label="t('campaigns.actions.new-folder')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/folder.svg" alt="" aria-hidden="true">
</button>
<button class="sidebar-action" type="button" @click="fetchCampaignNotes" :disabled="!Campaign || loadingNotes" :title="t('campaigns.actions.refresh')" :aria-label="t('campaigns.actions.refresh')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/refresh.svg" alt="" aria-hidden="true">
</button>
</template>
<template v-else>
<button class="sidebar-action" type="button" @click="createEntry(activeSection === 'actors' ? 'actor' : 'item')" :disabled="!Campaign" :title="t('campaigns.actions.create', { section: t(`campaigns.sections.${activeSection}`).toLowerCase() })" :aria-label="t('campaigns.actions.create', { section: t(`campaigns.sections.${activeSection}`).toLowerCase() })">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/plus.svg" alt="" aria-hidden="true">
</button>
<button class="sidebar-action" type="button" @click="fetchCampaignEntries(activeSection)" :disabled="!Campaign || loadingEntries" :title="t('campaigns.actions.refresh')" :aria-label="t('campaigns.actions.refresh')">
<img class="sidebar-action-icon" src="/icons/iconoir/regular/refresh.svg" alt="" aria-hidden="true">
</button>
</template>
</div>
</div>
<div class="sidebar-list-drop-wrap" :class="{ 'drag-over': activeSection === 'notes' && isDragOverSidebar }" id="campaign-section-list" @dragenter.self="isDragOverSidebar = true" @dragleave.self="isDragOverSidebar = false" @dragover.prevent @drop.stop="handleSidebarDrop">
<template v-if="activeSection === 'notes'">
<div v-if="loadingNotes" class="sidebar-state">{{ t('campaigns.states.loading-notes') }}</div>
<div v-else-if="notesError" class="sidebar-state error">{{ notesError }}</div>
<div v-else-if="folders.length === 0 && notes.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-notes') }}</div>
<NestedNoteList v-else ref="nestedNoteListRef"
:parent-folder-id="null" :folders="folders" :notes="rootNotes" :campaign-id="campaignId"
:expanded-folder-ids="expandedFolderIds" @open-note="openNote"
@reload-notes="fetchCampaignNotes" @toggle-expanded-folder="toggleExpandedFolder" />
</template>
<template v-else-if="activeSection === 'actors'">
<div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div>
<div v-else-if="entriesError" class="sidebar-state error">{{ entriesError }}</div>
<div v-else-if="actors.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-actors') }}</div>
<div v-for="actor in actors" :key="actor._id" class="entity-entry" role="button" tabindex="0" @click="openCharacterSheet(actor)" @keydown.enter="openCharacterSheet(actor)" @keydown.space.prevent="openCharacterSheet(actor)" @contextmenu.prevent="showEntryMenu(actor, 'actor')">
<span class="entity-entry-name">{{ actor.name }}</span>
<span class="entity-entry-meta">{{ entrySummary(actor) }}</span>
</div>
</template>
<template v-else>
<div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div>
<div v-else-if="entriesError" class="sidebar-state error">{{ entriesError }}</div>
<div v-else-if="items.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-items') }}</div>
<div v-for="item in items" :key="item._id" class="entity-entry" role="button" tabindex="0" :aria-expanded="expandedEntryIds.includes(item._id)" @click="toggleEntryDetails(item._id)" @keydown.enter="toggleEntryDetails(item._id)" @keydown.space.prevent="toggleEntryDetails(item._id)" @contextmenu.prevent="showEntryMenu(item, 'item')">
<span class="entity-entry-name">{{ item.name }}</span>
<span class="entity-entry-meta">{{ itemSummary(item) }}</span>
<template v-if="expandedEntryIds.includes(item._id)">
<span v-if="item.weight !== undefined" class="entity-entry-description">{{ item.weight }} lb</span>
<span v-if="item.properties" class="entity-entry-description">{{ item.properties }}</span>
<span v-if="item.description" class="entity-entry-description">{{ item.description }}</span>
</template>
</div>
</template>
</div>
</aside>
</div>
</template>
<style scoped>
.sidebar-shell {
min-height: 0;
display: flex;
flex-direction: row;
}
.sidebar-actions {
width: 46px;
min-width: 46px;
padding: 8px 6px;
border-right: 1px solid var(--color-border);
background-color: var(--color-background-light);
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
}
.sidebar-action {
width: 34px;
height: 34px;
margin: 0;
padding: 0;
border: 1px solid var(--color-border);
border-radius: 8px;
background: var(--color-background-soft);
box-shadow: none;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.sidebar-action.selected {
background: var(--color-button-hover);
border-color: var(--color-link);
}
.sidebar-action:hover {
background: var(--color-button-hover);
}
.sidebar-action:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.sidebar-action-icon {
width: 18px;
height: 18px;
filter: invert(var(--color-icon-invert));
}
.notes-sidebar {
min-width: 280px;
width: 280px;
border-right: 1px solid var(--color-border);
background-color: var(--color-background-light);
display: flex;
flex-direction: column;
overflow: hidden;
transition: width 0.2s ease, min-width 0.2s ease, border-color 0.2s ease;
}
.notes-sidebar.collapsed {
width: 0;
min-width: 0;
border-right-color: transparent;
}
.sidebar-header {
width: 280px;
min-width: 280px;
box-sizing: border-box;
padding: 12px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
border-bottom: 1px solid var(--color-border);
}
.sidebar-header-actions { display: flex; align-items: center; gap: 4px; }
.sidebar-header-actions .sidebar-action { width: 30px; height: 30px; }
.sidebar-header-actions .sidebar-action-icon { width: 16px; height: 16px; }
.sidebar-copy {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.sidebar-eyebrow,
.sidebar-meta {
font-size: 12px;
opacity: 0.7;
}
.sidebar-title {
line-height: 1.2;
word-break: break-word;
}
.sidebar-list-drop-wrap {
width: 280px;
min-width: 280px;
box-sizing: border-box;
padding: 10px;
display: flex;
flex-direction: column;
overflow-y: auto;
gap: 2px;
transition: background-color 0.15s ease;
flex: 1;
min-height: 0;
}
.sidebar-list-drop-wrap.drag-over {
background: var(--color-button-hover);
}
.sidebar-state {
padding: 12px;
border-radius: 10px;
background: var(--color-background-soft);
font-size: 14px;
}
.sidebar-state.error {
color: #9e2a2b;
}
.entity-entry {
width: 100%; padding: 9px 10px; border: 1px solid transparent; border-radius: 8px;
background: transparent; color: var(--color-text); text-align: left; display: flex; flex-direction: column;
gap: 3px; cursor: pointer;
}
.entity-entry:hover { border-color: var(--color-border); background: var(--color-background-soft); }
.entity-entry:focus-visible { outline: 1px solid var(--color-link); }
.entity-entry-name { font-weight: bold; }
.entity-entry-meta, .entity-entry-description { font-size: 12px; opacity: 0.72; }
.entity-entry-description { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
@media (max-width: 900px) {
.notes-sidebar {
width: 220px;
min-width: 220px;
}
.sidebar-header,
.sidebar-list-drop-wrap {
width: 220px;
min-width: 220px;
}
}
</style>