Deploy deepseek 2
This commit is contained in:
302
frontend/app/components/viewer/content/EmbeddedEntry.vue
Normal file
302
frontend/app/components/viewer/content/EmbeddedEntry.vue
Normal file
@@ -0,0 +1,302 @@
|
||||
<script setup>
|
||||
// `![[Name]]` in a note mounts this card where the token was written. It resolves the label against
|
||||
// the campaign's lists and draws the character's sheet or the item's description inline; the button
|
||||
// opens the full sheet window, the same one the sidebar uses. Mounted like a widget: its only prop
|
||||
// is the label the note wrote, and it talks to the services on its own.
|
||||
import { computed, nextTick, onMounted, ref } from 'vue';
|
||||
import { getBaseUrl } from '~/services/Server';
|
||||
import { FindLinkTarget } from '~/services/LinkAutocomplete';
|
||||
import { LoadLinkEntry, LoadLinkTargets } from '~/services/LinkTargets';
|
||||
import { useCampaignService } from '~/services/Campaign';
|
||||
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
|
||||
|
||||
// `t` comes from the note as a prop: a card mounted with its own `createApp` is not inside the
|
||||
// app's plugin tree, so it cannot call `useI18n()` the way the note can.
|
||||
const props = defineProps(['href', 't']);
|
||||
const { Campaign } = useCampaignService();
|
||||
const translate = (key) => (props.t ? props.t(key) : key);
|
||||
|
||||
const target = ref(null);
|
||||
const entry = ref(null);
|
||||
const loading = ref(true);
|
||||
|
||||
const campaignId = computed(() => Campaign.value?._id ?? Campaign.value?.id ?? null);
|
||||
const isActor = computed(() => target.value?.type === 'actor');
|
||||
const isItem = computed(() => target.value?.type === 'item');
|
||||
|
||||
onMounted(async () => {
|
||||
const targets = await LoadLinkTargets(campaignId.value);
|
||||
const found = FindLinkTarget(targets, props.href);
|
||||
if (!found) {
|
||||
loading.value = false;
|
||||
return;
|
||||
}
|
||||
target.value = found;
|
||||
entry.value = await LoadLinkEntry(campaignId.value, found.type, found.id);
|
||||
loading.value = false;
|
||||
});
|
||||
|
||||
// --- The character sheet, in the small ---
|
||||
const abilityStats = [
|
||||
{ key: 'str', label: 'STR' }, { key: 'dex', label: 'DEX' }, { key: 'con', label: 'CON' },
|
||||
{ key: 'int', label: 'INT' }, { key: 'wis', label: 'WIS' }, { key: 'cha', label: 'CHA' }
|
||||
];
|
||||
|
||||
function abilityModifier(score) {
|
||||
const modifier = Math.floor((Number(score ?? 10) - 10) / 2);
|
||||
return modifier >= 0 ? `+${modifier}` : String(modifier);
|
||||
}
|
||||
|
||||
function barPercent(current, max) {
|
||||
const top = Number(max) || 0;
|
||||
return top > 0 ? Math.min(100, Math.max(0, ((Number(current) || 0) / top) * 100)) : 0;
|
||||
}
|
||||
|
||||
const hitPointsPercent = computed(() => barPercent(entry.value?.hitPoints?.current, entry.value?.hitPoints?.max));
|
||||
|
||||
const actorLine = computed(() => {
|
||||
const parts = [];
|
||||
if (entry.value?.className) parts.push(entry.value.className);
|
||||
if (entry.value?.species) parts.push(entry.value.species);
|
||||
if (entry.value?.level) parts.push(`${translate('campaigns.character-sheet.level')} ${entry.value.level}`);
|
||||
return parts.join(' · ');
|
||||
});
|
||||
|
||||
// Uploaded images are served by `/api/public`; a synced world hands over full URLs.
|
||||
function resolveImage(image) {
|
||||
if (!image) return '';
|
||||
return /^(https?:|data:|\/\/)/i.test(image)
|
||||
? image
|
||||
: `${getBaseUrl()}/public/${image}`;
|
||||
}
|
||||
|
||||
const imageUrl = computed(() => resolveImage(entry.value?.image));
|
||||
const initial = computed(() => String(entry.value?.name ?? '?').slice(0, 1).toUpperCase());
|
||||
|
||||
// --- The item's sheet, in the small ---
|
||||
const itemTags = computed(() => {
|
||||
const parts = [];
|
||||
if (entry.value?.category) parts.push(translate(`campaigns.item.categories.${entry.value.category}`));
|
||||
if (entry.value?.rarity) parts.push(translate(`campaigns.item.rarities.${entry.value.rarity}`));
|
||||
return parts;
|
||||
});
|
||||
|
||||
const weight = computed(() => {
|
||||
if (entry.value?.weight === undefined || entry.value?.weight === '') return '';
|
||||
return Number(entry.value.weight).toFixed(1);
|
||||
});
|
||||
|
||||
async function openSheet() {
|
||||
const type = target.value?.type;
|
||||
if ((type !== 'actor' && type !== 'item') || !entry.value) return;
|
||||
|
||||
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.value } : { item: entry.value });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span v-if="loading" class="embedded-entry embedded-loading">{{ href }}</span>
|
||||
|
||||
<span v-else-if="entry && isActor" class="embedded-entry embedded-actor">
|
||||
<span class="embed-head">
|
||||
<span class="embed-mark" :class="{ empty: !imageUrl }">
|
||||
<img v-if="imageUrl" :src="imageUrl" alt="">
|
||||
<span v-else aria-hidden="true">{{ initial }}</span>
|
||||
</span>
|
||||
<span class="embed-identity">
|
||||
<strong class="embed-name">{{ entry.name }}</strong>
|
||||
<span class="embed-line">{{ actorLine }}</span>
|
||||
</span>
|
||||
<button class="embed-open" type="button" @click="openSheet">
|
||||
{{ translate('campaigns.link-preview.open-character') }}
|
||||
</button>
|
||||
</span>
|
||||
</span>
|
||||
|
||||
<span v-else-if="entry && isItem" class="embedded-entry embedded-item">
|
||||
<span class="embed-head">
|
||||
<span class="embed-mark" :class="{ empty: !imageUrl }">
|
||||
<img v-if="imageUrl" :src="imageUrl" alt="">
|
||||
<span v-else aria-hidden="true">{{ initial }}</span>
|
||||
</span>
|
||||
<span class="embed-identity">
|
||||
<strong class="embed-name">{{ entry.name }}</strong>
|
||||
<span class="embed-tags">
|
||||
<span v-for="tag in itemTags" :key="tag" class="embed-tag">{{ tag }}</span>
|
||||
</span>
|
||||
</span>
|
||||
<button class="embed-open" type="button" @click="openSheet">
|
||||
{{ translate('campaigns.link-preview.open-item') }}
|
||||
</button>
|
||||
</span>
|
||||
</span>
|
||||
|
||||
<span v-else class="embedded-entry embedded-missing" :title="translate('campaigns.link-preview.not-found')">{{ href }}</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* A card written between paragraphs: it takes the note's width but is still inline content, so the
|
||||
markdown paragraph around it does not turn into an invalid block. */
|
||||
.embedded-entry {
|
||||
display: inline-block;
|
||||
width: 100%;
|
||||
margin: 8px 0;
|
||||
padding: 13px 14px;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 10px;
|
||||
background: var(--color-background-light);
|
||||
box-shadow: 0 3px 12px var(--color-window-shadow);
|
||||
color: var(--color-text);
|
||||
font-size: 13px;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.embedded-loading,
|
||||
.embedded-missing {
|
||||
color: var(--color-gray);
|
||||
font-size: 12px;
|
||||
opacity: .75;
|
||||
}
|
||||
|
||||
.embed-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 11px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.embed-mark {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
flex: 0 0 52px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 9px;
|
||||
background: var(--color-background-soft);
|
||||
color: var(--color-link);
|
||||
font: 24px MrEavesRemake;
|
||||
}
|
||||
|
||||
.embed-mark.empty { border-style: dashed; }
|
||||
.embed-mark img { width: 100%; height: 100%; object-fit: contain; }
|
||||
|
||||
.embed-identity { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 5px; }
|
||||
|
||||
.embed-name {
|
||||
font: 21px MrEavesRemake;
|
||||
letter-spacing: .02em;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.embed-line { font-size: 11px; opacity: .72; overflow-wrap: anywhere; }
|
||||
.embed-weight { display: block; margin: 0 0 10px; }
|
||||
|
||||
.embed-tags { display: flex; flex-wrap: wrap; gap: 5px; }
|
||||
|
||||
.embed-tag {
|
||||
padding: 2px 8px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 999px;
|
||||
background: var(--color-background-soft);
|
||||
font-size: 11px;
|
||||
opacity: .9;
|
||||
}
|
||||
|
||||
.embed-open {
|
||||
flex: 0 0 auto;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--color-link);
|
||||
border-radius: 7px;
|
||||
background: transparent;
|
||||
color: var(--color-link);
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.embed-open:hover { background: var(--color-button-hover); }
|
||||
|
||||
.embed-vitals { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
|
||||
|
||||
.embed-stat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
padding: 7px 4px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 7px;
|
||||
background: var(--color-background-soft);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.embed-stat span { font-size: 9px; text-transform: uppercase; letter-spacing: .05em; opacity: .68; }
|
||||
.embed-stat strong { font: 16px MrEavesRemake; white-space: nowrap; }
|
||||
|
||||
.embed-hp-track {
|
||||
display: block;
|
||||
height: 6px;
|
||||
margin: 8px 0 10px;
|
||||
overflow: hidden;
|
||||
border-radius: 999px;
|
||||
background: var(--color-background-soft);
|
||||
}
|
||||
|
||||
.embed-hp-fill { display: block; height: 100%; border-radius: inherit; background: var(--color-red); }
|
||||
|
||||
.embed-abilities { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 5px; }
|
||||
|
||||
.embed-ability {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1px;
|
||||
padding: 6px 3px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 7px;
|
||||
background: var(--color-background-soft);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.embed-ability > span:first-child { font-size: 9px; font-weight: 700; letter-spacing: .06em; opacity: .68; }
|
||||
.embed-ability strong { font: 17px MrEavesRemake; }
|
||||
.embed-ability em { font-style: normal; font-size: 10px; opacity: .72; }
|
||||
|
||||
.embed-section { display: block; margin-top: 10px; }
|
||||
|
||||
.embed-section-title {
|
||||
display: block;
|
||||
padding-bottom: 5px;
|
||||
margin-bottom: 5px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
font: 14px MrEavesRemake;
|
||||
letter-spacing: .03em;
|
||||
}
|
||||
|
||||
.embed-copy {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 5;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.45;
|
||||
opacity: .85;
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.embed-head { align-items: flex-start; flex-wrap: wrap; }
|
||||
.embed-open { margin-left: auto; }
|
||||
.embed-abilities { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
}
|
||||
</style>
|
||||
227
frontend/app/components/viewer/content/LinkPreview.vue
Normal file
227
frontend/app/components/viewer/content/LinkPreview.vue
Normal file
@@ -0,0 +1,227 @@
|
||||
<script setup>
|
||||
// The small card a note shows when the pointer rests on a `[[…]]` link to a character or an item.
|
||||
// It only reads what the sidebar lists already answer with; pressing the card's button opens the
|
||||
// full sheet window, the same one clicking the sidebar row opens.
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { getBaseUrl } from '~/services/Server';
|
||||
|
||||
const props = defineProps(['preview']);
|
||||
const emit = defineEmits(['enter', 'leave', 'close', 'open']);
|
||||
const { t } = useI18n();
|
||||
|
||||
const target = computed(() => props.preview?.target ?? {});
|
||||
const entry = computed(() => props.preview?.entry ?? {});
|
||||
const isActor = computed(() => target.value.type === 'actor');
|
||||
const isItem = computed(() => target.value.type === 'item');
|
||||
|
||||
const position = computed(() => ({
|
||||
left: `${props.preview?.x ?? 0}px`,
|
||||
top: `${props.preview?.y ?? 0}px`
|
||||
}));
|
||||
|
||||
// Uploaded images are served by `/api/public`; a synced world hands over full URLs.
|
||||
function resolveImage(image) {
|
||||
if (!image) return '';
|
||||
return /^(https?:|data:|\/\/)/i.test(image)
|
||||
? image
|
||||
: `${getBaseUrl()}/public/${image}`;
|
||||
}
|
||||
|
||||
const imageUrl = computed(() => resolveImage(entry.value.image));
|
||||
const initial = computed(() => String(entry.value.name ?? '?').slice(0, 1).toUpperCase());
|
||||
|
||||
const actorLine = computed(() => {
|
||||
const parts = [];
|
||||
if (entry.value.className) parts.push(entry.value.className);
|
||||
if (entry.value.species) parts.push(entry.value.species);
|
||||
if (entry.value.level) parts.push(`${t('campaigns.character-sheet.level')} ${entry.value.level}`);
|
||||
return parts.join(' · ');
|
||||
});
|
||||
|
||||
const itemLine = computed(() => {
|
||||
const parts = [];
|
||||
if (entry.value.category) parts.push(t(`campaigns.item.categories.${entry.value.category}`));
|
||||
if (entry.value.rarity) parts.push(t(`campaigns.item.rarities.${entry.value.rarity}`));
|
||||
return parts.join(' · ');
|
||||
});
|
||||
|
||||
const hitPoints = computed(() => {
|
||||
const hp = entry.value.hitPoints;
|
||||
if (!hp) return '';
|
||||
return `${Number(hp.current ?? 0)} / ${Number(hp.max ?? 0)}`;
|
||||
});
|
||||
|
||||
const description = computed(() => String(entry.value.description ?? '').trim());
|
||||
|
||||
const openLabel = computed(() => t(isActor.value
|
||||
? 'campaigns.link-preview.open-character'
|
||||
: 'campaigns.link-preview.open-item'));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
class="link-preview"
|
||||
:style="position"
|
||||
role="dialog"
|
||||
:aria-label="entry.name"
|
||||
@mouseenter="emit('enter')"
|
||||
@mouseleave="emit('leave')"
|
||||
>
|
||||
<div class="preview-head">
|
||||
<div class="preview-mark" :class="{ empty: !imageUrl }">
|
||||
<img v-if="imageUrl" :src="imageUrl" :alt="''">
|
||||
<span v-else aria-hidden="true">{{ initial }}</span>
|
||||
</div>
|
||||
<div class="preview-identity">
|
||||
<strong class="preview-name">{{ entry.name }}</strong>
|
||||
<span class="preview-line">{{ isActor ? actorLine : itemLine }}</span>
|
||||
</div>
|
||||
<button class="preview-close" type="button" :aria-label="$t('campaigns.link-preview.close')" @click="emit('close')">×</button>
|
||||
</div>
|
||||
|
||||
<div v-if="isActor" class="preview-stats">
|
||||
<div class="preview-stat">
|
||||
<span>{{ $t('campaigns.character-sheet.armor-class') }}</span>
|
||||
<strong>{{ entry.armorClass ?? '—' }}</strong>
|
||||
</div>
|
||||
<div class="preview-stat">
|
||||
<span>{{ $t('campaigns.character-sheet.hit-points') }}</span>
|
||||
<strong>{{ hitPoints || '—' }}</strong>
|
||||
</div>
|
||||
<div class="preview-stat">
|
||||
<span>{{ $t('campaigns.character-sheet.speed') }}</span>
|
||||
<strong>{{ entry.speed ?? '—' }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-else-if="isItem">
|
||||
<p class="preview-copy">{{ description || $t('campaigns.link-preview.no-description') }}</p>
|
||||
<p v-if="entry.weight !== undefined && entry.weight !== ''" class="preview-weight">
|
||||
{{ $t('campaigns.item.weight') }}: {{ Number(entry.weight).toFixed(1) }}
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<button class="preview-open" type="button" @click="emit('open')">{{ openLabel }}</button>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* The card floats above the notes, which scroll under it, so it is fixed to the viewport and
|
||||
positioned from the link's rectangle by Note.vue. */
|
||||
.link-preview {
|
||||
position: fixed;
|
||||
z-index: 4000;
|
||||
width: 320px;
|
||||
max-height: min(70vh, 420px);
|
||||
overflow: auto;
|
||||
padding: 13px 14px 12px;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 10px;
|
||||
background: var(--color-background-light);
|
||||
box-shadow: 0 10px 30px var(--color-window-shadow);
|
||||
color: var(--color-text);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.preview-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding-bottom: 10px;
|
||||
margin-bottom: 10px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.preview-mark {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
flex: 0 0 44px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 9px;
|
||||
background: var(--color-background-soft);
|
||||
color: var(--color-link);
|
||||
font: 21px MrEavesRemake;
|
||||
}
|
||||
|
||||
.preview-mark.empty { border-style: dashed; }
|
||||
.preview-mark img { width: 100%; height: 100%; object-fit: contain; }
|
||||
|
||||
.preview-identity { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
|
||||
|
||||
.preview-name {
|
||||
font: 18px MrEavesRemake;
|
||||
letter-spacing: .02em;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.preview-line { font-size: 11px; opacity: .72; overflow-wrap: anywhere; }
|
||||
|
||||
.preview-close {
|
||||
flex: 0 0 auto;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 5px;
|
||||
background: transparent;
|
||||
color: var(--color-text);
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.preview-close:hover { background: var(--color-button-hover); }
|
||||
|
||||
.preview-stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 7px; }
|
||||
|
||||
.preview-stat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
padding: 7px 4px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 7px;
|
||||
background: var(--color-background-soft);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.preview-stat span { font-size: 9px; text-transform: uppercase; letter-spacing: .05em; opacity: .68; }
|
||||
.preview-stat strong { font: 15px MrEavesRemake; white-space: nowrap; }
|
||||
|
||||
.preview-copy {
|
||||
margin: 0;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 5;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.45;
|
||||
opacity: .85;
|
||||
}
|
||||
|
||||
.preview-weight { margin: 7px 0 0; font-size: 11px; opacity: .68; }
|
||||
|
||||
.preview-open {
|
||||
width: 100%;
|
||||
margin-top: 11px;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid var(--color-link);
|
||||
border-radius: 7px;
|
||||
background: transparent;
|
||||
color: var(--color-link);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.preview-open:hover { background: var(--color-button-hover); }
|
||||
</style>
|
||||
@@ -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>
|
||||
|
||||
73
frontend/app/components/viewer/content/SuggestionMenu.vue
Normal file
73
frontend/app/components/viewer/content/SuggestionMenu.vue
Normal file
@@ -0,0 +1,73 @@
|
||||
<script setup>
|
||||
// The dropdown the note editor shows while a widget name or a wiki link is being typed. It only
|
||||
// draws what it is handed: each entry carries its own `label` and `hint`, and the parent decides
|
||||
// when it is open, where it sits and what is selected.
|
||||
defineProps(['suggestions', 'selected', 'position']);
|
||||
const emit = defineEmits(['select', 'hover']);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="suggestion-menu" :style="position" role="listbox">
|
||||
<div
|
||||
v-for="(suggestion, index) in suggestions"
|
||||
:key="suggestion.key"
|
||||
class="suggestion"
|
||||
:class="{ selected: index === selected }"
|
||||
role="option"
|
||||
:aria-selected="index === selected"
|
||||
@mousedown.prevent="emit('select', suggestion)"
|
||||
@mouseenter="emit('hover', index)"
|
||||
>
|
||||
<span class="suggestion-label">{{ suggestion.label }}</span>
|
||||
<span class="suggestion-hint">{{ suggestion.hint }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.suggestion-menu {
|
||||
position: absolute;
|
||||
z-index: 40;
|
||||
min-width: 190px;
|
||||
max-width: 320px;
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
padding: 4px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 6px;
|
||||
background-color: var(--color-background-light);
|
||||
box-shadow: 0 6px 18px var(--color-container-shadow);
|
||||
}
|
||||
|
||||
.suggestion {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.suggestion.selected {
|
||||
background-color: var(--color-selected);
|
||||
}
|
||||
|
||||
.suggestion-label {
|
||||
font-family: monospace;
|
||||
color: var(--color-text);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.suggestion-hint {
|
||||
font-size: 11px;
|
||||
color: var(--color-gray);
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -1,23 +1,28 @@
|
||||
<script setup>
|
||||
import { ref,onMounted } from 'vue';
|
||||
import { ref,onMounted,onUnmounted } from 'vue';
|
||||
import { emitter } from '~/services/Emitter';
|
||||
|
||||
|
||||
const statusIcon = ref(null);
|
||||
const statusMessage = ref(null);
|
||||
|
||||
emitter.on("status-bar-update", (state) => {
|
||||
const handleStatusUpdate = (state) => {
|
||||
var preloadImage = new Image();
|
||||
preloadImage.src = '/icons/Pixelarticons/black/' + state.icon + ".svg";
|
||||
preloadImage.onload = function() {
|
||||
statusIcon.value.src = this.src;
|
||||
// The update can arrive (or finish loading) while the bar is not mounted.
|
||||
if (statusIcon.value) statusIcon.value.src = this.src;
|
||||
};
|
||||
statusMessage.value.innerText = state.text;
|
||||
})
|
||||
if (statusMessage.value) statusMessage.value.innerText = state.text;
|
||||
};
|
||||
|
||||
emitter.on("status-bar-update", handleStatusUpdate);
|
||||
|
||||
onMounted(() => {
|
||||
emitter.emit("status-bar-update", {text: "Hola", icon: "check"})
|
||||
});
|
||||
|
||||
onUnmounted(() => emitter.off("status-bar-update", handleStatusUpdate));
|
||||
</script>
|
||||
<template>
|
||||
<span class="status-text">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup>
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top } from '@/services/Windows';
|
||||
import { SetupHandle, SetSize, ResetPosition, ClearWindow, CreateWindow, GetFirstWindowId, Top } from '@/services/Windows';
|
||||
import WindowHandle from './partials/WindowHandle.vue';
|
||||
import Server, { getBaseUrl } from '~/services/Server';
|
||||
import { emitter } from '~/services/Emitter';
|
||||
@@ -100,6 +100,11 @@ function normalizeActor(actor) {
|
||||
name: item.name ?? '', quantity: Number(item.quantity ?? 1), weight: Number(item.weight ?? 0),
|
||||
icon: item.icon ?? ''
|
||||
})),
|
||||
// Les capacitats del món: una filera per element, amb la seva icona. El text lliure
|
||||
// de sota continua sent el que el món no té com a element.
|
||||
features: (actor?.features ?? []).map((feature) => ({
|
||||
name: feature.name ?? '', description: feature.description ?? '', icon: feature.icon ?? ''
|
||||
})),
|
||||
traits: actor?.traits ?? '',
|
||||
spells: actor?.spells ?? '',
|
||||
image: actor?.image ?? ''
|
||||
@@ -233,6 +238,14 @@ function removeInventoryItem(index) {
|
||||
form.value.inventory.splice(index, 1);
|
||||
}
|
||||
|
||||
// Una capacitat s'obre com un objecte: la seva icona, el seu nom i la seva descripció en una
|
||||
// finestra pròpia. N'hi ha una de sola, i obrir-ne una altra substitueix la que hi ha.
|
||||
function openTrait(feature) {
|
||||
const existing = GetFirstWindowId('trait_sheet');
|
||||
if (existing !== undefined) ClearWindow({ id: existing });
|
||||
CreateWindow('trait_sheet', { feature });
|
||||
}
|
||||
|
||||
async function saveSheet() {
|
||||
if (!form.value.name.trim() || saving.value) return;
|
||||
saving.value = true;
|
||||
@@ -519,8 +532,20 @@ async function saveSheet() {
|
||||
<main v-show="activeTab === 'traits'" class="sheet-tab-body">
|
||||
<section class="sheet-panel traits-panel">
|
||||
<h2>{{ $t('campaigns.character-sheet.traits') }}</h2>
|
||||
<!-- Una capacitat per filera, amb la icona a l'esquerra com l'inventari;
|
||||
clicar-la obre la seva descripció. -->
|
||||
<div v-if="form.features.length" class="trait-list">
|
||||
<button v-for="(trait, index) in form.features" :key="index" class="trait-row" type="button" @click="openTrait(trait)">
|
||||
<span class="trait-icon-cell">
|
||||
<img v-if="trait.icon" :src="resolveImage(trait.icon)" alt="">
|
||||
<span v-else class="item-icon-blank" aria-hidden="true" />
|
||||
</span>
|
||||
<span class="trait-name">{{ trait.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<textarea v-if="editing" v-model="form.traits" rows="12" :placeholder="$t('campaigns.character-sheet.traits-placeholder')" />
|
||||
<p v-else class="sheet-copy">{{ form.traits || $t('campaigns.character-sheet.empty-traits') }}</p>
|
||||
<p v-else-if="form.traits" class="sheet-copy">{{ form.traits }}</p>
|
||||
<p v-else-if="!form.features.length" class="sheet-copy">{{ $t('campaigns.character-sheet.empty-traits') }}</p>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@@ -636,8 +661,18 @@ async function saveSheet() {
|
||||
.sheet-copy { min-height: 74px; margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; line-height: 1.45; opacity: .85; }
|
||||
input, textarea { box-sizing: border-box; max-width: 100%; padding: 6px 7px; border: 1px solid var(--color-border); border-radius: 6px; background: var(--color-background-soft); color: var(--color-text); font: inherit; }
|
||||
input:focus, textarea:focus { outline: none; border-color: var(--color-link); }
|
||||
input[type='number'] { appearance: textfield; -moz-appearance: textfield; }
|
||||
input[type='number']::-webkit-inner-spin-button, input[type='number']::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
|
||||
textarea { resize: vertical; width: 100%; min-height: 88px; font-size: 12px; }
|
||||
.traits-panel, .spells-panel { min-height: 175px; }
|
||||
/* Les capacitats de la pestanya de trets: la icona del món a l'esquerra i el nom a la dreta,
|
||||
com una filera de l'inventari. */
|
||||
.trait-list { display: flex; flex-direction: column; gap: 5px; margin-bottom: 11px; }
|
||||
.trait-row { display: flex; align-items: center; gap: 8px; width: 100%; padding: 5px 7px; border: 1px solid var(--color-border); border-radius: 7px; background: var(--color-background-soft); color: var(--color-text); font: inherit; text-align: left; cursor: pointer; }
|
||||
.trait-row:hover { border-color: var(--color-link); }
|
||||
.trait-icon-cell { width: 26px; flex: 0 0 26px; display: grid; place-items: center; }
|
||||
.trait-icon-cell img { display: block; width: 26px; height: 26px; object-fit: contain; border-radius: 5px; }
|
||||
.trait-name { flex: 1; min-width: 0; overflow-wrap: anywhere; font-size: 13px; }
|
||||
.panel-title-row { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
|
||||
.panel-title-row h2 { flex: 1; }
|
||||
.weight-summary { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin: 1px 0 7px; font-size: 12px; }
|
||||
|
||||
57
frontend/app/components/windows/TraitWindow.vue
Normal file
57
frontend/app/components/windows/TraitWindow.vue
Normal file
@@ -0,0 +1,57 @@
|
||||
<script setup>
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top } from '@/services/Windows';
|
||||
import WindowHandle from './partials/WindowHandle.vue';
|
||||
import { getBaseUrl } from '~/services/Server';
|
||||
|
||||
// A feature of the character sheet, opened from the traits tab (see CharacterSheetWindow.vue).
|
||||
// The icon, the name and the description come from the Foundry feature item the campaign synced.
|
||||
const props = defineProps(['data']);
|
||||
const id = props.data.id;
|
||||
const feature = props.data.feature ?? {};
|
||||
const handle = ref(null);
|
||||
const wrapper = ref(null);
|
||||
|
||||
onMounted(() => {
|
||||
Top(wrapper);
|
||||
SetupHandle(id, handle);
|
||||
SetSize(id, { width: 420, height: 500 });
|
||||
ResetPosition(id, 'center');
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => ClearWindow({ type: 'trait_sheet' }));
|
||||
|
||||
const imageUrl = computed(() => {
|
||||
if (!feature.icon) return '';
|
||||
return /^(https?:|data:|\/\/)/i.test(feature.icon)
|
||||
? feature.icon
|
||||
: `${getBaseUrl()}/public/${feature.icon}`;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="window-wrapper trait-window" :id="'window-wrapper-' + id" ref="wrapper">
|
||||
<WindowHandle :window="id" ref="handle" />
|
||||
<div class="trait-body">
|
||||
<header class="trait-hero">
|
||||
<span class="trait-mark" :class="{ empty: !imageUrl }">
|
||||
<img v-if="imageUrl" :src="imageUrl" alt="">
|
||||
<span v-else aria-hidden="true">{{ String(feature.name ?? '').slice(0, 1).toUpperCase() }}</span>
|
||||
</span>
|
||||
<h1>{{ feature.name }}</h1>
|
||||
</header>
|
||||
<p v-if="feature.description" class="trait-description">{{ feature.description }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.trait-window { display: flex; align-items: center; flex-direction: column; }
|
||||
.trait-body { flex: 1; min-height: 0; align-self: stretch; box-sizing: border-box; margin: 10px; padding: 8px; overflow-y: auto; }
|
||||
.trait-hero { display: flex; align-items: center; gap: 12px; padding-bottom: 10px; margin-bottom: 10px; border-bottom: 1px solid var(--color-border); }
|
||||
.trait-mark { width: 52px; height: 52px; flex: 0 0 52px; display: grid; place-items: center; overflow: hidden; border: 1px solid var(--color-border); border-radius: 9px; background: var(--color-background-soft); color: var(--color-link); font: 24px MrEavesRemake; }
|
||||
.trait-mark.empty { border-style: dashed; }
|
||||
.trait-mark img { width: 100%; height: 100%; object-fit: contain; }
|
||||
.trait-hero h1 { margin: 0; font: 22px MrEavesRemake; overflow-wrap: anywhere; }
|
||||
.trait-description { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; line-height: 1.5; opacity: .9; }
|
||||
</style>
|
||||
@@ -46,6 +46,34 @@ Headings, **bold**, *italic*, lists, quotes, tables, code and links all work:
|
||||
Clicking a heading **folds** the section under it — handy when you are reading a long note on a
|
||||
projector and only want the part you are talking about. Sub-headings fold with their parent.
|
||||
|
||||
## Linking to characters, items and other entries
|
||||
|
||||
A note can point at the rest of the campaign. While editing, type `[[` and the editor offers the
|
||||
campaign's notes, characters, items and maps; choose one and it writes a link like `[[Mira]]` (or
|
||||
`[[Rope of Climbing]]`). The list narrows as you type and the arrow keys, Enter or Tab, and Escape
|
||||
work the same way as in the widget menu.
|
||||
|
||||
In display mode the link shows the entry's name. Resting the pointer on a link to a **character** or
|
||||
an **item** opens a small preview — the portrait or icon, the class and level, armour class, hit
|
||||
points and speed for a character; the rarity, weight and description for an item — and clicking it
|
||||
opens the full sheet in its window. A link to a note opens that note beside the current one, and a
|
||||
link to a map anchors the map where the notes are.
|
||||
|
||||
Links are written by name, so renaming an entry leaves the old link pointing at nothing: it is shown
|
||||
dimmed and no longer opens anything. Write `[[` again to link the entry under its new name.
|
||||
|
||||
### Embedding a character or an item
|
||||
|
||||
Put a **!** in front of the link — `![[Mira]]` or `![[Rope of Climbing]]` — and the note shows the
|
||||
entry itself instead of a link. A character arrives as a small sheet: portrait, class, level and
|
||||
species, armour class, hit points, speed and ability scores, with the traits, proficiencies and
|
||||
spells below. An item arrives with its icon, category, rarity, weight, properties and description.
|
||||
|
||||
The embedded card is part of the note in display mode, and its **Open** button opens the full sheet,
|
||||
the same window the sidebar opens. Only characters and items can be embedded; a note or a map written
|
||||
with the **!** stays as plain text. Name resolution works exactly like a normal link, so an embed of
|
||||
an entry that has been renamed is shown dimmed.
|
||||
|
||||
## Rolling dice in a note
|
||||
|
||||
A note can hold a dice widget: a button that rolls and shows the result right there, so the book of a
|
||||
@@ -57,6 +85,11 @@ Write `@roll` and the expression in square brackets to drop it in the middle of
|
||||
The goblin attacks with @roll[1d20+4].
|
||||
```
|
||||
|
||||
The editor offers the widgets for you: while editing, typing `@` opens a list of the widgets a note
|
||||
can use, and choosing one writes its syntax — the inline `@roll[...]` or the block below — with the
|
||||
cursor where the expression goes. Arrow keys move through the list, Enter or Tab takes the widget,
|
||||
and Escape closes it.
|
||||
|
||||
Or in a block of its own, between `@roll` and `@end`, when the roll is worth showing on its own line:
|
||||
|
||||
```markdown
|
||||
@@ -69,6 +102,10 @@ Either way the widget shows the expression as a button: press it and the dice la
|
||||
the total spelled out. Press it again to roll again. Only the expression itself goes between `@roll`
|
||||
and `@end` — write the note about the roll next to the widget, not inside it.
|
||||
|
||||
When the note reaches a linked [Foundry world](/docs/foundry), its dice widgets are buttons on the
|
||||
journal page too: pressing one rolls the expression with Foundry's dice and posts the result to chat,
|
||||
where the whole table sees it.
|
||||
|
||||
The expression understands:
|
||||
|
||||
| Written | Meaning |
|
||||
|
||||
@@ -15,9 +15,15 @@ Character and item sync works without the bridge.
|
||||
|
||||
## Installing the module
|
||||
|
||||
Foundry VTT v12 to v14. Copy the `dragonroll-foundry` folder into
|
||||
`{Foundry user data}/Data/modules/dragonroll-foundry/`, restart Foundry, and enable **Dragonroll
|
||||
Foundry API** in the world's module settings.
|
||||
Foundry VTT v12 to v14. In Foundry's **Setup → Add-on Modules → Install Module**, paste the
|
||||
manifest URL `https://dragonroll.aranroig.com/foundry/module.json`. Foundry downloads the module
|
||||
from your Dragonroll server, and the same URL later tells it when an update is available.
|
||||
|
||||
A self-hosted Dragonroll serves its own manifest at `https://<your-dragonroll-host>/foundry/module.json`.
|
||||
|
||||
Then enable **Dragonroll Foundry API** in the world's module settings. To install by hand instead,
|
||||
copy the `dragonroll-foundry` folder into `{Foundry user data}/Data/modules/dragonroll-foundry/`
|
||||
and restart Foundry.
|
||||
|
||||
The module's own settings hold two things you set: the **Dragonroll Endpoint** — the address of your
|
||||
Dragonroll server, `https://dragonroll.aranroig.com` by default — and **Dragonroll Auto-sync**, which
|
||||
@@ -52,7 +58,7 @@ Worth knowing:
|
||||
| The folders grouping that item directory | Item folders with the same names and nesting |
|
||||
| A folder's colour | The campaign's folder colour — and the other way round, what you colour in Dragonroll lands on the world's folder |
|
||||
| The world's **scenes** | The campaign's maps: the scene's background picture and the grid laid over it, in the scene's own cell size |
|
||||
| A journal called **Dragonroll** — one page per note | Your campaign's notes. They arrive **from** Dragonroll: what you write in the journal does not go back |
|
||||
| A journal per note folder, named after its path — one page per note | Your campaign's notes. They arrive **from** Dragonroll: what you write in a journal does not go back |
|
||||
|
||||
The item list is the world's item directory and nothing else. The gear a character carries is that
|
||||
character's inventory: it travels with the character and stays on its sheet, so a sword a fighter owns
|
||||
@@ -78,11 +84,20 @@ few seconds. A **full** snapshot — the one taken when the world links, or forc
|
||||
directory — is the only thing that prunes: it is the only moment either side can see the whole list and
|
||||
notice what is gone. Live edits never delete anything.
|
||||
|
||||
Notes are the exception that runs one way, because notes are written in Dragonroll: every note stands
|
||||
as a page of a single journal called **Dragonroll**. A note you make or edit in the app appears on that
|
||||
journal within a few seconds, and deleting one takes its page with it. Pages the campaign does not own
|
||||
— one the GM made in that journal themselves — are left alone, and nothing written in the journal
|
||||
travels back to the campaign.
|
||||
Notes are the exception that runs one way, because notes are written in Dragonroll: each folder
|
||||
stands as a journal named after its path. Notes in the root of the campaign share the journal called
|
||||
**Dragonroll**, while notes in a folder called *Sessions* with a subfolder *Arc 1* share the journal
|
||||
**Sessions / Arc 1**; every note is a page of the journal of its folder. A note's dice widgets are
|
||||
buttons there as well: press one in the journal and Foundry rolls it and posts the result to chat, so
|
||||
advantage and disadvantage roll the way the campaign's notes describe them. The note's `[[links]]`
|
||||
work in the page too: a link to a note page, a character, an item or a scene opens it in Foundry, and
|
||||
`![[a character or item]]` is drawn as a sheet preview inside the page. Renaming a folder renames
|
||||
its journal, and moving a note to another folder moves its page along. The module only pulls the notes
|
||||
over when something has changed, checking every fifteen seconds, so a note you make, edit or move in
|
||||
the app appears in its journal within that time, and deleting one takes its page with it. Pages the
|
||||
campaign does not own — ones the GM made in those journals themselves — are left alone, and nothing
|
||||
written in a journal travels back to the campaign. A folder journal whose notes have all left is
|
||||
removed too, unless the GM keeps pages of their own in it.
|
||||
|
||||
## Auto-sync, and sending one actor on purpose
|
||||
|
||||
|
||||
109
frontend/app/services/LinkAutocomplete.js
Normal file
109
frontend/app/services/LinkAutocomplete.js
Normal file
@@ -0,0 +1,109 @@
|
||||
// The rules behind the note editor's wiki-link autocomplete (type `[[` while editing a note and the
|
||||
// campaign's notes, actors, items and maps are offered to link to). These helpers hold no state,
|
||||
// touch no DOM and import nothing, so tests can load them straight from source. Marker.js renders
|
||||
// `[[target]]` as a link, so the target written here is the entry's label.
|
||||
|
||||
// Accent- and case-insensitive, the way the search palette compares names.
|
||||
function Normalize(text) {
|
||||
return String(text ?? '')
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.toLowerCase()
|
||||
.trim();
|
||||
}
|
||||
|
||||
// The `[[target` the caret is sitting in. `[[The Wr` answers `{ start, query: 'The Wr' }`.
|
||||
//
|
||||
// A link is a single line: a `]]` or a newline between the `[[` and the caret closes the token, so
|
||||
// the menu only follows the link currently being typed. Returns null when there is none.
|
||||
function FindLinkTrigger(text, caret) {
|
||||
if (typeof text !== 'string') return null;
|
||||
const position = Math.max(0, Math.min(Number(caret) || 0, text.length));
|
||||
|
||||
const before = text.slice(0, position);
|
||||
const start = before.lastIndexOf('[[');
|
||||
if (start === -1) return null;
|
||||
|
||||
const query = before.slice(start + 2);
|
||||
if (query.includes(']]') || query.includes('\n')) return null;
|
||||
|
||||
return { start, query };
|
||||
}
|
||||
|
||||
// One `{ id, label, type }` per linkable entry, from the campaign's four lists. Entries without a
|
||||
// name are left out (they would show as an empty menu row), the rest are sorted by label so the menu
|
||||
// reads alphabetically whatever order the API answered with.
|
||||
function BuildLinkSuggestions({ notes, actors, items, maps } = {}) {
|
||||
const suggestions = [];
|
||||
const seen = new Set();
|
||||
|
||||
const push = (type, list, labelOf) => {
|
||||
for (const entry of list ?? []) {
|
||||
const label = String(labelOf(entry) ?? '').trim();
|
||||
if (!entry?._id || !label) continue;
|
||||
const key = `${type}:${label}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
suggestions.push({ id: String(entry._id), label, type });
|
||||
}
|
||||
};
|
||||
|
||||
push('note', notes, (note) => note.title);
|
||||
push('actor', actors, (actor) => actor.name);
|
||||
push('item', items, (item) => item.name);
|
||||
push('map', maps, (map) => map.name);
|
||||
|
||||
return suggestions.sort((a, b) => a.label.localeCompare(b.label));
|
||||
}
|
||||
|
||||
// The suggestions matching what has been typed. An empty query offers them all; the ones whose label
|
||||
// starts with it come first, and a match further inside still shows, the way search does it. The list
|
||||
// is capped so a large campaign cannot open a menu taller than the note.
|
||||
const MAX_SUGGESTIONS = 50;
|
||||
|
||||
function FilterLinkSuggestions(suggestions, query) {
|
||||
const needle = Normalize(query);
|
||||
const all = suggestions ?? [];
|
||||
if (!needle) return all.slice(0, MAX_SUGGESTIONS);
|
||||
|
||||
return all
|
||||
.filter((suggestion) => Normalize(suggestion.label).includes(needle))
|
||||
.sort((a, b) => {
|
||||
const startsA = Normalize(a.label).startsWith(needle) ? 0 : 1;
|
||||
const startsB = Normalize(b.label).startsWith(needle) ? 0 : 1;
|
||||
return startsA - startsB || a.label.localeCompare(b.label);
|
||||
})
|
||||
.slice(0, MAX_SUGGESTIONS);
|
||||
}
|
||||
|
||||
// The entry a written `[[label]]` points at. Links store the label (not the id), so the note looks
|
||||
// the target up again when it is rendered; the comparison is the same case- and accent-insensitive
|
||||
// one the menu uses. Returns null when nothing in the campaign carries that label any more.
|
||||
function FindLinkTarget(suggestions, label) {
|
||||
const needle = Normalize(label);
|
||||
if (!needle) return null;
|
||||
|
||||
return (suggestions ?? []).find((suggestion) => Normalize(suggestion.label) === needle) ?? null;
|
||||
}
|
||||
|
||||
// Replaces the typed `[[query` with `[[label]]` and returns where the caret goes: just after the
|
||||
// closing brackets, ready to carry on with the note.
|
||||
function InsertLinkSuggestion(text, trigger, suggestion) {
|
||||
const source = String(text ?? '');
|
||||
const start = trigger?.start ?? 0;
|
||||
const query = trigger?.query ?? '';
|
||||
|
||||
const before = source.slice(0, start);
|
||||
const after = source.slice(start + 2 + query.length);
|
||||
const snippet = `[[${suggestion?.label ?? ''}]]`;
|
||||
|
||||
return { text: before + snippet + after, caret: start + snippet.length };
|
||||
}
|
||||
|
||||
export {
|
||||
BuildLinkSuggestions,
|
||||
FilterLinkSuggestions,
|
||||
FindLinkTarget,
|
||||
FindLinkTrigger,
|
||||
InsertLinkSuggestion
|
||||
};
|
||||
71
frontend/app/services/LinkTargets.js
Normal file
71
frontend/app/services/LinkTargets.js
Normal file
@@ -0,0 +1,71 @@
|
||||
// Fetches the campaign entries a note can link to (`[[…]]`) and keeps them briefly, so the several
|
||||
// notes a campaign has open share one round of requests. The rules that turn the entries into
|
||||
// suggestions live in LinkAutocomplete.js; this only talks to the API.
|
||||
import Server from './Server';
|
||||
import { BuildLinkSuggestions } from './LinkAutocomplete';
|
||||
|
||||
// Long enough to spare the API while a note is being written, short enough that an entry created in
|
||||
// another note shows up soon after.
|
||||
const CACHE_TTL = 30 * 1000;
|
||||
const cache = new Map(); // campaignId → { at, promise }
|
||||
|
||||
// The campaign's four lists as the API answers them. The note preview needs the entry itself (a
|
||||
// character sheet, an item), not only the label the suggestion carries, so the lists are kept as
|
||||
// they arrive and both readers resolve from the same round of requests.
|
||||
const LIST_PATHS = {
|
||||
note: { path: '/note/all', key: 'notes' },
|
||||
actor: { path: '/actor/list', key: 'actors' },
|
||||
item: { path: '/item/list', key: 'items' },
|
||||
map: { path: '/map/list', key: 'maps' }
|
||||
};
|
||||
|
||||
async function fetchList(campaignId, path, key) {
|
||||
try {
|
||||
const response = await Server().get(path, { params: { campaign: campaignId } });
|
||||
if (response.data.status !== 'ok') return [];
|
||||
return response.data[key] ?? [];
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function LoadCampaignEntries(campaignId) {
|
||||
const id = campaignId ? String(campaignId) : '';
|
||||
if (!id) {
|
||||
return Promise.resolve({ notes: [], actors: [], items: [], maps: [] });
|
||||
}
|
||||
|
||||
const cached = cache.get(id);
|
||||
if (cached && Date.now() - cached.at < CACHE_TTL) return cached.promise;
|
||||
|
||||
const promise = Promise.all(
|
||||
Object.values(LIST_PATHS).map(({ path, key }) => fetchList(id, path, key))
|
||||
).then(([notes, actors, items, maps]) => ({ notes, actors, items, maps }));
|
||||
|
||||
cache.set(id, { at: Date.now(), promise });
|
||||
return promise;
|
||||
}
|
||||
|
||||
// The campaign's linkable entries, as BuildLinkSuggestions answers. Without a campaign id there is
|
||||
// nothing to offer.
|
||||
function LoadLinkTargets(campaignId) {
|
||||
return LoadCampaignEntries(campaignId).then((lists) => BuildLinkSuggestions(lists));
|
||||
}
|
||||
|
||||
// The entry a link points at, for the preview the note shows on hover (and to open its sheet). The
|
||||
// target is one of the suggestions `LoadLinkTargets` answered; the lists it lives in are already
|
||||
// cached, so this does not make another request.
|
||||
function LoadLinkEntry(campaignId, type, id) {
|
||||
const list = LIST_PATHS[type];
|
||||
if (!list) return Promise.resolve(null);
|
||||
|
||||
return LoadCampaignEntries(campaignId).then((lists) => {
|
||||
return (lists[list.key] ?? []).find((entry) => String(entry._id) === String(id)) ?? null;
|
||||
});
|
||||
}
|
||||
|
||||
function ClearLinkTargets() {
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
export { LoadLinkTargets, LoadLinkEntry, ClearLinkTargets };
|
||||
@@ -88,6 +88,32 @@ const inlineExtension = {
|
||||
},
|
||||
};
|
||||
|
||||
// `![[Name]]` embeds the entry itself instead of linking it: the note mounts a card with the
|
||||
// character's sheet or the item's description where the token was written.
|
||||
const embedExtension = {
|
||||
name: "embed",
|
||||
level: "inline",
|
||||
start(src) {
|
||||
return src.indexOf("![[");
|
||||
},
|
||||
|
||||
tokenizer(src) {
|
||||
const rule = /^!\[\[([^\n]*)\]\]/;
|
||||
const match = rule.exec(src);
|
||||
if (!match) return;
|
||||
|
||||
return {
|
||||
type: "embed",
|
||||
raw: match[0],
|
||||
link: match[1],
|
||||
};
|
||||
},
|
||||
|
||||
renderer(token) {
|
||||
return `<span class="vue-embed" data-href="${escapeAttr(token.link)}"></span>`;
|
||||
},
|
||||
};
|
||||
|
||||
const linkExtension = {
|
||||
name: "link_to",
|
||||
level: "inline",
|
||||
@@ -108,16 +134,32 @@ const linkExtension = {
|
||||
},
|
||||
|
||||
renderer(token) {
|
||||
return `<span class="vue-link" data-href="${escapeAttr(token.link)}">Link</span>`;
|
||||
// The link shows the entry's name, not a generic "Link", so a note reads as written. The
|
||||
// note looks the target up by this label and turns the span into a preview link.
|
||||
const label = String(token.link ?? "").trim() || token.link;
|
||||
return `<span class="vue-link" data-href="${escapeAttr(token.link)}" role="link" tabindex="0">${escapeAttr(label)}</span>`;
|
||||
},
|
||||
};
|
||||
|
||||
marker.use({
|
||||
extensions: [extension, inlineExtension, linkExtension],
|
||||
// The embed comes before the link: at the `!` of `![[…]]` the embed tokenizer is offered first,
|
||||
// so the same label written with the bang does not fall through to the plain link.
|
||||
extensions: [extension, inlineExtension, embedExtension, linkExtension],
|
||||
});
|
||||
|
||||
function ParseMarkdown(source) {
|
||||
return marker.parse(source || "");
|
||||
}
|
||||
|
||||
export { ParseMarkdown, GetWidget };
|
||||
// The widgets a note can use, as `{ inline: [...names], display: [...names] }`. The note editor's
|
||||
// `@` autocomplete reads this, so a widget added to `widget_map` is offered there without any other
|
||||
// change.
|
||||
const GetWidgetRegistry = () => {
|
||||
const registry = {};
|
||||
for (const type of Object.keys(widget_map)) {
|
||||
registry[type] = Object.keys(widget_map[type]);
|
||||
}
|
||||
return registry;
|
||||
};
|
||||
|
||||
export { ParseMarkdown, GetWidget, GetWidgetRegistry };
|
||||
78
frontend/app/services/WidgetAutocomplete.js
Normal file
78
frontend/app/services/WidgetAutocomplete.js
Normal file
@@ -0,0 +1,78 @@
|
||||
// The rules behind the note editor's widget autocomplete (type `@` while editing a note and the
|
||||
// widgets of Marker.js are offered to insert). These helpers hold no state, touch no DOM and import
|
||||
// nothing, so tests can load them straight from source.
|
||||
|
||||
// What counts as a widget name while the user is typing one, matching the `\w+` Marker.js reads.
|
||||
const NAME_CHARACTER = /[A-Za-z0-9_]/;
|
||||
|
||||
// The `@name` the caret is sitting in. Typing `@ro` answers `{ start, query: 'ro' }`, ready to be
|
||||
// replaced by the chosen widget.
|
||||
//
|
||||
// The `@` has to open a word (start of the note, whitespace or punctuation before it) so an email
|
||||
// address does not pop the menu open. Returns null when the caret is not in such a token.
|
||||
function FindWidgetTrigger(text, caret) {
|
||||
if (typeof text !== 'string') return null;
|
||||
const position = Math.max(0, Math.min(Number(caret) || 0, text.length));
|
||||
|
||||
let start = position;
|
||||
while (start > 0 && NAME_CHARACTER.test(text[start - 1])) start--;
|
||||
|
||||
const at = start - 1;
|
||||
if (at < 0 || text[at] !== '@') return null;
|
||||
|
||||
const before = at > 0 ? text[at - 1] : '';
|
||||
if (before && NAME_CHARACTER.test(before)) return null;
|
||||
|
||||
return { start: at, query: text.slice(start, position) };
|
||||
}
|
||||
|
||||
// The widgets to offer, one entry per way to write each one (`type` is what Marker.js renders:
|
||||
// `inline` for `@roll[...]`, `display` for the `@roll … @end` block). `registry` is the map of
|
||||
// widget names per type that GetWidgetRegistry() answers with, so a widget is described once, in
|
||||
// Marker.js, and shows up here on its own.
|
||||
function BuildWidgetSuggestions(registry) {
|
||||
const suggestions = [];
|
||||
for (const type of ['inline', 'display']) {
|
||||
for (const name of registry?.[type] ?? []) {
|
||||
suggestions.push({ name: String(name), type });
|
||||
}
|
||||
}
|
||||
return suggestions;
|
||||
}
|
||||
|
||||
// The suggestions whose name starts with what has been typed. An empty query offers them all.
|
||||
function FilterWidgetSuggestions(suggestions, query) {
|
||||
const needle = String(query ?? '').toLowerCase();
|
||||
const all = suggestions ?? [];
|
||||
if (!needle) return all.slice();
|
||||
return all.filter((suggestion) => suggestion.name.toLowerCase().startsWith(needle));
|
||||
}
|
||||
|
||||
// Replaces the typed `@query` with the widget's syntax and says where the caret goes afterwards:
|
||||
// inside the brackets for an inline widget (`@roll[]`), on the blank line of a block (`@roll\n\n@end`).
|
||||
function InsertWidgetSuggestion(text, trigger, suggestion) {
|
||||
const source = String(text ?? '');
|
||||
const start = trigger?.start ?? 0;
|
||||
const query = trigger?.query ?? '';
|
||||
const name = suggestion?.name ?? '';
|
||||
|
||||
const before = source.slice(0, start);
|
||||
const after = source.slice(start + 1 + query.length);
|
||||
|
||||
const snippet = suggestion?.type === 'display'
|
||||
? `@${name}\n\n@end`
|
||||
: `@${name}[]`;
|
||||
|
||||
return {
|
||||
text: before + snippet + after,
|
||||
// 1 for the `@` and 1 for either the opening bracket or the blank line.
|
||||
caret: start + name.length + 2
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
BuildWidgetSuggestions,
|
||||
FilterWidgetSuggestions,
|
||||
FindWidgetTrigger,
|
||||
InsertWidgetSuggestion
|
||||
};
|
||||
@@ -82,6 +82,12 @@ const defWindows = {
|
||||
close: () => ClearWindow({type: 'character_sheet'}),
|
||||
movable: true
|
||||
},
|
||||
trait_sheet: {
|
||||
title: 'windows.trait-sheet',
|
||||
component: () => import('~/components/windows/TraitWindow.vue'),
|
||||
close: () => ClearWindow({ type: 'trait_sheet' }),
|
||||
movable: true
|
||||
},
|
||||
item_sheet: {
|
||||
title: 'windows.item-sheet',
|
||||
component: () => import('~/components/windows/ItemSheetWindow.vue'),
|
||||
|
||||
Reference in New Issue
Block a user