add entity mention extension with search autocomplete

This commit is contained in:
Justin Edmund 2025-12-21 16:32:49 -08:00
parent a37a950be2
commit cfcf59f2d9
6 changed files with 525 additions and 0 deletions

View file

@ -491,3 +491,51 @@ input[type='checkbox'] {
color: var(--color-destructive);
border: 1px solid darkred;
}
/* Entity Mention Styles - .tiptap prefix for specificity over .tiptap a */
.tiptap a.entity-mention,
.tiptap a.entity-mention:hover,
.tiptap a.entity-mention:visited {
padding: 2px 6px;
border-radius: 4px;
text-decoration: none;
font-weight: 500;
transition: background 0.15s, opacity 0.15s;
background: rgba(128, 128, 128, 0.2);
color: var(--text-primary);
}
.tiptap a.entity-mention:hover {
opacity: 0.8;
}
/* Element-specific mention colors */
.tiptap a.entity-mention[data-element='wind'] {
background: rgba(48, 195, 114, 0.2);
color: #1dc688;
}
.tiptap a.entity-mention[data-element='fire'] {
background: rgba(224, 85, 85, 0.2);
color: #ec5c5c;
}
.tiptap a.entity-mention[data-element='water'] {
background: rgba(66, 165, 245, 0.2);
color: #42a5f5;
}
.tiptap a.entity-mention[data-element='earth'] {
background: rgba(198, 134, 66, 0.2);
color: #c68642;
}
.tiptap a.entity-mention[data-element='dark'] {
background: rgba(156, 39, 176, 0.2);
color: #ba68c8;
}
.tiptap a.entity-mention[data-element='light'] {
background: rgba(255, 193, 7, 0.2);
color: #ffc107;
}

View file

@ -14,6 +14,8 @@ import { Table, TableCell, TableRow, TableHeader } from './extensions/table/inde
import { Placeholder } from '@tiptap/extensions';
import { Markdown } from '@tiptap/markdown';
import MathMatics from '@tiptap/extension-mathematics';
import Youtube from '@tiptap/extension-youtube';
import { EntityMention, createEntityMentionSuggestion } from './extensions/entity-mention/index.js';
import AutoJoiner from 'tiptap-extension-auto-joiner';
import 'katex/dist/katex.min.css';
@ -116,6 +118,16 @@ export default (
TableRow,
TableCell,
Markdown,
Youtube.configure({
inline: false,
modestBranding: true
}),
EntityMention.configure({
HTMLAttributes: {
class: 'entity-mention'
},
suggestion: createEntityMentionSuggestion()
}),
...(extensions ?? [])
],
...options

View file

@ -0,0 +1,73 @@
/**
* EntityMention Extension
*
* Extends Tiptap's Mention extension to handle game entity mentions
* (characters, weapons, summons). Renders as clickable links to gbf.wiki.
*/
import Mention from '@tiptap/extension-mention'
import { mergeAttributes } from '@tiptap/core'
/** Element ID to slug mapping */
const ELEMENT_SLUGS: Record<number, string> = {
0: 'null',
1: 'wind',
2: 'fire',
3: 'water',
4: 'earth',
5: 'dark',
6: 'light'
}
/**
* Gets the element slug from various attribute formats
* Handles both legacy (object with slug) and new (numeric) formats
*/
function getElementSlug(element: unknown): string {
if (!element) return 'null'
// Handle object format: { id: number, slug: string, ... }
if (typeof element === 'object' && element !== null && 'slug' in element) {
return (element as { slug: string }).slug
}
// Handle numeric format
if (typeof element === 'number') {
return ELEMENT_SLUGS[element] ?? 'null'
}
return 'null'
}
export const EntityMention = Mention.extend({
name: 'mention',
renderHTML({ node, HTMLAttributes }) {
const id = node.attrs.id
// Extract name - handle various formats from legacy data
const name = id?.name?.en ?? id?.granblue_en ?? 'Unknown'
// Get element slug for styling
const elementSlug = getElementSlug(id?.element)
// Get entity type for additional styling/tracking
const entityType = id?.type ?? id?.searchableType?.toLowerCase() ?? 'unknown'
return [
'a',
mergeAttributes(
{
href: `https://gbf.wiki/${encodeURIComponent(name.replace(/ /g, '_'))}`,
target: '_blank',
rel: 'noopener noreferrer'
},
{ 'data-type': this.name },
{ 'data-element': elementSlug },
{ 'data-entity-type': entityType },
this.options.HTMLAttributes,
HTMLAttributes
),
name
]
}
})

