Something went wrong. Try again.
A monorepo for writing specs and other serious text on the AT Protocol.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258// 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<string, string>; x: number; y: number; apply: (fields: Record<string, string>) => 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<PMJson[]>('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`<label >${label} <input type="text" .value=${p.fields[name] ?? ''} placeholder=${ph} @input=${(e: Event) => (this.prompt = { ...p, fields: { ...p.fields, [name]: (e.target as HTMLInputElement).value } })} @keydown=${(e: KeyboardEvent) => { e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); this.#applyPrompt(); } else if (e.key === 'Escape') this.prompt = null; }} /> </label>` : nothing; return html`<div class="surface"></div> <div class="chrome"> ${p ? html`<div class="prompt" style="left:${p.x}px;top:${p.y}px" @mousedown=${(e: Event) => e.stopPropagation()}> ${p.kind === 'link' ? field('uri', 'Link URL', 'https://…') : html`${field('key', 'Reference key', 'rfc2119')} ${field('title', 'Title (optional)')} ${field('uri', 'URL (optional)')}`} <div class="row"> <button type="button" class="btn btn-small" @click=${() => (this.prompt = null)}>Cancel</button> <button type="button" class="btn btn-primary btn-small" @click=${() => this.#applyPrompt()}>Apply</button> </div> </div>` : nothing} ${m ? html`<div class="math-edit" style="left:${m.x}px;top:${m.y}px" @mousedown=${(e: Event) => e.stopPropagation()}> <label >Inline math (TeX) <textarea rows="1" .value=${m.latex} @input=${(e: Event) => this.#setMath((e.target as HTMLTextAreaElement).value)} @keydown=${(e: KeyboardEvent) => { e.stopPropagation(); if (e.key === 'Escape' || e.key === 'Enter') { e.preventDefault(); this.mathEdit = null; this.#editor?.commands.focus(); } }} ></textarea> </label> </div>` : nothing} </div>`; }}
customElements.define('draft-line', DraftLine);