Deploy deepseek 2
Some checks failed
Test / test (push) Failing after 2s
Build and Deploy Nuxt / build (push) Successful in 1m51s

This commit is contained in:
2026-10-19 19:04:28 +02:00
parent b5d5e570d5
commit 1ec29121e1
45 changed files with 3438 additions and 166 deletions

View File

@@ -1,12 +1,21 @@
<script setup>
import { onMounted, onUnmounted, ref, createApp } from 'vue';
import { onMounted, onUnmounted, ref, nextTick, createApp } from 'vue';
import ToastManager from '~/components/managers/ToastManager.vue';
import { emitter } from '~/services/Emitter';
import { GetWidget, ParseMarkdown } from '~/services/Marker';
import { GetWidget, GetWidgetRegistry, ParseMarkdown } from '~/services/Marker';
import { BuildWidgetSuggestions, FilterWidgetSuggestions, FindWidgetTrigger, InsertWidgetSuggestion } from '~/services/WidgetAutocomplete';
import { FilterLinkSuggestions, FindLinkTarget, FindLinkTrigger, InsertLinkSuggestion } from '~/services/LinkAutocomplete';
import { LoadLinkEntry, LoadLinkTargets } from '~/services/LinkTargets';
import { AnchorMap } from '~/services/Content';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
import { useCampaignService } from '~/services/Campaign';
import Server from '~/services/Server';
import { DisplayToast } from '~/services/Toaster';
import { useI18n } from 'vue-i18n';
import TestWidget from '../widgets/TestWidget.vue';
import EmbeddedEntry from './EmbeddedEntry.vue';
import LinkPreview from './LinkPreview.vue';
import SuggestionMenu from './SuggestionMenu.vue';
// import { GetNote, GetContent } from '@/services/Content';
const props = defineProps(['text', 'title', 'noteKey']);
@@ -24,6 +33,228 @@ const showClose = ref(false);
let savedState = { text: '', title: '' };
// --- Autocompletat de la nota ---
// Mentre s'edita, escriure `@` ofereix els widgets de la nota (els de Marker.js) i `[[` els
// enllacos de la campanya (notes, actors, objectes i mapes). La llista es calcula sobre el text i
// el cursor reals, no sobre el model, perque l'esdeveniment d'entrada arriba abans que Vue
// actualitzi `sourceText`.
const editor = ref(null);
const suggestions = ref([]);
const selectedSuggestion = ref(0);
const suggestionStyle = ref({});
const allWidgetSuggestions = BuildWidgetSuggestions(GetWidgetRegistry());
const { Campaign } = useCampaignService();
const linkTargets = ref([]);
let linkTargetsLoaded = false;
let linkTargetsRequest = null;
const campaignId = computed(() => Campaign.value?._id ?? Campaign.value?.id ?? null);
// Les destinacions d'enllac venen del servidor una sola vegada: tant el desplegable d'edicio com la
// vista previa dels enllacos ja escrits fan servir la mateixa llista.
function ensureLinkTargets() {
if (linkTargetsLoaded) return Promise.resolve(linkTargets.value);
if (!linkTargetsRequest) {
linkTargetsRequest = LoadLinkTargets(campaignId.value).then((targets) => {
linkTargets.value = targets;
linkTargetsLoaded = true;
return targets;
}).catch(() => []);
}
return linkTargetsRequest;
}
// Estils que el mirall ha de copiar del textarea per mesurar-hi el cursor.
const MIRROR_STYLES = [
'direction', 'boxSizing', 'width', 'height',
'overflowX', 'overflowY',
'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth',
'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',
'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust',
'lineHeight', 'fontFamily', 'textAlign', 'textTransform', 'textIndent',
'textDecoration', 'letterSpacing', 'wordSpacing', 'tabSize'
];
// Posicio (en px, relativa al contenidor de la nota) del cursor del textarea. Un element mirall
// invisible copia els estils i el text fins al cursor i ens diu on cau.
function caretCoordinates(textarea, position) {
const style = window.getComputedStyle(textarea);
const mirror = document.createElement('div');
mirror.style.position = 'absolute';
mirror.style.top = '0';
mirror.style.left = '0';
mirror.style.visibility = 'hidden';
mirror.style.whiteSpace = 'pre-wrap';
mirror.style.wordWrap = 'break-word';
for (const property of MIRROR_STYLES) {
if (style[property] != null) mirror.style[property] = style[property];
}
const value = textarea.value;
mirror.textContent = value.substring(0, position);
const marker = document.createElement('span');
marker.textContent = value.substring(position) || '.';
mirror.appendChild(marker);
document.body.appendChild(mirror);
const lineHeight = parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.2 || 20;
const coordinates = {
top: marker.offsetTop + textarea.offsetTop - textarea.scrollTop,
left: marker.offsetLeft + textarea.offsetLeft - textarea.scrollLeft,
lineHeight
};
document.body.removeChild(mirror);
return coordinates;
}
// Cada entrada del desplegable porta ja el seu text i la seva pista traduida; `value` es el widget o
// l'objectiu d'enllac cru que s'inserirà en triar-la.
function widgetEntry(widget) {
return {
key: `widget:${widget.type}:${widget.name}`,
kind: 'widget',
value: widget,
label: `@${widget.name}`,
hint: t('general.widgets.' + widget.type)
};
}
function linkEntry(target) {
return {
key: `link:${target.type}:${target.id}`,
kind: 'link',
value: target,
label: `[[${target.label}]]`,
hint: t(`campaigns.sections.${target.type}s`)
};
}
function closeSuggestions() {
suggestions.value = [];
}
// Dibuixa el desplegable sota el cursor, girant-lo cap amunt si no hi cap.
function showSuggestions(matches, caret) {
if (!matches.length || !editor.value) {
closeSuggestions();
return;
}
suggestions.value = matches;
selectedSuggestion.value = 0;
const coordinates = caretCoordinates(editor.value, caret);
const container = editor.value.parentElement;
const containerHeight = container ? container.clientHeight : 0;
let top = coordinates.top + coordinates.lineHeight;
if (containerHeight && top + 150 > containerHeight) top = Math.max(0, coordinates.top - 150);
suggestionStyle.value = { top: `${top}px`, left: `${coordinates.left}px` };
}
function updateSuggestions(text, caret) {
const widgetTrigger = FindWidgetTrigger(text, caret);
if (widgetTrigger) {
showSuggestions(FilterWidgetSuggestions(allWidgetSuggestions, widgetTrigger.query).map(widgetEntry), caret);
return;
}
const linkTrigger = FindLinkTrigger(text, caret);
if (linkTrigger) {
// Les destinacions d'enllac vénen del servidor: la primera vegada que es tecleja `[[` es
// demanen, i en arribar es torna a calcular el desplegable sobre el que hi ha ara al cursor.
if (!linkTargetsLoaded) {
closeSuggestions();
ensureLinkTargets().then(() => {
const el = editor.value;
if (el) updateSuggestions(el.value, el.selectionStart ?? el.value.length);
});
return;
}
showSuggestions(FilterLinkSuggestions(linkTargets.value, linkTrigger.query).map(linkEntry), caret);
return;
}
closeSuggestions();
}
function onEditorInput(event) {
const el = event.target;
updateSuggestions(el.value, el.selectionStart ?? el.value.length);
}
function onEditorClick(event) {
if (!suggestions.value.length) return;
const el = event.target;
updateSuggestions(el.value, el.selectionStart ?? el.value.length);
}
function onEditorKeydown(event) {
if (!suggestions.value.length) return;
if (event.key === 'ArrowDown') {
event.preventDefault();
selectedSuggestion.value = (selectedSuggestion.value + 1) % suggestions.value.length;
} else if (event.key === 'ArrowUp') {
event.preventDefault();
selectedSuggestion.value = (selectedSuggestion.value - 1 + suggestions.value.length) % suggestions.value.length;
} else if (event.key === 'Enter' || event.key === 'Tab') {
event.preventDefault();
applySuggestion(suggestions.value[selectedSuggestion.value]);
} else if (event.key === 'Escape') {
event.preventDefault();
closeSuggestions();
}
}
function onSuggestionHover(index) {
selectedSuggestion.value = index;
}
function applySuggestion(entry) {
if (!entry) return;
if (entry.kind === 'link') applyLinkSuggestion(entry.value);
else applyWidgetSuggestion(entry.value);
}
// Escriu el text inserit i deixa el cursor on el widget o l'enllac el volen.
function writeSuggestion(result) {
sourceText.value = result.text;
closeSuggestions();
const el = editor.value;
if (!el) return;
nextTick(() => {
el.focus();
el.setSelectionRange(result.caret, result.caret);
});
}
function applyWidgetSuggestion(suggestion) {
const el = editor.value;
if (!el || !suggestion) return;
const trigger = FindWidgetTrigger(el.value, el.selectionStart ?? el.value.length);
if (!trigger) {
closeSuggestions();
return;
}
writeSuggestion(InsertWidgetSuggestion(el.value, trigger, suggestion));
}
function applyLinkSuggestion(target) {
const el = editor.value;
if (!el || !target) return;
const trigger = FindLinkTrigger(el.value, el.selectionStart ?? el.value.length);
if (!trigger) {
closeSuggestions();
return;
}
writeSuggestion(InsertLinkSuggestion(el.value, trigger, target));
}
function markDirty() {
isDirty.value = sourceText.value !== savedState.text || title.value !== savedState.title;
}
@@ -81,6 +312,195 @@ function mountComponents() {
});
});
}
// --- Enllacos `[[…]]` de la vista previa ---
// Cada enllac porta el nom de l'entrada. En muntar la nota el resolem contra les llistes de la
// campanya: un personatge o un objecte mostra una fitxa resumida en passar-hi el ratoli i s'obre
// sencer en fer-hi clic; una nota s'obre a la columna i un mapa s'ancora com des de la barra.
const linkPreview = ref(null);
const PREVIEW_DELAY = 180;
const PREVIEW_HIDE_DELAY = 140;
let previewTimer = null;
let previewHideTimer = null;
let hoveredLink = null;
let previewHovered = false;
function resolveLink(el) {
return FindLinkTarget(linkTargets.value, el?.dataset?.href);
}
function hideLinkPreview() {
clearTimeout(previewTimer);
clearTimeout(previewHideTimer);
previewHovered = false;
hoveredLink = null;
linkPreview.value = null;
}
function scheduleHideLinkPreview() {
clearTimeout(previewTimer);
clearTimeout(previewHideTimer);
previewHideTimer = setTimeout(() => {
if (!previewHovered) hideLinkPreview();
}, PREVIEW_HIDE_DELAY);
}
function keepLinkPreview() {
previewHovered = true;
clearTimeout(previewHideTimer);
}
async function showLinkPreview(el) {
await ensureLinkTargets();
if (hoveredLink !== el) return;
const target = resolveLink(el);
if (!target || (target.type !== 'actor' && target.type !== 'item')) return;
const entry = await LoadLinkEntry(campaignId.value, target.type, target.id);
if (!entry || hoveredLink !== el) return;
// The card is fixed to the viewport, so it is placed from the link's rectangle and kept
// inside the window; a link near the bottom gets the card above it instead.
const rect = el.getBoundingClientRect();
const width = 320;
const estimatedHeight = 260;
const x = Math.min(Math.max(8, rect.left), Math.max(8, window.innerWidth - width - 12));
const y = rect.bottom + estimatedHeight + 12 > window.innerHeight
? Math.max(8, rect.top - estimatedHeight - 8)
: rect.bottom + 8;
linkPreview.value = { target, entry, x, y };
}
function onLinkEnter(el) {
hoveredLink = el;
clearTimeout(previewTimer);
clearTimeout(previewHideTimer);
previewTimer = setTimeout(() => showLinkPreview(el), PREVIEW_DELAY);
}
// Marks every link of the rendered note with the type it points at, so the CSS can tell a character
// from an item and a target that is gone can be dimmed. It runs after the lists arrive.
async function annotateLinks(root) {
const links = Array.from(root.querySelectorAll('.vue-link'));
if (!links.length) return;
await ensureLinkTargets();
if (!root.isConnected) return;
for (const el of links) {
const target = resolveLink(el);
if (target) {
el.dataset.linkType = target.type;
el.classList.add('is-resolved');
} else {
el.classList.add('is-unresolved');
el.title = t('campaigns.link-preview.not-found');
}
}
}
function bindLinks(root) {
root.querySelectorAll('.vue-link').forEach((el) => {
if (el.dataset.linkBound) return;
el.dataset.linkBound = '1';
el.addEventListener('mouseenter', () => onLinkEnter(el));
el.addEventListener('mouseleave', scheduleHideLinkPreview);
el.addEventListener('focus', () => onLinkEnter(el));
el.addEventListener('blur', scheduleHideLinkPreview);
el.addEventListener('click', (event) => {
event.stopPropagation();
openLink(el);
});
el.addEventListener('keydown', (event) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
event.stopPropagation();
openLink(el);
});
});
annotateLinks(root);
}
async function openLink(el) {
await ensureLinkTargets();
const target = resolveLink(el);
if (!target) return;
hideLinkPreview();
openLinkTarget(target);
}
async function openLinkTarget(target) {
if (target.type === 'actor' || target.type === 'item') {
const entry = await LoadLinkEntry(campaignId.value, target.type, target.id);
if (entry) await openEntrySheet(target.type, entry);
return;
}
if (target.type === 'note') {
try {
const response = await Server().get(`/note/retrieve/${target.id}`);
if (response.data.status !== 'ok' || !response.data.note) return;
const note = response.data.note;
emitter.emit('push-note', { key: note._id, title: note.title, text: note.content ?? '', date: note.date });
} catch (error) {}
return;
}
if (target.type === 'map') {
const map = await LoadLinkEntry(campaignId.value, 'map', target.id);
if (map) AnchorMap(map);
}
}
// The same window the sidebar opens: replace the sheet that is already up instead of stacking a
// second one.
async function openEntrySheet(type, entry) {
const windowType = type === 'actor' ? 'character_sheet' : 'item_sheet';
const existingWindowId = GetFirstWindowId(windowType);
if (existingWindowId !== undefined) {
ClearWindow({ id: existingWindowId });
await nextTick();
}
CreateWindow(windowType, type === 'actor' ? { actor: entry } : { item: entry });
}
function openPreviewedEntry() {
const target = linkPreview.value?.target;
hideLinkPreview();
if (target) openLinkTarget(target);
}
function setupLinks() {
const root = renderedContent.value;
if (!root) return;
bindLinks(root);
}
// --- `![[…]]` embeddings ---
// An embedded token mounts a card of its own, the way widgets do: the placeholder left by Marker is
// the app's container, and `EmbeddedEntry.vue` resolves the label and draws the sheet inline.
function mountEmbeds() {
const root = renderedContent.value;
if (!root) return;
root.querySelectorAll('.vue-embed').forEach(el => {
if (el.dataset.embedMounted) return;
el.dataset.embedMounted = '1';
try {
const app = createApp(EmbeddedEntry, { href: el.dataset.href, t });
app.config.errorHandler = (err) => {
console.error('Embed error', el.dataset.href, err);
};
app.mount(el);
mountedApps.push(app);
} catch (err) {
console.error('Failed to mount embed', el.dataset.href, err);
}
});
}
///
function update(){
@@ -88,11 +508,14 @@ function update(){
// la reassignacio de displayText (v-html) eliminaria els contenidors i
// desmuntar-les despres fallaria sobre nodes desaccelats.
unmountComponents();
hideLinkPreview();
displayText.value = compiledMarkdown.value;
setTimeout(() => {
setupHeadings();
setupCallout()
setupLinks();
mountComponents();
mountEmbeds();
}, 0);
}
@@ -107,6 +530,9 @@ onMounted(() => {
savedState = { text: props.text, title: props.title };
emitter.on('title-updated', handleTitleUpdate);
// window.addEventListener('keydown', handleKeydown);
// The preview is pinned to the viewport, so any scroll (the note column, another note) leaves
// it behind: dismiss it instead of letting it float over the wrong place.
window.addEventListener('scroll', hideLinkPreview, true);
setTimeout(() => setupCallout(), 0);
update();
});
@@ -120,6 +546,8 @@ function handleTitleUpdate(data) {
onUnmounted(() => {
emitter.off('title-updated', handleTitleUpdate);
// window.removeEventListener('keydown', handleKeydown);
window.removeEventListener('scroll', hideLinkPreview, true);
hideLinkPreview();
unmountComponents();
});
@@ -128,6 +556,8 @@ function handleKeydown(e) {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'e') {
e.preventDefault(); // prevent browser default behavior
editingMode.value = !editingMode.value;
closeSuggestions();
hideLinkPreview();
if(!editingMode.value){
update();
SaveNote(); // Save when switching to display mode
@@ -280,7 +710,7 @@ function renderFoldTree(items, target) {
function handleFoldClick(e) {
// No plegar quan es fa clic en un enllaç o se selecciona text
if (e.target.closest('a')) return;
if (e.target.closest('a, .vue-link')) return;
const selection = window.getSelection();
if (selection && selection.toString()) return;
@@ -325,13 +755,39 @@ function setupHeadings() {
<span>{{ title }}</span>
</div>
<div class="note-content-container">
<textarea v-model="sourceText" class="full-editor" v-if="editingMode"></textarea>
<template v-if="editingMode">
<textarea
ref="editor"
v-model="sourceText"
class="full-editor"
@input="onEditorInput"
@click="onEditorClick"
@keydown="onEditorKeydown"
@blur="closeSuggestions"
></textarea>
<SuggestionMenu
v-if="suggestions.length"
:suggestions="suggestions"
:selected="selectedSuggestion"
:position="suggestionStyle"
@select="applySuggestion"
@hover="onSuggestionHover"
/>
</template>
<div v-else class="note-content" ref="noteContent">
<h1>{{ title }}</h1>
<div ref="renderedContent" v-html="displayText"></div>
</div>
</div>
<LinkPreview
v-if="linkPreview"
:preview="linkPreview"
@enter="keepLinkPreview"
@leave="scheduleHideLinkPreview"
@close="hideLinkPreview"
@open="openPreviewedEntry"
/>
</div>
</template>
@@ -439,6 +895,7 @@ width: 100%;
.note-content-container {
width: 100%;
position: relative;
}
.note-content :deep(img) {
@@ -446,4 +903,29 @@ width: 100%;
height: auto;
display: block; /* optional: avoids inline spacing issues */
}
/* Els `[[enllacos]]` de la nota: es llegeixen com a text subratllat i obren la fitxa de
l'entrada. El tipus el marca el servei d'enllacos en resoldre'l. */
.note-content :deep(.vue-link) {
color: var(--color-link);
cursor: pointer;
text-decoration: underline;
text-decoration-style: dotted;
text-underline-offset: 2px;
border-radius: 2px;
}
.note-content :deep(.vue-link:hover),
.note-content :deep(.vue-link:focus-visible) {
text-decoration-style: solid;
background: var(--color-button-hover);
outline: none;
}
.note-content :deep(.vue-link.is-unresolved) {
color: var(--color-gray);
cursor: help;
text-decoration-style: dashed;
opacity: .7;
}
</style>