Mentions from your backend
With the default kit, pass a search function as mentions:
ts
import type { Editor } from '@writeon/core'
import type { KitMention } from '@writeon/kit'
interface Person {
id: string
name: string
title?: string
}
// Called with what was typed after "@".
// Answers to an older query are ignored, so a slow request
// never shows stale people.
export async function searchPeople(
query: string,
): Promise<KitMention[]> {
const q = encodeURIComponent(query)
const response = await fetch(`/api/people?q=${q}&limit=8`)
if (!response.ok) return []
const people = (await response.json()) as Person[]
return people.map((person) => ({
id: person.id,
label: person.name,
...(person.title ? { description: person.title } : {}),
}))
}
export async function mountWithMentions(
root: HTMLElement,
editor: Editor,
) {
const { mountAdvanced } = await import('@writeon/kit/advanced')
return mountAdvanced(root, editor, { mentions: searchPeople })
}- The menu opens after
@at the start of a word and closes on a space, Escape, or when nothing matches. - Choosing a person inserts a mention node with
idandlabel; theidis what you store and resolve later. Both are checked by the schema. - Results are announced to screen readers ("5 suggestions"), and focus never leaves the editor.
Mentions are plain data in the document. To notify people, read the mention nodes from the validated document on the server:
ts
import type { NodeJSON } from '@writeon/core'
function mentionedIds(node: NodeJSON, out = new Set<string>()): Set<string> {
if (node.type === 'mention' && typeof node.attrs?.id === 'string') out.add(node.attrs.id)
for (const child of node.content ?? []) mentionedIds(child, out)
return out
}Without the kit, use createSuggestionMenu(editor, { char: '@', items, label }) from @writeon/ui with insertMention() from @writeon/advanced.