| 1 | // clipboard.mjs — copy, cut and paste (spec §6.6). |
| 2 | // |
| 3 | // Copy and cut put Mapa Markdown in text/plain, ProseMirror's HTML in |
| 4 | // text/html, and a private application/x-mapa slice: each copied block's |
| 5 | // Markdown (its source, when it is untouched) and the exact bytes between |
| 6 | // them. Paste prefers that slice. Its blocks are built by markup.mjs's |
| 7 | // parser, never taken on trust, and get fresh origins recorded with their |
| 8 | // sources and seams, so a cut and paste re-emits the bytes it cut. |
| 9 | // text/plain from outside is parsed as Mapa Markdown; text/html goes |
| 10 | // through the schema's parseDOM. A pasted block's ^id is removed only |
| 11 | // when that id is already in the document (outside what the paste |
| 12 | // replaces), so a cut and paste keeps the links to its block. |
| 13 | |
| 14 | import { Plugin, PluginKey, TextSelection } from 'prosemirror-state' |
| 15 | import { Fragment, Slice } from 'prosemirror-model' |
| 16 | import { parse, spans, safeURL, Image, ImagePrefix, Code } from './markup.mjs' |
| 17 | import { fromMarkdown } from './fromMarkdown.mjs' |
| 18 | import { serialiseDetailed } from './serialize.mjs' |
| 19 | import { recordBody } from './fidelity.mjs' |
| 20 | import { inColumn, withoutLayouts, crossColumns, deleteInColumns } from './columns.mjs' |
| 21 | |
| 22 | export const mapaType = 'application/x-mapa' |
| 23 | |
| 24 | // copyData is what copy puts on the clipboard for from..to: Markdown for |
| 25 | // text/plain, and the x-mapa slice. |
| 26 | // The slice also carries the public id of the page it came from (images |
| 27 | // §2.2), so a paste elsewhere knows to copy its images. |
| 28 | export function copyData (state, fidelity, from = state.selection.from, |
| 29 | to = state.selection.to, page = '') { |
| 30 | const whole = state.doc.slice(from, to, true) |
| 31 | // Inside one column, the slice is that column's blocks: no fence of |
| 32 | // the layout around them goes on the clipboard (Fable on the build, M2). |
| 33 | let content = whole.content |
| 34 | const first = content.firstChild |
| 35 | if (content.childCount === 1 && first.type.name === 'columns' && first.childCount === 1) { |
| 36 | content = first.firstChild.content |
| 37 | } |
| 38 | const doc = state.schema.topNodeType.create(null, content) |
| 39 | const { body, emitted } = serialiseDetailed(doc, fidelity, { edges: false, raw: true }) |
| 40 | const mapa = JSON.stringify({ |
| 41 | v: 1, |
| 42 | sources: emitted.map(block => block.text), |
| 43 | seams: emitted.slice(1).map(block => block.seam), |
| 44 | page |
| 45 | }) |
| 46 | return { text: body, mapa } |
| 47 | } |
| 48 | |
| 49 | // sliceImages is the image ids an x-mapa slice holds, and its page. |
| 50 | function sliceImages (data) { |
| 51 | let payload |
| 52 | try { payload = JSON.parse(data) } catch { return null } |
| 53 | if (payload?.v !== 1 || !Array.isArray(payload.sources)) return null |
| 54 | const ids = new Set() |
| 55 | for (const source of payload.sources) { |
| 56 | if (typeof source !== 'string') return null |
| 57 | for (const block of parse(source)) { |
| 58 | if (block.kind === Code) continue |
| 59 | for (const span of spans(block.source)) if (span.kind === Image) ids.add(span.target) |
| 60 | } |
| 61 | } |
| 62 | return { payload, ids: [...ids], page: typeof payload.page === 'string' ? payload.page : '' } |
| 63 | } |
| 64 | |
| 65 | // withCopies is a slice's payload with each copied image's address |
| 66 | // rewritten, touching nothing else in its sources. |
| 67 | function withCopies (payload, copies) { |
| 68 | const sources = payload.sources.map(source => { |
| 69 | if (parse(source)[0]?.kind === Code) return source |
| 70 | let out = '' |
| 71 | for (const span of spans(source)) { |
| 72 | const fresh = span.kind === Image ? copies[span.target] : null |
| 73 | out += fresh ? `` : span.source |
| 74 | } |
| 75 | return out |
| 76 | }) |
| 77 | return JSON.stringify({ ...payload, sources }) |
| 78 | } |
| 79 | |
| 80 | // remoteImages is pasted HTML with each <img> from outside Mapa made a |
| 81 | // web link, or nothing when its address is not one (images §2.2): Mapa |
| 82 | // never fetches it. |
| 83 | export function remoteImages (html) { |
| 84 | if (!/<img/iu.test(html)) return html |
| 85 | const doc = new DOMParser().parseFromString(html, 'text/html') |
| 86 | for (const img of [...doc.querySelectorAll('img')]) { |
| 87 | const src = img.getAttribute('src') ?? '' |
| 88 | if (src.startsWith(ImagePrefix)) continue |
| 89 | if (safeURL(src)) { |
| 90 | const link = doc.createElement('a') |
| 91 | link.setAttribute('href', src) |
| 92 | link.textContent = img.getAttribute('alt') || src |
| 93 | img.replaceWith(link) |
| 94 | } else { |
| 95 | img.remove() |
| 96 | } |
| 97 | } |
| 98 | return doc.body.innerHTML |
| 99 | } |
| 100 | |
| 101 | // slicePayload reads an x-mapa slice: the Markdown it carries, or null |
| 102 | // when it is not one this editor wrote. |
| 103 | function slicePayload (data) { |
| 104 | let payload |
| 105 | try { |
| 106 | payload = JSON.parse(data) |
| 107 | } catch { |
| 108 | return null |
| 109 | } |
| 110 | const { sources, seams } = payload ?? {} |
| 111 | if (payload?.v !== 1 || !Array.isArray(sources) || !Array.isArray(seams) || |
| 112 | sources.length === 0 || seams.length !== sources.length - 1 || |
| 113 | ![...sources, ...seams].every(text => typeof text === 'string') || |
| 114 | !seams.every(text => /^\n(?:[^\n]*\n)*$/u.test(text))) { |
| 115 | return null |
| 116 | } |
| 117 | const body = sources.map((source, index) => (index ? seams[index - 1] : '') + source).join('') |
| 118 | const blocks = parse(body) |
| 119 | if (blocks.length !== sources.length || |
| 120 | blocks.some((block, index) => block.source !== sources[index])) return null |
| 121 | return body |
| 122 | } |
| 123 | |
| 124 | // takenMarkers is every ^id in the document outside the selection. An |
| 125 | // empty block (the one a cut leaves) writes nothing, so its ^id is not in |
| 126 | // the document. |
| 127 | export function takenMarkers (state, fidelity) { |
| 128 | const { from, to } = state.selection |
| 129 | const taken = new Set() |
| 130 | for (const block of serialiseDetailed(state.doc, fidelity).emitted) { |
| 131 | const marker = block.holder.attrs.marker |
| 132 | const inside = block.holderPos >= from && |
| 133 | block.holderPos + block.holder.nodeSize <= to |
| 134 | if (marker && !inside) taken.add(marker) |
| 135 | } |
| 136 | return taken |
| 137 | } |
| 138 | |
| 139 | function stripMarkers (fragment, taken) { |
| 140 | const out = [] |
| 141 | fragment.forEach(node => { |
| 142 | let next = node |
| 143 | if (!node.isTextblock && !node.isLeaf) next = node.copy(stripMarkers(node.content, taken)) |
| 144 | if (next.attrs.marker && taken.has(next.attrs.marker)) { |
| 145 | next = next.type.create({ ...next.attrs, marker: null }, next.content, next.marks) |
| 146 | } |
| 147 | out.push(next) |
| 148 | }) |
| 149 | return Fragment.from(out) |
| 150 | } |
| 151 | |
| 152 | export function stripTakenMarkers (slice, state, fidelity) { |
| 153 | const taken = takenMarkers(state, fidelity) |
| 154 | if (taken.size === 0) return slice |
| 155 | return new Slice(stripMarkers(slice.content, taken), slice.openStart, slice.openEnd) |
| 156 | } |
| 157 | |
| 158 | // pasteTransaction is a paste of an x-mapa slice over the selection, or |
| 159 | // null when data is not one. Its blocks get fresh origins recorded with |
| 160 | // their sources and the seams between them. |
| 161 | export function pasteTransaction (state, fidelity, data) { |
| 162 | const body = slicePayload(data) |
| 163 | if (body === null) return null |
| 164 | const { doc } = recordBody(state.schema, fidelity, body, { trailing: false, edges: false }) |
| 165 | // Into a column, a layout arrives as its blocks: layouts never nest. |
| 166 | const content = inColumn(state.selection.$from) ? withoutLayouts(doc.content) : doc.content |
| 167 | const slice = stripTakenMarkers(Slice.maxOpen(content), state, fidelity) |
| 168 | // Into an empty paragraph of its own (where a cut leaves the caret), |
| 169 | // the blocks replace it whole rather than merging into it, so every |
| 170 | // pasted block keeps its source and the seams between them. |
| 171 | const { $from, empty } = state.selection |
| 172 | if (empty && $from.depth === 1 && $from.parent.type.name === 'paragraph' && |
| 173 | $from.parent.content.size === 0) { |
| 174 | const tr = state.tr.replaceWith($from.before(), $from.after(), slice.content) |
| 175 | const end = $from.before() + slice.content.size |
| 176 | return tr.setSelection(TextSelection.near(tr.doc.resolve(end), -1)) |
| 177 | } |
| 178 | return state.tr.replaceSelection(slice) |
| 179 | } |
| 180 | |
| 181 | // textSlice is text/plain from outside, read as Mapa Markdown. |
| 182 | export function textSlice (schema, text) { |
| 183 | const doc = fromMarkdown(schema, text, { trailing: false }) |
| 184 | return doc.childCount ? Slice.maxOpen(doc.content) : Slice.empty |
| 185 | } |
| 186 | |
| 187 | // sliceText is a slice's Markdown, written from its nodes, for a slice |
| 188 | // that is not the selection. |
| 189 | function sliceText (schema, slice) { |
| 190 | let content = slice.content |
| 191 | const first = content.firstChild |
| 192 | if (!first) return '' |
| 193 | if (first.isInline) content = Fragment.from(schema.nodes.paragraph.create(null, content)) |
| 194 | else if (first.type.name === 'list_item') { |
| 195 | content = Fragment.from(schema.nodes.bullet_list.create(null, content)) |
| 196 | } |
| 197 | try { |
| 198 | return serialiseDetailed(schema.topNodeType.create(null, content), null, |
| 199 | { edges: false, raw: true }).body |
| 200 | } catch { |
| 201 | return slice.content.textBetween(0, slice.content.size, '\n\n') |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | const clipboardKey = new PluginKey('mapa-clipboard') |
| 206 | |
| 207 | // clipboardPlugin wires the handlers above into the view. |
| 208 | // |
| 209 | // options.page is this page's public id now; options.copy(ids) is POST |
| 210 | // /images/copy, answering { status, json }; options.copied(reply) |
| 211 | // records each copy's answer, and options.refused(why) says why a paste |
| 212 | // went nowhere. |
| 213 | export function clipboardPlugin (fidelity, options = {}) { |
| 214 | const page = () => options.page?.() ?? '' |
| 215 | const copy = (view, event, cut) => { |
| 216 | const data = event.clipboardData |
| 217 | if (!data || view.state.selection.empty) return false |
| 218 | const { text, mapa } = copyData(view.state, fidelity, undefined, undefined, page()) |
| 219 | const { dom } = view.serializeForClipboard(view.state.selection.content()) |
| 220 | event.preventDefault() |
| 221 | data.clearData() |
| 222 | data.setData('text/html', dom.innerHTML) |
| 223 | data.setData('text/plain', text) |
| 224 | data.setData(mapaType, mapa) |
| 225 | if (cut && crossColumns(view.state)) { |
| 226 | deleteInColumns(view.state, tr => view.dispatch(tr.setMeta('uiEvent', 'cut'))) |
| 227 | } else if (cut) { |
| 228 | view.dispatch(view.state.tr.deleteSelection().scrollIntoView() |
| 229 | .setMeta('uiEvent', 'cut')) |
| 230 | } |
| 231 | return true |
| 232 | } |
| 233 | return new Plugin({ |
| 234 | key: clipboardKey, |
| 235 | props: { |
| 236 | handleDOMEvents: { |
| 237 | copy: (view, event) => copy(view, event, false), |
| 238 | cut: (view, event) => copy(view, event, true) |
| 239 | }, |
| 240 | handlePaste (view, event) { |
| 241 | const data = event.clipboardData?.getData(mapaType) |
| 242 | if (!data) return false |
| 243 | const images = sliceImages(data) |
| 244 | if (images?.ids.length && options.copy && (!images.page || images.page !== page())) { |
| 245 | event.preventDefault() |
| 246 | pasteCopies(view, fidelity, images, options) |
| 247 | return true |
| 248 | } |
| 249 | const tr = pasteTransaction(view.state, fidelity, data) |
| 250 | if (!tr) return false |
| 251 | view.dispatch(tr.scrollIntoView().setMeta('paste', true).setMeta('uiEvent', 'paste')) |
| 252 | return true |
| 253 | }, |
| 254 | transformPastedHTML: html => remoteImages(html), |
| 255 | clipboardTextSerializer (slice, view) { |
| 256 | if (view.state.selection.content().eq(slice)) { |
| 257 | return copyData(view.state, fidelity).text |
| 258 | } |
| 259 | return sliceText(view.state.schema, slice) |
| 260 | }, |
| 261 | clipboardTextParser (text, $context, plain, view) { |
| 262 | return textSlice(view.state.schema, text) |
| 263 | }, |
| 264 | transformPasted (slice, view) { |
| 265 | let pasted = slice |
| 266 | if (inColumn(view.state.selection.$from)) { |
| 267 | let holds = false |
| 268 | slice.content.forEach(node => { holds = holds || node.type.name === 'columns' }) |
| 269 | if (holds) pasted = Slice.maxOpen(withoutLayouts(slice.content)) |
| 270 | } |
| 271 | return stripTakenMarkers(pasted, view.state, fidelity) |
| 272 | } |
| 273 | } |
| 274 | }) |
| 275 | } |
| 276 | |
| 277 | // pasteCopies pastes a slice from another page: its images are copied |
| 278 | // first (POST /images/copy), and their addresses rewritten before it |
| 279 | // goes in. An id the person may not read is left out of the reply, and |
| 280 | // stays as typed, drawn as not available (images §2.2). A copy that is |
| 281 | // refused (an allowance, no store, a busy server) pastes nothing and |
| 282 | // says why, rather than pasting addresses that would not draw (Fable |
| 283 | // L3). |
| 284 | async function pasteCopies (view, fidelity, images, options) { |
| 285 | let reply = null |
| 286 | try { |
| 287 | reply = await options.copy(images.ids) |
| 288 | } catch {} |
| 289 | if (!reply || reply.status !== 200) { |
| 290 | options.refused?.(reply?.json?.refused ?? |
| 291 | 'the images could not be copied. Check your connection and try again.') |
| 292 | return |
| 293 | } |
| 294 | options.copied?.(reply.json ?? {}) |
| 295 | const tr = pasteTransaction(view.state, fidelity, withCopies(images.payload, reply.json ?? {})) |
| 296 | if (tr) view.dispatch(tr.scrollIntoView().setMeta('paste', true).setMeta('uiEvent', 'paste')) |
| 297 | } |
| 298 | |