oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1// tasks.mjs — a task's box in the editor (spec §6.11, §6.12). The
2// server draws the box with CSS on the item (build note 5); the editor
3// lays a named button over it, "Done: Send Tom the summary", which a
4// click or a tap toggles without placing the caret. It is out of the
5// text's flow, so drawing it moves nothing (L5).
6
7import { Plugin } from 'prosemirror-state'
8import { Decoration, DecorationSet } from 'prosemirror-view'
9
10// itemAt is the task item whose paragraph holds pos.
11function itemAt (doc, pos) {
12 const $pos = doc.resolve(pos)
13 for (let depth = $pos.depth; depth > 0; depth--) {
14 const node = $pos.node(depth)
15 if (node.type.name === 'list_item') return { pos: $pos.before(depth), node }
16 }
17 return null
18}
19
20function box (view, getPos, node) {
21 const done = node.attrs.checked !== ' '
22 const button = document.createElement('button')
23 button.type = 'button'
24 button.setAttribute('mapa-task-box', '')
25 button.setAttribute('contenteditable', 'false')
26 button.setAttribute('aria-pressed', done ? 'true' : 'false')
27 button.setAttribute('aria-label', `${done ? 'Done' : 'Not done'}: ${node.firstChild?.textContent ?? ''}`)
28 button.addEventListener('mousedown', event => event.preventDefault())
29 button.addEventListener('click', event => {
30 event.preventDefault()
31 const found = itemAt(view.state.doc, getPos())
32 if (!found?.node.attrs.task) return
33 const checked = found.node.attrs.checked !== ' ' ? ' ' : 'x'
34 view.dispatch(view.state.tr.setNodeMarkup(found.pos, null, { ...found.node.attrs, checked }))
35 })
36 return button
37}
38
39function draw (doc) {
40 const decorations = []
41 doc.descendants((node, pos) => {
42 if (node.type.name !== 'list_item' || !node.attrs.task) return
43 const key = `task:${node.attrs.checked}:${node.firstChild?.textContent ?? ''}`
44 decorations.push(Decoration.widget(pos + 2, (view, getPos) => box(view, getPos, node),
45 { side: -1, key, ignoreSelection: true, stopEvent: () => true }))
46 })
47 return DecorationSet.create(doc, decorations)
48}
49
50export function tasksPlugin () {
51 return new Plugin({
52 state: {
53 init: (config, state) => draw(state.doc),
54 apply: (tr, set) => tr.docChanged ? draw(tr.doc) : set
55 },
56 props: { decorations (state) { return this.getState(state) } }
57 })
58}
59