// bubble.mjs — the selection bubble (spec §6.6, §6.11): bold, italic, // code, Page link and Web link over a selection, then Make team page on // a private note. It sits above the selection, or below it on a coarse // pointer, clear of iOS's own callout, and above the keyboard. // // Page link (⌘L, build note 81) opens a field holding the selected // words, with the same pages [[ offers; choosing one makes the words a // chip, [[Target|words]]. Web link (⌘⇧K) opens the address field. Two // fields, not one guessing: "example.com" is as good a page title as an // address. A URL pasted over a selection makes a web link (linkPaste). import { Plugin, PluginKey, TextSelection } from 'prosemirror-state' import { toggleMark } from 'prosemirror-commands' import { safeURL } from './markup.mjs' import { Combobox } from './combobox.mjs' import { rows } from './suggest.mjs' import { linkable, linkCheck, pageLinkSource } from './pagelink.mjs' export const bubbleKey = new PluginKey('mapa-bubble') // openers is each view's Page link, for ⌘L, the Insert menu and the // phone's row (pagelink.mjs's linkPage). const openers = new WeakMap() // openPageLink opens the bubble's Page link over found (linkable's). export function openPageLink (view, found) { openers.get(view)?.(found) } function element (tag, attrs = {}, text = '') { const node = document.createElement(tag) for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value) if (text) node.textContent = text return node } function markActive (state, type) { const { from, to, empty, $from } = state.selection return empty ? Boolean(type.isInSet(state.storedMarks || $from.marks())) : state.doc.rangeHasMark(from, to, type) } // setLink links the selection to href, or unlinks it with none. export function setLink (href) { return (state, dispatch) => { const { from, to, empty } = state.selection const type = state.schema.marks.link if (empty) return false if (dispatch) { const tr = state.tr.removeMark(from, to, type) if (href) tr.addMark(from, to, type.create({ href })) dispatch(tr) } return true } } function showing (state) { const { selection } = state return selection instanceof TextSelection && !selection.empty && !selection.$from.parent.type.spec.code } const pageCount = items => items.length === 1 ? '1 page' : `${items.length} pages` // pageLink is the bubble's Page link: its field, its list, and the // line that says why a selection cannot be linked. function pageLink (view, bar, { ask, resolutions, back }) { const field = element('input', { type: 'text', role: 'combobox', 'aria-autocomplete': 'list', 'aria-expanded': 'false', 'aria-label': 'Page to link to', placeholder: 'Find a page', autocomplete: 'off', 'mapa-bubble-page': '' }) field.hidden = true const note = element('p', { role: 'status', 'mapa-bubble-note': '' }) bar.append(field, note) const box = new Combobox(view, { label: 'Pages to link to', count: pageCount, input: field }) let words = '' let asked = 0 let timer = null const close = () => { asked++ clearTimeout(timer) box.close() field.hidden = true } // choose links the words, or says why not (review low 2): the page // changed under the field, or the link would not read back. const choose = target => view => { const { tr, refuse } = linkCheck(view.state, target, words) close() if (tr) view.dispatch(tr) else note.textContent = refuse back() } // make is a row's action, or null for a target the words cannot be // linked to as typed (a # or | in a page not written yet). const make = target => pageLinkSource(target, target === words ? '' : words) ? choose(target) : null async function refresh () { const mine = ++asked const text = field.value let suggestions = [] try { suggestions = await ask(text) } catch {} const states = resolutions ? await resolutions.lookup(suggestions.map(row => row.text)) : {} if (mine !== asked || field.hidden) return box.show(rows({ text }, suggestions, states, make).filter(item => item.run), 0) } field.addEventListener('input', () => { clearTimeout(timer) timer = setTimeout(refresh, 30) }) field.addEventListener('keydown', event => { if (event.isComposing) return if (event.key === 'Escape') { event.preventDefault() close() back() return } if (box.keys(event)) { event.preventDefault() return } if (event.key === 'Enter') event.preventDefault() }) field.addEventListener('blur', () => box.close()) return { open (found) { note.textContent = '' if (found.refuse) { close() note.textContent = found.refuse return false } words = found.words field.hidden = false field.value = words field.focus() field.select() refresh() return true }, close, // quiet takes the note away when the selection moves on. quiet () { note.textContent = '' }, // saying is whether the note is up: the bubble stays to show it, // even over a selection it has no buttons for (⌘A, review low 1). get saying () { return note.textContent !== '' }, destroy () { box.destroy() } } } export function bubblePlugin ({ makeTeamPage = null, ask = async () => [], resolutions = null } = {}) { let bar = null let field = null return new Plugin({ key: bubbleKey, view (view) { const schema = view.state.schema bar = element('div', { 'mapa-bubble': '', role: 'toolbar', 'aria-label': 'Format' }) bar.hidden = true const fields = () => [...bar.querySelectorAll('input')] bar.addEventListener('mousedown', event => { if (!fields().includes(event.target)) event.preventDefault() }) // The toolbar's own keys: arrows move between its buttons, Esc goes // back to the text. bar.addEventListener('keydown', event => { if (fields().includes(event.target)) return const all = [...bar.querySelectorAll('button')] const at = all.indexOf(document.activeElement) if (event.key === 'Escape') { event.preventDefault() view.focus() } else if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') { event.preventDefault() all[(at + (event.key === 'ArrowRight' ? 1 : -1) + all.length) % all.length]?.focus() } }) const buttons = [] const add = (label, text, run, { mark = null, keeps = false, title = '' } = {}) => { const button = element('button', { type: 'button', 'aria-label': label, 'mapa-bubble-button': '' }, text) if (title) button.title = title button.addEventListener('click', () => { run(view) if (!keeps) view.focus() }) bar.append(button) buttons.push({ button, mark }) return button } add('Bold', 'B', view => toggleMark(schema.marks.strong)(view.state, view.dispatch), { mark: schema.marks.strong }) add('Italic', 'I', view => toggleMark(schema.marks.em)(view.state, view.dispatch), { mark: schema.marks.em }) add('Code', '<>', view => toggleMark(schema.marks.code)(view.state, view.dispatch), { mark: schema.marks.code }) add('Page link', 'Page link', view => openPage(linkable(view.state)), { keeps: true, title: 'Link to a page (⌘L)' }) add('Web link', 'Web link', () => openLink(), { mark: schema.marks.link, keeps: true, title: 'Link to a web address (⇧⌘K)' }) if (makeTeamPage) add('Make team page', 'Make team page', view => makeTeamPage(view), { keeps: true }) field = element('input', { type: 'url', 'aria-label': 'Link address', placeholder: 'Paste a link', 'mapa-bubble-field': '' }) field.hidden = true bar.append(field) document.body.append(bar) const page = pageLink(view, bar, { ask, resolutions, back: () => view.focus() }) field.addEventListener('keydown', event => { if (event.key === 'Enter') { event.preventDefault() const href = field.value.trim() if (href === '' || safeURL(href)) setLink(href)(view.state, view.dispatch) closeLink() } else if (event.key === 'Escape') { event.preventDefault() closeLink() } }) function openLink () { page.close() page.quiet() field.hidden = false field.value = '' field.focus() } function closeLink () { field.hidden = true view.focus() } function openPage (found) { if (!found) return field.hidden = true bar.hidden = false place() if (!page.open(found)) view.focus() place() } bar.openLink = openLink openers.set(view, openPage) const place = () => { const shown = showing(view.state) || (page.saying && !view.state.selection.empty) if (!shown || (!view.hasFocus() && !bar.contains(document.activeElement))) { bar.hidden = true field.hidden = true page.close() return } for (const { button, mark } of buttons) { if (mark) button.setAttribute('aria-pressed', markActive(view.state, mark) ? 'true' : 'false') } bar.hidden = false const { from, to } = view.state.selection const start = view.coordsAtPos(from) const end = view.coordsAtPos(to) const coarse = window.matchMedia('(pointer: coarse)').matches const top = coarse ? end.bottom + 12 : start.top - bar.offsetHeight - 8 const left = Math.max(4, Math.min((start.left + end.left) / 2 - bar.offsetWidth / 2, window.innerWidth - bar.offsetWidth - 4)) bar.style.setProperty('top', `${Math.max(top, 4)}px`) bar.style.setProperty('left', `${left}px`) } const blurred = () => setTimeout(place, 0) view.dom.addEventListener('blur', blurred) bar.addEventListener('focusout', blurred) return { update (view, previous) { if (!view.state.selection.eq(previous.selection)) page.quiet() place() }, destroy () { view.dom.removeEventListener('blur', blurred) openers.delete(view) page.destroy() bar.remove() } } }, props: { handleKeyDown (view, event) { // ⌥F10 moves to the toolbar, as in most editors; Esc comes back. if (event.key === 'F10' && event.altKey && bar && !bar.hidden) { event.preventDefault() bar.querySelector('button')?.focus() return true } if (event.key.toLowerCase() === 'k' && event.shiftKey && (event.metaKey || event.ctrlKey) && showing(view.state)) { event.preventDefault() bar?.openLink() return true } return false } } }) } // linkPaste: a URL pasted over selected text links the text. export function linkPaste () { return new Plugin({ props: { handlePaste (view, event) { const text = event.clipboardData?.getData('text/plain')?.trim() ?? '' if (view.state.selection.empty || !/^https?:\/\/\S+$/u.test(text) || !safeURL(text)) return false return setLink(text)(view.state, view.dispatch) } } }) }