// One line of rich text (a title, an abstract): a single-paragraph TipTap // document, content in and out as ProseMirror inline JSON, Enter reported // to the host. import { LitElement, html, nothing, type PropertyValues } from 'lit'; import { Editor, posToDOMRect } from '@tiptap/core'; import type { Node as PMNode } from '@tiptap/pm/model'; import { BubbleMenu } from '@tiptap/extension-bubble-menu'; import { lineExtensions } from '../schema/extensions.ts'; import { fillBubble, FULL_FEATURES, SIMPLE_FEATURES } from './bubble.ts'; import type { PMJson } from '../types.ts'; type Prompt = { kind: 'link' | 'ref'; fields: Record; x: number; y: number; apply: (fields: Record) => void }; type MathEdit = { pos: number; latex: string; x: number; y: number }; const stable = (content: PMJson[]) => JSON.stringify(content); export class DraftLine extends LitElement { static properties = { content: { attribute: false }, mode: { type: String }, placeholder: { type: String }, prompt: { state: true }, mathEdit: { state: true } }; /** The paragraph's inline content. */ declare content: PMJson[]; declare mode: 'simple' | 'full'; declare placeholder: string; declare prompt: Prompt | null; declare mathEdit: MathEdit | null; #editor: Editor | null = null; #lastEmitted = ''; #bubble: { update: () => void } | null = null; constructor() { super(); this.content = []; this.mode = 'full'; this.placeholder = ''; this.prompt = null; this.mathEdit = null; } protected override createRenderRoot() { return this; } get editor(): Editor | null { return this.#editor; } #doc(content: PMJson[]): PMJson { return { type: 'doc', content: [content.length ? { type: 'paragraph', content } : { type: 'paragraph' }] }; } override firstUpdated(): void { const surface = this.querySelector('.surface') as HTMLElement; const bubbleEl = document.createElement('div'); const editor = new Editor({ element: surface, extensions: [ ...lineExtensions(this.mode, () => this.dispatchEvent(new CustomEvent('enter')), { onMathClick: (node, pos) => this.#openMath(node, pos) }, () => this.placeholder), BubbleMenu.configure({ element: bubbleEl, appendTo: () => this.querySelector('.chrome') as HTMLElement, shouldShow: ({ from, to }) => from !== to, options: { placement: 'top-start' }, }), ], content: this.#doc(this.content) as never, editorProps: { attributes: { class: 'line', spellcheck: 'true', 'data-placeholder': this.placeholder }, handleKeyDown: (_view, e) => { if ((e.metaKey || e.ctrlKey) && !e.altKey && this.mode === 'full') { const k = e.key.toLowerCase(); if (k === 'k') { e.preventDefault(); this.#linkPrompt(); return true; } if (k === 'r' && e.shiftKey) { e.preventDefault(); this.#refPrompt(); return true; } } if (e.key === 'Escape' && (this.prompt || this.mathEdit)) { this.prompt = null; this.mathEdit = null; return true; } return false; }, }, onUpdate: ({ editor: e }) => { const json = e.getJSON() as PMJson; const content = json.content?.[0]?.content ?? []; this.#lastEmitted = stable(content); this.content = content; this.dispatchEvent(new CustomEvent('change', { detail: content })); }, onSelectionUpdate: () => this.#bubble?.update(), }); this.#editor = editor; this.#bubble = fillBubble(bubbleEl, editor, this.mode === 'simple' ? SIMPLE_FEATURES : FULL_FEATURES, { onLink: () => this.#linkPrompt(), onRef: () => this.#refPrompt() }); bubbleEl.style.visibility = 'hidden'; // the plugin appends and shows it over a selection this.#lastEmitted = stable(this.content); } override updated(changed: PropertyValues): void { if (changed.has('content') && this.#editor && stable(this.content) !== this.#lastEmitted) { this.#editor.commands.setContent(this.#doc(this.content) as never, { emitUpdate: false }); this.#lastEmitted = stable(this.content); } if (changed.has('prompt') && this.prompt) requestAnimationFrame(() => (this.querySelector('.prompt input') as HTMLInputElement | null)?.focus()); if (changed.has('mathEdit') && this.mathEdit) requestAnimationFrame(() => (this.querySelector('.math-edit textarea') as HTMLTextAreaElement | null)?.focus()); } override disconnectedCallback(): void { super.disconnectedCallback(); this.#editor?.destroy(); this.#editor = null; } focusEnd(): void { this.#editor?.chain().focus('end').run(); } focusStart(): void { this.#editor?.chain().focus('start').run(); } #local(rect: DOMRect | null | undefined): { x: number; y: number } { const host = this.getBoundingClientRect(); if (!rect) return { x: 0, y: 0 }; return { x: Math.max(0, rect.left - host.left), y: rect.bottom - host.top }; } #selectionPos(): { x: number; y: number } { const e = this.#editor!; const { from, to } = e.state.selection; return this.#local(posToDOMRect(e.view, from, to)); } #linkPrompt(): void { const e = this.#editor; if (!e || e.state.selection.empty) return; const href = (e.getAttributes('link').href as string | undefined) ?? ''; this.prompt = { kind: 'link', fields: { uri: href }, ...this.#selectionPos(), apply: (f) => { const uri = f.uri?.trim(); if (uri) e.chain().focus().extendMarkRange('link').setLink({ href: uri }).run(); else e.chain().focus().extendMarkRange('link').unsetLink().run(); }, }; } #refPrompt(): void { const e = this.#editor; if (!e || e.state.selection.empty) return; const { from, to } = e.state.selection; const cur = e.getAttributes('ref'); this.prompt = { kind: 'ref', fields: { key: (cur.key as string | undefined) ?? e.state.doc.textBetween(from, to, ' ').trim(), title: (cur.title as string) ?? '', uri: (cur.uri as string) ?? '' }, ...this.#selectionPos(), apply: (f) => { const k = f.key?.trim(); if (!k) return; e.chain().focus().setTextSelection({ from, to }).setMark('ref', { key: k, title: f.title?.trim() || null, uri: f.uri?.trim() || null }).run(); }, }; } #openMath(node: PMNode, pos: number): void { const e = this.#editor; if (!e) return; this.mathEdit = { pos, latex: String(node.attrs.latex ?? ''), ...this.#local(posToDOMRect(e.view, pos, pos + node.nodeSize)) }; } #setMath(latex: string): void { const e = this.#editor; const m = this.mathEdit; if (!e || !m) return; e.commands.command(({ tr, dispatch }) => { const node = tr.doc.nodeAt(m.pos); if (!node || node.type.name !== 'inlineMath') return false; tr.setNodeMarkup(m.pos, undefined, { ...node.attrs, latex }); dispatch?.(tr); return true; }); this.mathEdit = { ...m, latex }; } #applyPrompt(): void { const p = this.prompt; if (!p) return; this.prompt = null; p.apply(p.fields); } override render() { const p = this.prompt; const m = this.mathEdit; const field = (name: string, label: string, ph = '') => p ? html`` : nothing; return html`
${p ? html`
e.stopPropagation()}> ${p.kind === 'link' ? field('uri', 'Link URL', 'https://…') : html`${field('key', 'Reference key', 'rfc2119')} ${field('title', 'Title (optional)')} ${field('uri', 'URL (optional)')}`}
` : nothing} ${m ? html`
e.stopPropagation()}>
` : nothing}
`; } } customElements.define('draft-line', DraftLine);