// clipboard.mjs — copy, cut and paste (spec §6.6).
//
// Copy and cut put Mapa Markdown in text/plain, ProseMirror's HTML in
// text/html, and a private application/x-mapa slice: each copied block's
// Markdown (its source, when it is untouched) and the exact bytes between
// them. Paste prefers that slice. Its blocks are built by markup.mjs's
// parser, never taken on trust, and get fresh origins recorded with their
// sources and seams, so a cut and paste re-emits the bytes it cut.
// text/plain from outside is parsed as Mapa Markdown; text/html goes
// through the schema's parseDOM. A pasted block's ^id is removed only
// when that id is already in the document (outside what the paste
// replaces), so a cut and paste keeps the links to its block.
import { Plugin, PluginKey, TextSelection } from 'prosemirror-state'
import { Fragment, Slice } from 'prosemirror-model'
import { parse, spans, safeURL, Image, ImagePrefix, Code } from './markup.mjs'
import { fromMarkdown } from './fromMarkdown.mjs'
import { serialiseDetailed } from './serialize.mjs'
import { recordBody } from './fidelity.mjs'
import { inColumn, withoutLayouts, crossColumns, deleteInColumns } from './columns.mjs'
export const mapaType = 'application/x-mapa'
// copyData is what copy puts on the clipboard for from..to: Markdown for
// text/plain, and the x-mapa slice.
// The slice also carries the public id of the page it came from (images
// §2.2), so a paste elsewhere knows to copy its images.
export function copyData (state, fidelity, from = state.selection.from,
to = state.selection.to, page = '') {
const whole = state.doc.slice(from, to, true)
// Inside one column, the slice is that column's blocks: no fence of
// the layout around them goes on the clipboard (Fable on the build, M2).
let content = whole.content
const first = content.firstChild
if (content.childCount === 1 && first.type.name === 'columns' && first.childCount === 1) {
content = first.firstChild.content
}
const doc = state.schema.topNodeType.create(null, content)
const { body, emitted } = serialiseDetailed(doc, fidelity, { edges: false, raw: true })
const mapa = JSON.stringify({
v: 1,
sources: emitted.map(block => block.text),
seams: emitted.slice(1).map(block => block.seam),
page
})
return { text: body, mapa }
}
// sliceImages is the image ids an x-mapa slice holds, and its page.
function sliceImages (data) {
let payload
try { payload = JSON.parse(data) } catch { return null }
if (payload?.v !== 1 || !Array.isArray(payload.sources)) return null
const ids = new Set()
for (const source of payload.sources) {
if (typeof source !== 'string') return null
for (const block of parse(source)) {
if (block.kind === Code) continue
for (const span of spans(block.source)) if (span.kind === Image) ids.add(span.target)
}
}
return { payload, ids: [...ids], page: typeof payload.page === 'string' ? payload.page : '' }
}
// withCopies is a slice's payload with each copied image's address
// rewritten, touching nothing else in its sources.
function withCopies (payload, copies) {
const sources = payload.sources.map(source => {
if (parse(source)[0]?.kind === Code) return source
let out = ''
for (const span of spans(source)) {
const fresh = span.kind === Image ? copies[span.target] : null
out += fresh ? `` : span.source
}
return out
})
return JSON.stringify({ ...payload, sources })
}
// remoteImages is pasted HTML with each
from outside Mapa made a
// web link, or nothing when its address is not one (images §2.2): Mapa
// never fetches it.
export function remoteImages (html) {
if (!/
typeof text === 'string') ||
!seams.every(text => /^\n(?:[^\n]*\n)*$/u.test(text))) {
return null
}
const body = sources.map((source, index) => (index ? seams[index - 1] : '') + source).join('')
const blocks = parse(body)
if (blocks.length !== sources.length ||
blocks.some((block, index) => block.source !== sources[index])) return null
return body
}
// takenMarkers is every ^id in the document outside the selection. An
// empty block (the one a cut leaves) writes nothing, so its ^id is not in
// the document.
export function takenMarkers (state, fidelity) {
const { from, to } = state.selection
const taken = new Set()
for (const block of serialiseDetailed(state.doc, fidelity).emitted) {
const marker = block.holder.attrs.marker
const inside = block.holderPos >= from &&
block.holderPos + block.holder.nodeSize <= to
if (marker && !inside) taken.add(marker)
}
return taken
}
function stripMarkers (fragment, taken) {
const out = []
fragment.forEach(node => {
let next = node
if (!node.isTextblock && !node.isLeaf) next = node.copy(stripMarkers(node.content, taken))
if (next.attrs.marker && taken.has(next.attrs.marker)) {
next = next.type.create({ ...next.attrs, marker: null }, next.content, next.marks)
}
out.push(next)
})
return Fragment.from(out)
}
export function stripTakenMarkers (slice, state, fidelity) {
const taken = takenMarkers(state, fidelity)
if (taken.size === 0) return slice
return new Slice(stripMarkers(slice.content, taken), slice.openStart, slice.openEnd)
}
// pasteTransaction is a paste of an x-mapa slice over the selection, or
// null when data is not one. Its blocks get fresh origins recorded with
// their sources and the seams between them.
export function pasteTransaction (state, fidelity, data) {
const body = slicePayload(data)
if (body === null) return null
const { doc } = recordBody(state.schema, fidelity, body, { trailing: false, edges: false })
// Into a column, a layout arrives as its blocks: layouts never nest.
const content = inColumn(state.selection.$from) ? withoutLayouts(doc.content) : doc.content
const slice = stripTakenMarkers(Slice.maxOpen(content), state, fidelity)
// Into an empty paragraph of its own (where a cut leaves the caret),
// the blocks replace it whole rather than merging into it, so every
// pasted block keeps its source and the seams between them.
const { $from, empty } = state.selection
if (empty && $from.depth === 1 && $from.parent.type.name === 'paragraph' &&
$from.parent.content.size === 0) {
const tr = state.tr.replaceWith($from.before(), $from.after(), slice.content)
const end = $from.before() + slice.content.size
return tr.setSelection(TextSelection.near(tr.doc.resolve(end), -1))
}
return state.tr.replaceSelection(slice)
}
// textSlice is text/plain from outside, read as Mapa Markdown.
export function textSlice (schema, text) {
const doc = fromMarkdown(schema, text, { trailing: false })
return doc.childCount ? Slice.maxOpen(doc.content) : Slice.empty
}
// sliceText is a slice's Markdown, written from its nodes, for a slice
// that is not the selection.
function sliceText (schema, slice) {
let content = slice.content
const first = content.firstChild
if (!first) return ''
if (first.isInline) content = Fragment.from(schema.nodes.paragraph.create(null, content))
else if (first.type.name === 'list_item') {
content = Fragment.from(schema.nodes.bullet_list.create(null, content))
}
try {
return serialiseDetailed(schema.topNodeType.create(null, content), null,
{ edges: false, raw: true }).body
} catch {
return slice.content.textBetween(0, slice.content.size, '\n\n')
}
}
const clipboardKey = new PluginKey('mapa-clipboard')
// clipboardPlugin wires the handlers above into the view.
//
// options.page is this page's public id now; options.copy(ids) is POST
// /images/copy, answering { status, json }; options.copied(reply)
// records each copy's answer, and options.refused(why) says why a paste
// went nowhere.
export function clipboardPlugin (fidelity, options = {}) {
const page = () => options.page?.() ?? ''
const copy = (view, event, cut) => {
const data = event.clipboardData
if (!data || view.state.selection.empty) return false
const { text, mapa } = copyData(view.state, fidelity, undefined, undefined, page())
const { dom } = view.serializeForClipboard(view.state.selection.content())
event.preventDefault()
data.clearData()
data.setData('text/html', dom.innerHTML)
data.setData('text/plain', text)
data.setData(mapaType, mapa)
if (cut && crossColumns(view.state)) {
deleteInColumns(view.state, tr => view.dispatch(tr.setMeta('uiEvent', 'cut')))
} else if (cut) {
view.dispatch(view.state.tr.deleteSelection().scrollIntoView()
.setMeta('uiEvent', 'cut'))
}
return true
}
return new Plugin({
key: clipboardKey,
props: {
handleDOMEvents: {
copy: (view, event) => copy(view, event, false),
cut: (view, event) => copy(view, event, true)
},
handlePaste (view, event) {
const data = event.clipboardData?.getData(mapaType)
if (!data) return false
const images = sliceImages(data)
if (images?.ids.length && options.copy && (!images.page || images.page !== page())) {
event.preventDefault()
pasteCopies(view, fidelity, images, options)
return true
}
const tr = pasteTransaction(view.state, fidelity, data)
if (!tr) return false
view.dispatch(tr.scrollIntoView().setMeta('paste', true).setMeta('uiEvent', 'paste'))
return true
},
transformPastedHTML: html => remoteImages(html),
clipboardTextSerializer (slice, view) {
if (view.state.selection.content().eq(slice)) {
return copyData(view.state, fidelity).text
}
return sliceText(view.state.schema, slice)
},
clipboardTextParser (text, $context, plain, view) {
return textSlice(view.state.schema, text)
},
transformPasted (slice, view) {
let pasted = slice
if (inColumn(view.state.selection.$from)) {
let holds = false
slice.content.forEach(node => { holds = holds || node.type.name === 'columns' })
if (holds) pasted = Slice.maxOpen(withoutLayouts(slice.content))
}
return stripTakenMarkers(pasted, view.state, fidelity)
}
}
})
}
// pasteCopies pastes a slice from another page: its images are copied
// first (POST /images/copy), and their addresses rewritten before it
// goes in. An id the person may not read is left out of the reply, and
// stays as typed, drawn as not available (images §2.2). A copy that is
// refused (an allowance, no store, a busy server) pastes nothing and
// says why, rather than pasting addresses that would not draw (Fable
// L3).
async function pasteCopies (view, fidelity, images, options) {
let reply = null
try {
reply = await options.copy(images.ids)
} catch {}
if (!reply || reply.status !== 200) {
options.refused?.(reply?.json?.refused ??
'the images could not be copied. Check your connection and try again.')
return
}
options.copied?.(reply.json ?? {})
const tr = pasteTransaction(view.state, fidelity, withCopies(images.payload, reply.json ?? {}))
if (tr) view.dispatch(tr.scrollIntoView().setMeta('paste', true).setMeta('uiEvent', 'paste'))
}