Something went wrong. Try again.
A monorepo for writing specs and other serious text on the AT Protocol.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269// Assembling the editor: which extensions a document gets for a given host// configuration, and the smaller set a single-line field gets.import { Extension, type Extensions } from '@tiptap/core';import StarterKit from '@tiptap/starter-kit';import Paragraph from '@tiptap/extension-paragraph';import { BulletList, ListItem, OrderedList } from '@tiptap/extension-list';import Subscript from '@tiptap/extension-subscript';import Superscript from '@tiptap/extension-superscript';import { Placeholder } from '@tiptap/extensions';import { CodeBlockLowlight } from '@tiptap/extension-code-block-lowlight';import { Mathematics } from '@tiptap/extension-mathematics';import { UniqueID } from '@tiptap/extension-unique-id';import { DragHandle } from '@tiptap/extension-drag-handle';import Collaboration from '@tiptap/extension-collaboration';import type { Node as PMNode } from '@tiptap/pm/model';import { suggestChanges } from '@handlewithcare/prosemirror-suggest-changes';import type * as Y from 'yjs';import { lowlight } from '../languages.ts';import { ALL_BLOCKS, type BlockKind } from '../types.ts';import { BLOCK_MARKS, Comment, Deletion, Dfn, DfnRef, Insertion, Modification, Ref } from './marks.ts';import { DefinitionDescription, DefinitionItem, DefinitionList, DefinitionTerm, Doc, Figure, LineDoc, Section, SectionTitle } from './nodes.ts';import { DraftKeymap, InlineMathDollar, SectionAnchors } from './keymap.ts';import { CodeBlockView, type ViewHooks } from './views.ts';
export type MathHooks = { onMathClick: (node: PMNode, pos: number) => void };
export type BodyOptions = { blocks?: readonly BlockKind[]; hooks: ViewHooks & MathHooks; /** Extra extensions from the host. */ extensions?: Extensions; collaboration?: { doc: Y.Doc; field?: string }; /** The drag handle tells the host which block it hovers, for a block menu. */ onHandleNode?: (info: { node: PMNode | null; pos: number }) => void;};
/** The attribute that makes a block an outline note: a sketch of what will be written rather than prose. */const outlineAttr = { outline: { default: false, parseHTML: (el: HTMLElement) => el.hasAttribute('data-outline'), renderHTML: (a: Record<string, unknown>) => (a.outline ? { 'data-outline': '' } : {}) } };
/** The writer's notes a block draws on, by title (with the kind of each once known): kept with the block, shown under it. */const drawsAttr = { draws: { default: null, parseHTML: (el: HTMLElement) => { try { const v: unknown = JSON.parse(el.getAttribute('data-draws') ?? 'null'); return Array.isArray(v) && v.length ? v : null; } catch { return null; } }, renderHTML: (a: Record<string, unknown>) => (Array.isArray(a.draws) && a.draws.length ? { 'data-draws': JSON.stringify(a.draws) } : {}), },};
/** A paragraph, which may be an outline note: what its section, or the paragraph itself, will say. */export const OutlineParagraph = Paragraph.extend({ addAttributes() { return { ...this.parent?.(), ...outlineAttr, ...drawsAttr }; },});
/** Lists, which may be outline notes too: the points a paragraph will make, one per sentence. */const OutlineBulletList = BulletList.extend({ marks: BLOCK_MARKS, addAttributes() { return { ...this.parent?.(), ...outlineAttr, ...drawsAttr }; },});const OutlineOrderedList = OrderedList.extend({ marks: BLOCK_MARKS, addAttributes() { return { ...this.parent?.(), ...outlineAttr, ...drawsAttr }; },});
/** The suggestion marks and the plugin that turns edits into suggestions. */export const Suggestions = Extension.create({ name: 'suggestions', addProseMirrorPlugins() { return [suggestChanges()]; },});
export function bodyExtensions(o: BodyOptions): Extensions { const blocks = new Set<BlockKind>(o.blocks ?? ALL_BLOCKS); const hooks = o.hooks; const lists = blocks.has('list') || blocks.has('ordered'); const collab = !!o.collaboration; return [ Doc, StarterKit.configure({ document: false, paragraph: false, heading: false, blockquote: false, horizontalRule: false, strike: false, underline: false, hardBreak: false, codeBlock: false, bulletList: false, orderedList: false, listItem: false, trailingNode: false, undoRedo: collab ? false : undefined, link: { openOnClick: false, autolink: true, defaultProtocol: 'https' }, }), OutlineParagraph, ...(lists ? [ ...(blocks.has('list') ? [OutlineBulletList] : []), ...(blocks.has('ordered') ? [OutlineOrderedList] : []), ListItem.extend({ content: `paragraph (${[blocks.has('list') ? 'bulletList' : '', blocks.has('ordered') ? 'orderedList' : ''].filter(Boolean).join(' | ')})?`, marks: BLOCK_MARKS }), ] : []), Subscript, Superscript, Dfn, DfnRef, Ref, Comment, Insertion, Deletion, Modification, Suggestions, Section.configure({ hooks }), SectionTitle.configure({ hooks }), ...(blocks.has('definitionList') ? [DefinitionList, DefinitionItem, DefinitionTerm, DefinitionDescription] : []), ...(blocks.has('figure') ? [Figure.configure({ hooks })] : []), ...(blocks.has('code') ? [ CodeBlockLowlight.extend({ marks: 'insertion deletion modification comment', addNodeView() { return (props) => new CodeBlockView(props); }, }).configure({ lowlight, defaultLanguage: null, exitOnArrowDown: true, exitOnTripleEnter: false }), ] : []), ...(blocks.has('math') ? [ Mathematics.configure({ katexOptions: { throwOnError: false }, inlineOptions: { onClick: hooks.onMathClick }, blockOptions: { onClick: hooks.onMathClick }, }), InlineMathDollar, ] : []), DraftKeymap, SectionAnchors, UniqueID.configure({ attributeName: 'id', types: ['section', 'paragraph', 'codeBlock', 'blockMath', 'bulletList', 'orderedList', 'definitionList', 'figure'], generateID: () => hooks.newId(), }), Placeholder.configure({ includeChildren: true, showOnlyCurrent: false, placeholder: ({ node, pos, editor }) => { switch (node.type.name) { case 'sectionTitle': return 'Section title'; case 'paragraph': { // decorations run against the new document while editor.state may // still be the old one: look up defensively let inList = false; try { const doc = editor.state.doc; if (pos <= doc.content.size) inList = doc.resolve(pos).parent.type.name === 'listItem'; } catch { inList = false; } return inList ? 'list item' : 'Type / for a block type, or just write'; } case 'definitionTerm': return 'term'; case 'definitionDescription': return 'definition'; case 'figure': return 'caption (optional)'; case 'codeBlock': return 'code…'; default: return ''; } }, }), DragHandle.configure({ render() { const el = document.createElement('div'); el.className = 'drag-handle'; el.title = 'Drag to move; click for the block menu'; el.textContent = '⋮⋮'; return el; }, onNodeChange: ({ node, editor }) => { // the handle reports the node; its position is looked up by identity let pos = -1; if (node) { editor.state.doc.descendants((n, p) => { if (pos >= 0) return false; if (n === node) { pos = p; return false; } return true; }); } o.onHandleNode?.({ node, pos }); }, nested: { rules: [ { id: 'no-inner-parts', evaluate: ({ node }) => (['sectionTitle', 'definitionItem', 'definitionTerm', 'definitionDescription'].includes(node.type.name) ? 1000 : 0), }, ], }, }), ...(o.collaboration ? [Collaboration.configure({ document: o.collaboration.doc, field: o.collaboration.field ?? 'draft' })] : []), ...(o.extensions ?? []), ];}
/** A single line of rich text: a title (simple marks) or an abstract (all of them). */export function lineExtensions(mode: 'simple' | 'full', onEnter: () => void, hooks: MathHooks, placeholder: () => string = () => ''): Extensions { const full = mode === 'full'; return [ LineDoc, StarterKit.configure({ document: false, heading: false, blockquote: false, horizontalRule: false, strike: false, underline: false, hardBreak: false, codeBlock: false, bulletList: false, orderedList: false, listItem: false, listKeymap: false, trailingNode: false, dropcursor: false, gapcursor: false, link: full ? { openOnClick: false, autolink: true, defaultProtocol: 'https' } : false, }), Subscript, Superscript, ...(full ? [Dfn, DfnRef, Ref, Mathematics.configure({ katexOptions: { throwOnError: false }, inlineOptions: { onClick: hooks.onMathClick } }), InlineMathDollar] : []), Extension.create({ name: 'lineKeymap', priority: 1000, addKeyboardShortcuts() { return { Enter: () => { onEnter(); return true; }, 'Shift-Enter': () => true, }; }, }), Placeholder.configure({ placeholder }), ];}