// tasks.mjs — a task's box in the editor (spec §6.11, §6.12). The // server draws the box with CSS on the item (build note 5); the editor // lays a named button over it, "Done: Send Tom the summary", which a // click or a tap toggles without placing the caret. It is out of the // text's flow, so drawing it moves nothing (L5). import { Plugin } from 'prosemirror-state' import { Decoration, DecorationSet } from 'prosemirror-view' // itemAt is the task item whose paragraph holds pos. function itemAt (doc, pos) { const $pos = doc.resolve(pos) for (let depth = $pos.depth; depth > 0; depth--) { const node = $pos.node(depth) if (node.type.name === 'list_item') return { pos: $pos.before(depth), node } } return null } function box (view, getPos, node) { const done = node.attrs.checked !== ' ' const button = document.createElement('button') button.type = 'button' button.setAttribute('mapa-task-box', '') button.setAttribute('contenteditable', 'false') button.setAttribute('aria-pressed', done ? 'true' : 'false') button.setAttribute('aria-label', `${done ? 'Done' : 'Not done'}: ${node.firstChild?.textContent ?? ''}`) button.addEventListener('mousedown', event => event.preventDefault()) button.addEventListener('click', event => { event.preventDefault() const found = itemAt(view.state.doc, getPos()) if (!found?.node.attrs.task) return const checked = found.node.attrs.checked !== ' ' ? ' ' : 'x' view.dispatch(view.state.tr.setNodeMarkup(found.pos, null, { ...found.node.attrs, checked })) }) return button } function draw (doc) { const decorations = [] doc.descendants((node, pos) => { if (node.type.name !== 'list_item' || !node.attrs.task) return const key = `task:${node.attrs.checked}:${node.firstChild?.textContent ?? ''}` decorations.push(Decoration.widget(pos + 2, (view, getPos) => box(view, getPos, node), { side: -1, key, ignoreSelection: true, stopEvent: () => true })) }) return DecorationSet.create(doc, decorations) } export function tasksPlugin () { return new Plugin({ state: { init: (config, state) => draw(state.doc), apply: (tr, set) => tr.docChanged ? draw(tr.doc) : set }, props: { decorations (state) { return this.getState(state) } } }) }