932 lines
29 KiB
Vue
932 lines
29 KiB
Vue
<script setup>
|
|
import { onMounted, onUnmounted, ref, nextTick, createApp } from 'vue';
|
|
import ToastManager from '~/components/managers/ToastManager.vue';
|
|
import { emitter } from '~/services/Emitter';
|
|
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']);
|
|
const { t } = useI18n();
|
|
const noteContent = ref(null); // Markdown text
|
|
const renderedContent = ref(null); // Container holding the compiled HTML (v-html)
|
|
|
|
const sourceText = ref(''); // Original markdown source, used for editing
|
|
const displayText = ref(''); // Compiled HTML from markdown
|
|
|
|
const editingMode = ref(false);
|
|
const title = ref(props.title);
|
|
const isDirty = ref(false);
|
|
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;
|
|
}
|
|
|
|
function closeNote(){
|
|
// 'close-note' only closes the opened note; 'delete-note' is reserved for
|
|
// actual deletions (sidebar removal happens on that event instead)
|
|
emitter.emit('close-note', props.noteKey);
|
|
}
|
|
|
|
const compiledMarkdown = computed(() => {
|
|
return ParseMarkdown(sourceText.value);
|
|
});
|
|
|
|
// Apps de widget muntades sobre aquest node. Les guardem per desmuntar-les
|
|
// abans de re-renderitzar o en desmuntar la nota (evita instancies orfes i
|
|
// que Vue intenti parchar nodes ja eliminats).
|
|
const mountedApps = [];
|
|
|
|
function unmountComponents() {
|
|
for (const app of mountedApps) {
|
|
try {
|
|
app.unmount();
|
|
} catch (err) {
|
|
// El contenidor pot ja no ser al DOM; ignorem i netegim igualment.
|
|
}
|
|
}
|
|
mountedApps.length = 0;
|
|
}
|
|
|
|
function mountComponents() {
|
|
// Només dins d'aquesta nota: evitar muntar (o tornari a muntar) widgets
|
|
// d'altres notes obertes, que ja tenen la seva app.
|
|
const root = renderedContent.value;
|
|
if (!root) return;
|
|
|
|
const widget_types = ['display', 'inline'];
|
|
widget_types.forEach((widget_type) => {
|
|
const nodes = root.querySelectorAll('.vue-component-' + widget_type);
|
|
nodes.forEach(el => {
|
|
const widget = GetWidget(widget_type, el.dataset.component);
|
|
if (!widget) return; // widget desconegut: saltem en comptes de petar
|
|
try {
|
|
const app = createApp(widget, { content: el.dataset.content });
|
|
// Evita que un error dins del widget (p. ex. el parser de daus amb una
|
|
// expressio malformada) es converteixi en un error no controlat.
|
|
app.config.errorHandler = (err) => {
|
|
console.error('Widget error', el.dataset.component, err);
|
|
};
|
|
app.mount(el);
|
|
mountedApps.push(app);
|
|
} catch (err) {
|
|
console.error('Failed to mount widget', el.dataset.component, err);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
// --- 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(){
|
|
// Desmuntem les apps anteriors mentre els seus nodes encara son al DOM;
|
|
// 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);
|
|
}
|
|
|
|
watch(sourceText, markDirty);
|
|
|
|
watch(title, markDirty);
|
|
|
|
onMounted(() => {
|
|
sourceText.value = props.text;
|
|
title.value = props.title;
|
|
|
|
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();
|
|
});
|
|
|
|
function handleTitleUpdate(data) {
|
|
if (data.key !== props.noteKey) return;
|
|
title.value = data.title;
|
|
savedState.title = data.title;
|
|
}
|
|
|
|
onUnmounted(() => {
|
|
emitter.off('title-updated', handleTitleUpdate);
|
|
// window.removeEventListener('keydown', handleKeydown);
|
|
window.removeEventListener('scroll', hideLinkPreview, true);
|
|
hideLinkPreview();
|
|
unmountComponents();
|
|
});
|
|
|
|
function handleKeydown(e) {
|
|
// Check for Ctrl + E (or Cmd + E on Mac)
|
|
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
|
|
} else {
|
|
// Entrant en mode edicio, la vista prèvia (v-else) es destrueix;
|
|
// desmuntem els widgets per no deixar apps orfes.
|
|
unmountComponents();
|
|
}
|
|
return;
|
|
}
|
|
|
|
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
|
|
e.preventDefault(); // prevent browser default behavior
|
|
// Save the note (you can emit an event or call a method here)
|
|
SaveNote();
|
|
return;
|
|
}
|
|
}
|
|
|
|
function SaveNote(){
|
|
Server().post('/note/update', {
|
|
id: props.noteKey,
|
|
content: sourceText.value,
|
|
title: title.value,
|
|
}).then((response) => {
|
|
if(response.data.status !== 'ok'){
|
|
// El contingut no s'ha guardat: mantenem el punt de "no desar" i
|
|
// avisem en lloc d'empassar-nos l'error silenciosament.
|
|
isDirty.value = true;
|
|
DisplayToast('red', t(response.data.msg || 'general.notes.save-error'), 3000);
|
|
return;
|
|
}
|
|
savedState = { text: sourceText.value, title: title.value };
|
|
isDirty.value = false;
|
|
}).catch((error) => {
|
|
isDirty.value = true;
|
|
DisplayToast('red', t('general.notes.save-error'), 3000);
|
|
});
|
|
}
|
|
|
|
function toggleCallout() {
|
|
const outerBlock = this.parentElement;
|
|
outerBlock.classList.toggle("is-collapsed")
|
|
const collapsed = outerBlock.classList.contains("is-collapsed")
|
|
const height = collapsed ? this.scrollHeight : outerBlock.scrollHeight
|
|
outerBlock.style.maxHeight = height + "px"
|
|
|
|
// walk and adjust height of all parents
|
|
let current = outerBlock
|
|
let parent = outerBlock.parentElement
|
|
while (parent) {
|
|
if (!parent.classList.contains("callout")) {
|
|
return
|
|
}
|
|
|
|
const collapsed = parent.classList.contains("is-collapsed")
|
|
const height = collapsed ? parent.scrollHeight : parent.scrollHeight + current.scrollHeight
|
|
parent.style.maxHeight = height + "px"
|
|
|
|
current = parent
|
|
parent = parent.parentElement
|
|
}
|
|
}
|
|
|
|
function setupCallout() {
|
|
if (!noteContent.value) {
|
|
return;
|
|
}
|
|
|
|
const collapsible = noteContent.value.getElementsByClassName(
|
|
`callout is-collapsible`,
|
|
);
|
|
for (const div of collapsible) {
|
|
const title = div.firstElementChild;
|
|
|
|
if (title) {
|
|
title.addEventListener("click", toggleCallout)
|
|
|
|
const collapsed = div.classList.contains("is-collapsed")
|
|
const height = collapsed ? title.scrollHeight : div.scrollHeight
|
|
div.style.maxHeight = height + "px"
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- Col·lapse de seccions (h1, h2, h3) a la vista prèvia ---
|
|
// Agrupa el contingut sota cada capçalera fins la seguent del mateix nivell o
|
|
// superior, de manera que en fer clic sobre la capçalera es plegui tota la seva
|
|
// secció (les sub-seccions s'hi inclouen, estil Obsidian).
|
|
function headingLevel(el) {
|
|
const tag = el && el.tagName;
|
|
if (tag === 'H1') return 1;
|
|
if (tag === 'H2') return 2;
|
|
if (tag === 'H3') return 3;
|
|
return 0; // h4+ i la resta es tracten com a contingut normal
|
|
}
|
|
|
|
function buildFoldTree(nodes) {
|
|
const pos = { i: 0 };
|
|
|
|
function parseSection(level) {
|
|
const heading = nodes[pos.i];
|
|
pos.i++;
|
|
const body = [];
|
|
while (pos.i < nodes.length) {
|
|
const lvl = headingLevel(nodes[pos.i]);
|
|
if (lvl && lvl <= level) break; // seguent secció del mateix nivell o superior
|
|
if (lvl) {
|
|
body.push(parseSection(lvl)); // sub-secció més profunda
|
|
} else {
|
|
body.push({ node: nodes[pos.i] });
|
|
pos.i++;
|
|
}
|
|
}
|
|
return { heading, body, level };
|
|
}
|
|
|
|
const top = [];
|
|
while (pos.i < nodes.length) {
|
|
const lvl = headingLevel(nodes[pos.i]);
|
|
if (lvl) {
|
|
top.push(parseSection(lvl));
|
|
} else {
|
|
top.push({ node: nodes[pos.i] });
|
|
pos.i++;
|
|
}
|
|
}
|
|
return top;
|
|
}
|
|
|
|
function renderFoldTree(items, target) {
|
|
for (const item of items) {
|
|
if (item.node) {
|
|
target.appendChild(item.node);
|
|
continue;
|
|
}
|
|
const wrapper = document.createElement('div');
|
|
wrapper.className = 'fold fold-h' + item.level;
|
|
item.heading.classList.add('fold-handle');
|
|
wrapper.appendChild(item.heading);
|
|
|
|
const body = document.createElement('div');
|
|
body.className = 'fold-body';
|
|
renderFoldTree(item.body, body);
|
|
wrapper.appendChild(body);
|
|
|
|
target.appendChild(wrapper);
|
|
}
|
|
}
|
|
|
|
function handleFoldClick(e) {
|
|
// No plegar quan es fa clic en un enllaç o se selecciona text
|
|
if (e.target.closest('a, .vue-link')) return;
|
|
const selection = window.getSelection();
|
|
if (selection && selection.toString()) return;
|
|
|
|
const handle = e.target.closest('.fold-handle');
|
|
if (!handle) return;
|
|
const wrapper = handle.parentElement;
|
|
if (!wrapper || !wrapper.classList.contains('fold')) return;
|
|
wrapper.classList.toggle('is-collapsed');
|
|
}
|
|
|
|
function setupHeadings() {
|
|
const container = renderedContent.value;
|
|
if (!container) return;
|
|
|
|
const nodes = Array.from(container.children);
|
|
if (!nodes.some((el) => headingLevel(el))) return;
|
|
|
|
const tree = buildFoldTree(nodes);
|
|
renderFoldTree(tree, container);
|
|
|
|
if (!container._foldBound) {
|
|
container.addEventListener('click', handleFoldClick);
|
|
container._foldBound = true;
|
|
}
|
|
}
|
|
|
|
|
|
</script>
|
|
|
|
<template>
|
|
<div class="note" @keydown="handleKeydown" tabindex="0">
|
|
<div class="note-stunt">
|
|
<div class="unsaved-wrapper" v-if="isDirty">
|
|
<div class="unsaved-dot"></div>
|
|
<div class="close-button close-hidden" v-on:click="closeNote">
|
|
<img class="icon" src="/icons/Pixelarticons/white/close.svg" alt="My Happy SVG"/>
|
|
</div>
|
|
</div>
|
|
<div class="close-button" v-else v-on:click="closeNote">
|
|
<img class="icon" src="/icons/Pixelarticons/white/close.svg" alt="My Happy SVG"/>
|
|
</div>
|
|
<span>{{ title }}</span>
|
|
</div>
|
|
<div class="note-content-container">
|
|
<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>
|
|
|
|
<style scoped>
|
|
.note-stunt {
|
|
writing-mode: vertical-lr;
|
|
position: sticky;
|
|
top: 0px;
|
|
left: 0px;
|
|
bottom: 0px;
|
|
padding: 10px;
|
|
display: flex;
|
|
user-select: none;
|
|
}
|
|
|
|
.unsaved-wrapper {
|
|
position: relative;
|
|
margin-bottom: 5px;
|
|
width: 20px;
|
|
height: 20px;
|
|
}
|
|
|
|
.unsaved-dot {
|
|
width: 10px;
|
|
height: 10px;
|
|
border-radius: 50%;
|
|
background-color: #ffffff;
|
|
position: absolute;
|
|
top: 50%;
|
|
left: 50%;
|
|
transform: translate(-50%, -50%);
|
|
pointer-events: none;
|
|
}
|
|
|
|
.close-hidden {
|
|
opacity: 0;
|
|
visibility: hidden;
|
|
position: absolute;
|
|
top: 0;
|
|
left: 0;
|
|
width: 20px;
|
|
height: 20px;
|
|
margin-bottom: 0;
|
|
transition: opacity 0.15s ease, visibility 0.15s ease;
|
|
}
|
|
|
|
.unsaved-wrapper:hover .close-hidden {
|
|
opacity: 1;
|
|
visibility: visible;
|
|
}
|
|
|
|
.unsaved-wrapper:hover .unsaved-dot {
|
|
opacity: 0;
|
|
}
|
|
|
|
.full-editor {
|
|
width: 100%;
|
|
height: 100%;
|
|
box-sizing: border-box;
|
|
|
|
border: none;
|
|
outline: none;
|
|
resize: none;
|
|
|
|
padding: 20px;
|
|
font-size: 16px;
|
|
font-family: monospace; /* optional, gives document/editor feel */
|
|
|
|
padding-bottom: 400px; /* Small bottom margin */
|
|
}
|
|
|
|
.close-button {
|
|
height: 20px;
|
|
width: 20px;
|
|
margin-bottom: 5px;
|
|
display: flex;
|
|
justify-content: center;
|
|
cursor: pointer;
|
|
filter: invert(var(--color-icon-invert));
|
|
}
|
|
|
|
.note {
|
|
min-width: 700px;
|
|
max-width: 700px;
|
|
overflow-y: auto;
|
|
|
|
border-color: var(--color-note-border);
|
|
border-width: 0px;
|
|
border-right-width: 1px;
|
|
border-style: solid;
|
|
display: flex;
|
|
|
|
background-color: var(--color-background);
|
|
position: sticky;
|
|
top: 0px;
|
|
}
|
|
|
|
/* Contingut de cada nota */
|
|
.note-content {
|
|
padding-bottom: 400px;
|
|
overflow-y: auto;
|
|
max-width: 600px;
|
|
padding: 20px;
|
|
}
|
|
|
|
.note-content-container {
|
|
width: 100%;
|
|
position: relative;
|
|
}
|
|
|
|
.note-content :deep(img) {
|
|
max-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>
|