View file

@ -0,0 +1,239 @@
<script lang="ts">
/**
* EntityMentionList - Dropdown for entity mention suggestions
*
* Shows search results for characters, weapons, and summons when typing @
* Supports keyboard navigation and displays entity images with element colors.
*/
import { getBasePath } from '$lib/utils/images'
import { getElementClass } from '$lib/utils/element'
import type { UnifiedSearchResult } from '$lib/api/adapters/search.adapter'
interface Props {
items: UnifiedSearchResult[]
command: (item: EntityMentionData) => void
query: string
}
/** Data structure passed to the mention command */
export interface EntityMentionData {
granblue_id: string
name: { en: string; ja: string }
type: string
element: { id: number; slug: string }
}
let { items, command, query }: Props = $props()
let selectedIndex = $state(0)
// Reset selection when items change
$effect(() => {
void items
selectedIndex = 0
})
function getEntityImageUrl(item: UnifiedSearchResult): string {
const base = getBasePath()
const type = item.searchableType.toLowerCase()
const id = item.granblueId
if (type === 'character') {
return `${base}/character-square/${id}_01.jpg`
}
return `${base}/${type}-square/${id}.jpg`
}
function getElementSlug(element?: number): string {
const slugs: Record<number, string> = {
0: 'null',
1: 'wind',
2: 'fire',
3: 'water',
4: 'earth',
5: 'dark',
6: 'light'
}
return slugs[element ?? 0] ?? 'null'
}
function selectItem(index: number) {
const item = items[index]
if (!item) return
command({
granblue_id: item.granblueId,
name: {
en: item.nameEn ?? 'Unknown',
ja: item.nameJp ?? 'Unknown'
},
type: item.searchableType.toLowerCase(),
element: {
id: item.element ?? 0,
slug: getElementSlug(item.element)
}
})
}
function upHandler() {
selectedIndex = (selectedIndex + items.length - 1) % items.length
}
function downHandler() {
selectedIndex = (selectedIndex + 1) % items.length
}
function enterHandler() {
selectItem(selectedIndex)
}
/** Exposed for keyboard handling from suggestion plugin */
export function onKeyDown(event: KeyboardEvent): boolean {
if (event.key === 'ArrowUp') {
upHandler()
return true
}
if (event.key === 'ArrowDown') {
downHandler()
return true
}
if (event.key === 'Enter') {
enterHandler()
return true
}
return false
}
</script>
<div class="entity-mention-list">
{#if items.length > 0}
{#each items as item, index}
<button
type="button"
class="mention-item"
class:selected={index === selectedIndex}
class:element-wind={item.element === 1}
class:element-fire={item.element === 2}
class:element-water={item.element === 3}
class:element-earth={item.element === 4}
class:element-dark={item.element === 5}
class:element-light={item.element === 6}
onclick={() => selectItem(index)}
>
<div class="item-image {item.searchableType.toLowerCase()}">
<img src={getEntityImageUrl(item)} alt={item.nameEn ?? ''} loading="lazy" />
</div>
<span class="item-name">{item.nameEn ?? item.nameJp ?? 'Unknown'}</span>
</button>
{/each}
{:else}
<div class="no-results">
{#if query.length < 2}
Type at least 2 characters to search
{:else}
No results found
{/if}
</div>
{/if}
</div>
<style lang="scss">
@use '$src/themes/spacing' as *;
@use '$src/themes/colors' as *;
@use '$src/themes/typography' as *;
@use '$src/themes/layout' as *;
.entity-mention-list {
background: var(--dialog-bg);
border: 1px solid var(--border-color);
border-radius: $card-corner;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
overflow: hidden;
min-width: 200px;
max-width: 300px;
max-height: 280px;
overflow-y: auto;
}
.mention-item {
display: flex;
align-items: center;
gap: $unit;
width: 100%;
padding: $unit $unit-2x;
border: none;
background: transparent;
cursor: pointer;
text-align: left;
transition: background 0.1s;
&:hover,
&.selected {
background: var(--option-bg-hover);
}
}
.item-image {
width: 32px;
height: 32px;
border-radius: 4px;
overflow: hidden;
flex-shrink: 0;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
&.character {
border-radius: 50%;
}
}
.item-name {
flex: 1;
font-size: $font-regular;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
// Element indicator on hover/selection
.mention-item {
border-left: 3px solid transparent;
&.element-wind.selected,
&.element-wind:hover {
border-left-color: $wind-bg-00;
}
&.element-fire.selected,
&.element-fire:hover {
border-left-color: $fire-bg-00;
}
&.element-water.selected,
&.element-water:hover {
border-left-color: $water-bg-00;
}
&.element-earth.selected,
&.element-earth:hover {
border-left-color: $earth-bg-00;
}
&.element-dark.selected,
&.element-dark:hover {
border-left-color: $dark-bg-00;
}
&.element-light.selected,
&.element-light:hover {
border-left-color: $light-bg-00;
}
}
.no-results {
padding: $unit-2x;
text-align: center;
color: var(--text-secondary);
font-size: $font-small;
}
</style>

View file

@ -0,0 +1,3 @@
export { EntityMention } from './EntityMention.js'
export { createEntityMentionSuggestion } from './suggestion.js'
export type { EntityMentionData } from './EntityMentionList.svelte'

View file

@ -0,0 +1,150 @@
/**
* Entity Mention Suggestion Configuration
*
* Configures the Tiptap suggestion plugin for entity mentions.
* Handles search API calls and renders the dropdown using Svelte.
*/
import type { SuggestionOptions, SuggestionProps, SuggestionKeyDownProps } from '@tiptap/suggestion'
import { searchAdapter } from '$lib/api/adapters/search.adapter'
import type { UnifiedSearchResult } from '$lib/api/adapters/search.adapter'
import { mount, unmount } from 'svelte'
import EntityMentionList from './EntityMentionList.svelte'
import type { EntityMentionData } from './EntityMentionList.svelte'
interface MentionItem extends UnifiedSearchResult {}
/**
* Creates the suggestion configuration for entity mentions
*/
export function createEntityMentionSuggestion(): Omit<SuggestionOptions<MentionItem>, 'editor'> {
return {
char: '@',
allowSpaces: false,
items: async ({ query }): Promise<MentionItem[]> => {
// Require at least 2 characters to search
if (query.length < 2) return []
try {
const response = await searchAdapter.searchAll({
query,
per: 7
})
return response.results
} catch (error) {
console.error('Entity mention search failed:', error)
return []
}
},
render: () => {
let container: HTMLElement | null = null
let component: ReturnType<typeof mount> | null = null
let componentInstance: { onKeyDown: (event: KeyboardEvent) => boolean } | null = null
return {
onStart: (props: SuggestionProps<MentionItem>) => {
// Create container element
container = document.createElement('div')
container.className = 'entity-mention-popup'
document.body.appendChild(container)
// Mount Svelte component
component = mount(EntityMentionList, {
target: container,
props: {
items: props.items,
command: (item: EntityMentionData) => {
props.command({ id: item })
},
query: props.query
}
})
// Store reference for keyboard handling
// The component exports onKeyDown
componentInstance = component as unknown as { onKeyDown: (event: KeyboardEvent) => boolean }
// Position the popup
updatePosition(container, props.clientRect)
},
onUpdate: (props: SuggestionProps<MentionItem>) => {
if (!component || !container) return
// Update component props - Svelte 5 style
// We need to remount with new props since mount() doesn't return reactive props
unmount(component)
component = mount(EntityMentionList, {
target: container,
props: {
items: props.items,
command: (item: EntityMentionData) => {
props.command({ id: item })
},
query: props.query
}
})
componentInstance = component as unknown as { onKeyDown: (event: KeyboardEvent) => boolean }
// Update position
updatePosition(container, props.clientRect)
},
onKeyDown: (props: SuggestionKeyDownProps): boolean => {
if (props.event.key === 'Escape') {
return true
}
// Delegate to component for arrow/enter handling
if (componentInstance?.onKeyDown) {
return componentInstance.onKeyDown(props.event)
}
return false
},
onExit: () => {
if (component) {
unmount(component)
component = null
}
if (container) {
container.remove()
container = null
}
componentInstance = null
}
}
}
}
}
/**
* Positions the popup near the cursor
*/
function updatePosition(
container: HTMLElement,
clientRect: (() => DOMRect | null) | null | undefined
) {
if (!clientRect) return
const rect = clientRect()
if (!rect) return
// Position below the cursor
const top = rect.bottom + 8
const left = rect.left
// Check if popup would go off-screen
const viewportHeight = window.innerHeight
const popupHeight = 280 // max-height from styles
// If not enough space below, position above
const actualTop = top + popupHeight > viewportHeight ? rect.top - popupHeight - 8 : top
container.style.position = 'fixed'
container.style.top = `${actualTop}px`
container.style.left = `${left}px`
container.style.zIndex = '1000'
}