oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1// maketeam.mjs — Make team page from a selection (spec §6.7). The
2// selection is widened to every block it touches, and those blocks are
3// tinted before anything is confirmed. The popover asks for a title
4// (prefilled from the first heading, or the first words) and says what
5// moves. On confirm the draft is committed as an ordinary commit (a
6// day's first commit makes it), the block numbers are read from the
7// body just committed, parsed by markup.mjs, never from the editor's
8// tree, and Make team page is posted with them and the revision they
9// index, which the server checks. A taken or date-shaped title asks for
10// another. The note then holds a link where the blocks were.
11
12import { Plugin, PluginKey } from 'prosemirror-state'
13import { Decoration, DecorationSet } from 'prosemirror-view'
14import { parse, cleanBody, Grammar } from './markup.mjs'
15import { serialiseDetailed } from './serialize.mjs'
16import { held } from './busy.mjs'
17
18export const movingKey = new PluginKey('mapa-moving')
19
20// widen is the emitted blocks the selection touches: their numbers in
21// the body the document writes, and their places.
22export function widen (state, fidelity) {
23 const { from, to } = state.selection
24 const { emitted, body } = serialiseDetailed(state.doc, fidelity)
25 const chosen = []
26 emitted.forEach((block, index) => {
27 const end = block.pos + block.node.nodeSize
28 if (block.pos < Math.max(to, from + 1) && end > from) chosen.push({ index, block })
29 })
30 return { chosen, body }
31}
32
33// suggestTitle is the first heading among the blocks, or the first words.
34export function suggestTitle (blocks) {
35 const heading = blocks.find(({ block }) => block.node.type.name === 'heading')
36 const text = (heading ?? blocks[0])?.block.node.textContent ?? ''
37 const words = text.trim().split(/\s+/u).slice(0, 6).join(' ')
38 return words.replace(/[[\]|#^]/gu, '').slice(0, 80)
39}
40
41// numbersIn maps chosen blocks to the committed body's block numbers:
42// the same blocks, in the same order, saying the same thing.
43export function numbersIn (body, chosen, emitted) {
44 const blocks = parse(cleanBody(body))
45 if (blocks.length !== emitted) return null
46 const numbers = []
47 for (const { index, block } of chosen) {
48 if (!blocks[index] || blocks[index].source !== block.text) return null
49 numbers.push(index)
50 }
51 return numbers
52}
53
54export function movingPlugin () {
55 return new Plugin({
56 key: movingKey,
57 state: {
58 init: () => null,
59 apply (tr, ranges) {
60 const meta = tr.getMeta(movingKey)
61 if (meta !== undefined) return meta
62 return ranges && ranges.map(range => ({
63 from: tr.mapping.map(range.from), to: tr.mapping.map(range.to)
64 }))
65 }
66 },
67 props: {
68 decorations (state) {
69 const ranges = movingKey.getState(state)
70 if (!ranges) return null
71 return DecorationSet.create(state.doc, ranges.map(range =>
72 Decoration.node(range.from, range.to, { 'mapa-moving': '' })))
73 }
74 }
75 })
76}
77
78function element (tag, attrs = {}, text = '') {
79 const node = document.createElement(tag)
80 for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value)
81 if (text) node.textContent = text
82 return node
83}
84
85// dialog is the confirm popover, built once.
86function dialog () {
87 const box = element('dialog', { 'mapa-make-team': '', 'aria-labelledby': 'mapa-make-team-title' })
88 const form = element('form', { method: 'dialog' })
89 const heading = element('h2', { id: 'mapa-make-team-title' }, 'Make team page')
90 const label = element('label', { for: 'mapa-make-team-name' }, 'Title of the new page')
91 const input = element('input', { id: 'mapa-make-team-name', name: 'title', required: '', autocomplete: 'off', 'rst-input': '' })
92 const error = element('p', { 'mapa-make-team-error': '', role: 'alert' })
93 const said = element('p', {}, 'These blocks move to a new team page everyone can open. Your note keeps a link in their place. Nothing else in your note is shared.')
94 const confirm = element('button', { type: 'submit', 'rst-btn': 'primary' }, 'Make team page')
95 const cancel = element('button', { type: 'button', 'rst-btn': '' }, 'Cancel')
96 const foot = element('div', { 'mapa-make-team-foot': '' })
97 foot.append(cancel, confirm)
98 form.append(heading, label, input, error, said, foot)
99 box.append(form)
100 document.body.append(box)
101 return { box, form, input, error, confirm, cancel }
102}
103
104// makeTeamPage is the command: from the bubble, the accessory row.
105export function makeTeamPage ({ saver, fidelity, post, notify }) {
106 let parts = null
107 return view => {
108 const { chosen } = widen(view.state, fidelity)
109 if (chosen.length === 0) return false
110 const ranges = chosen.map(({ block }) => ({ from: block.pos, to: block.pos + block.node.nodeSize }))
111 view.dispatch(view.state.tr.setMeta(movingKey, ranges))
112 parts = parts ?? dialog()
113 const { box, form, input, error, confirm, cancel } = parts
114 input.value = suggestTitle(chosen)
115 error.textContent = ''
116 const done = () => {
117 view.dispatch(view.state.tr.setMeta(movingKey, null))
118 form.onsubmit = null
119 cancel.onclick = null
120 box.onclose = null
121 if (box.open) box.close()
122 view.focus()
123 }
124 cancel.onclick = done
125 box.onclose = done
126 form.onsubmit = async event => {
127 event.preventDefault()
128 const title = input.value.trim()
129 const answer = await held(confirm, () => move(view, chosen, title))
130 if (answer.error) {
131 error.textContent = answer.error
132 input.focus()
133 return
134 }
135 done()
136 notify(title, answer.href)
137 }
138 box.showModal()
139 input.select()
140 return true
141 }
142
143 // move commits, numbers the blocks from the commit, and posts them.
144 async function move (view, chosen, title) {
145 const outcome = await saver.commit({ explicit: true })
146 if (!['none', 'saved', 'merged'].includes(outcome) || !saver.page) {
147 return { error: 'Your note could not be saved just now, so nothing was moved. Try again.' }
148 }
149 const { emitted } = serialiseDetailed(view.state.doc, fidelity)
150 const fresh = widenAgain(view, chosen)
151 const numbers = fresh && numbersIn(saver.saved, fresh, emitted.length)
152 if (!numbers) return { error: 'Your note changed while it was saved. Choose the blocks again.' }
153 let reply
154 try {
155 reply = await post(`/p/${saver.page}/share`, {
156 title, revision: saver.base, block: numbers.map(String), grammar: String(Grammar)
157 })
158 } catch {
159 return { error: 'Nothing was moved: the server could not be reached.' }
160 }
161 if (reply.status !== 200) return { error: reply.json?.error ?? 'Nothing was moved.' }
162 saver.took(reply.json.body, reply.json.revision)
163 return { href: reply.json.href }
164 }
165
166 // widenAgain finds the chosen blocks in the document as it is after
167 // the commit (a merge may have moved them), by the text they wrote.
168 function widenAgain (view, chosen) {
169 const { emitted } = serialiseDetailed(view.state.doc, fidelity)
170 const out = []
171 let from = 0
172 for (const { block } of chosen) {
173 const at = emitted.findIndex((other, index) => index >= from && other.text === block.text)
174 if (at < 0) return null
175 out.push({ index: at, block: emitted[at] })
176 from = at + 1
177 }
178 return out
179 }
180}
181