// page.mjs — the editor on a page (spec §6.8, §6.9). It reads the JSON // island, mounts on the
the server drew (whose HTML // is the editor's own, L4), and wires saving to the page around it. // Before the mount the article is the readable page, not editable, so a // key pressed early types nothing; after it, the same boxes hold the same // text (L5). import { EditorState } from 'prosemirror-state' import { EditorView } from 'prosemirror-view' import { dropCursor } from 'prosemirror-dropcursor' import { gapCursor } from 'prosemirror-gapcursor' import { createSchema } from './schema.mjs' import { useDates } from './dates.mjs' import { mount, fidelityPlugin } from './fidelity.mjs' import { editorAdapter } from './adapter.mjs' import { clipboardPlugin } from './clipboard.mjs' import { Resolutions } from './resolutions.mjs' import { chipViews } from './chipview.mjs' import { Saver } from './saver.mjs' import { keys } from './keys.mjs' import { blockCommands, selectAll, safeUndo, safeRedo } from './commands.mjs' import { history } from 'prosemirror-history' import { rules } from './inputrules.mjs' import * as notices from './notices.mjs' import { conflictPlugin, showConflict } from './conflict.mjs' import { suggestPlugin } from './suggest.mjs' import { slashPlugin } from './slash.mjs' import { bubblePlugin, linkPaste, openPageLink } from './bubble.mjs' import { linkPage } from './pagelink.mjs' import { pickDate, insertToday } from './datepicker.mjs' import { anchorsPlugin } from './anchors.mjs' import { makeTeamPage, movingPlugin } from './maketeam.mjs' import { tasksPlugin } from './tasks.mjs' import { accessoryPlugin } from './accessory.mjs' import { post } from './post.mjs' import { startTitle } from './title.mjs' import { writeAreaPlugin } from './writearea.mjs' import { ImageAnswers, imageViews, imagesPlugin, describeAt } from './imageview.mjs' import { uploadsPlugin, droppingPlugin, chooser, inFlight } from './upload.mjs' import { imageBubblePlugin, live } from './imagebubble.mjs' import { closeOpen } from './altinset.mjs' import { columnsPlugin } from './columns.mjs' // post is a same-origin form POST that answers JSON, with a timeout. export { post } const storage = { get: key => sessionStorage.getItem(key), set: (key, value) => sessionStorage.setItem(key, value), remove: key => sessionStorage.removeItem(key) } // idleDelay is two minutes; a test may shorten it with data-mapa-idle // on , as mapa.js reads it. Nothing in the app sets it. function idleDelay () { const shorter = Number(document.documentElement.getAttribute('data-mapa-idle')) return shorter > 0 ? shorter : undefined } export function start () { const island = document.getElementById('mapa-editor') let article = island?.nextElementSibling while (article?.nodeName === 'SCRIPT') article = article.nextElementSibling if (!article || !article.matches('article[mapa-body]')) return null const data = JSON.parse(island.textContent) // Dates in the reader's locale, before any chip or list is drawn. useDates(data.dates) const resolutions = new Resolutions(data.links, async keys => (await post('/links/resolve', { target: keys })).json) // Images are answered for this page (images §4.5): the island's for // the text mounted over, /links/resolve's for an id typed later. const answers = new ImageAnswers(data.images, async ids => (await post('/links/resolve', { image: ids, page: data.page ?? '' })).json?.images) const schema = createSchema((target, anchor) => resolutions.answer(target, anchor), id => answers.answer(id)) const { doc, fidelity } = mount(schema, data.source) const holder = { view: null } const editor = editorAdapter(holder, fidelity) const saver = new Saver(data, { editor, post, storage, idle: idleDelay(), ui: ui(article, holder), // href may be a function, read when leaving: a Remove confirm page's // way back is the page's address after the commit (imagebubble.mjs). navigate: href => location.assign(typeof href === 'function' ? href() : href), replaceURL: href => history_(href), reload: () => location.reload(), refetch }) holder.saver = saver const images = imageHooks(article, answers, saver) holder.view = view(article, schema, doc, fidelity, resolutions, saver, editor, images) wire(holder.view, saver, article, images) const title = startTitle({ post, hooks: renameHooks(holder.view, saver) }) saver.settle() // A new page (New team page, New scratch page) opens with the caret in // its body (§4.7); a day, the home page, does not take focus. if (data.source.trim() === '' && !data.drafts.startsWith('/d/')) holder.view.focus() performance.mark('mapa-mounted') return { view: holder.view, saver, fidelity, resolutions, title, answers } } // imageHooks are what uploads and the image bubble tell the page: the // answers, the live region, the alt field, a bar's sentence, and // leaving for a Remove confirm page (images §4). function imageHooks (article, answers, saver) { const hooks = { answers, say: live(), // Not while another image's field has the person's attention // (Fable L9): the upload is said instead. alt: (view, pos) => document.activeElement?.closest?.('[mapa-alt]') ? hooks.say('Image added') : describeAt(view, pos, 'upload'), notice: text => notices.show(article, text), leave: href => saver.leave(href), // ⌘S in an image's description field (altinset.mjs). save: () => saver.commit({ explicit: true }) } hooks.choose = chooser(hooks) return hooks } // renameHooks are what a rename in place changes in the editor // (title.mjs): its name, and the saver's base, which follows the rename // when it was the revision the rename was made over. function renameHooks (view, saver) { return { renamed: ({ title, from, to }) => { view.dom.setAttribute('aria-label', `Page text, ${title}`) saver.renamed(from, to) }, refresh: refreshLinks } } function history_ (href) { window.history.replaceState(null, '', href) } // privateNote is whether this page is a note of the viewer's own (a // day, a scratch page, or one the File menu offers to make a team page // from): only those offer Make team page (§6.7). function privateNote (saver) { return saver.drafts.startsWith('/d/') || Boolean(saver.token) || Boolean(document.querySelector('[estilo-menubar] a[href$="/share"]')) } // moved says where the blocks went, until the page is next opened. function moved (article, title, href) { const link = document.createElement('a') link.href = href link.textContent = title const text = document.createElement('span') text.append('Moved to ', link, '.') notices.show(article, text) } // suggestions is /links/suggest's answer for [[ (unchanged, §6.6). async function suggestions (query) { const response = await fetch(`/links/suggest?q=${encodeURIComponent(query)}`, { credentials: 'same-origin' }) return response.ok ? (await response.json()).suggestions ?? [] : [] } function title () { return document.querySelector('h1[mapa-title]')?.textContent.trim() ?? '' } function view (article, schema, doc, fidelity, resolutions, saver, editor, images) { const share = privateNote(saver) ? makeTeamPage({ saver, fidelity, post, notify: (title, href) => moved(article, title, href) }) : null const state = EditorState.create({ doc, plugins: [ suggestPlugin({ ask: suggestions, resolutions }), columnsPlugin(), slashPlugin({ 'insert-image': images.choose }), bubblePlugin({ makeTeamPage: share, ask: suggestions, resolutions }), anchorsPlugin({ title }), movingPlugin(), tasksPlugin(), writeAreaPlugin(), accessoryPlugin({ makeTeamPage: share, linkPage: linkPage(openPageLink), image: images.choose }), imagesPlugin(images.answers), uploadsPlugin(), droppingPlugin(images), imageBubblePlugin(images), ...keys(schema, { save: () => saver.commit({ explicit: true }), linkPage: linkPage(openPageLink) }), ...rules(schema), history(), dropCursor(), gapCursor(), fidelityPlugin(fidelity), linkPaste(), clipboardPlugin(fidelity, { page: () => saver.page ?? '', copy: ids => post('/images/copy', { id: ids }), refused: why => notices.show(article, `Not pasted: ${why}`), copied: reply => { for (const image of Object.values(reply ?? {})) { images.answers.set(image.id, { width: image.width, height: image.height }) } } }), conflictPlugin({ fidelity, isRemote: () => editor.remote, isBusy: () => saver.resolving, resolve: choices => saver.resolve(choices) }) ] }) const editorView = new EditorView({ mount: article }, { state, nodeViews: { ...chipViews(resolutions), ...imageViews(images.answers, images) }, attributes: { role: 'textbox', 'aria-multiline': 'true', 'aria-label': `Page text, ${title()}`, spellcheck: 'true' }, dispatchTransaction (tr) { this.updateState(this.state.apply(tr)) if (tr.docChanged && !editor.remote) { saver.changed() uncommitted(saver) } }, // A plain click on a chip follows it (§6.6), through leaving. handleClickOn (view, pos, node, nodePos, event) { if (!['wikilink', 'datelink'].includes(node.type.name)) return false if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false const href = view.nodeDOM(nodePos)?.getAttribute?.('href') if (!href) return false event.preventDefault() closeOpen() saver.leave(href) return true } }) shareFromMenu(editorView, share) return editorView } // shareFromMenu: with blocks selected, File → Make team page… starts // from the selection, as the bubble does; with none, it is the page of // checkboxes it always was. function shareFromMenu (view, share) { const link = document.querySelector('[estilo-menubar] a[href$="/share"]') if (!link || !share) return link.addEventListener('click', event => { if (view.state.selection.empty) return event.preventDefault() link.closest('details')?.removeAttribute('open') share(view) }) } // ui is the saver's view of the page around the editor. function ui (article, holder) { return { status: state => { notices.status(state) if (holder.saver) uncommitted(holder.saver) }, notice: (kind, info) => flushFirst(notices.notice(article, kind, info), holder.saver), leaving: (kind, go) => flushFirst(notices.leaving(article, kind, go), holder.saver), conflict: conflict => showConflict(holder.view, conflict), // After a commit the draft bar's "unsaved changes" are saved, and the // panel reads the new committed text. committed: () => { document.querySelector('[mapa-unsaved]:not([mapa-editor-notice])')?.remove() refreshLinks() } } } // flushFirst makes a bar's forms store what is typed before they post: // Save as a scratch page takes the draft as stored, and Discard names // the version this tab now holds (review H1). A form that carries the // text itself (POST /scratch, for a page deleted before anything was // stored) is given it instead. When the flush fails the form is not // sent, and the bar says so (review round 4). function flushFirst (bar, saver) { for (const formNode of bar?.querySelectorAll?.('form') ?? []) { formNode.addEventListener('submit', async event => { event.preventDefault() const body = formNode.querySelector('input[name="body"]') if (body) { body.value = saver.deps.editor.prepare() } else if (!(await saver.flush())) { notSent(bar, saver) return } else { const version = formNode.querySelector('input[name="version"]') if (version) version.value = saver.version } saver.stopped = true formNode.submit() }) } return bar } // notSent tells the person a bar's action waited for a save that failed. function notSent (bar, saver) { saver.status('failed') let line = bar.querySelector('[mapa-not-sent]') if (!line) { line = document.createElement('p') line.setAttribute('mapa-not-sent', '') line.setAttribute('role', 'alert') bar.append(line) } line.textContent = 'Not done: what you typed could not be saved first. Check your connection and try again.' } // uncommitted marks while this tab holds text that leaving would // commit. The speculation ruleset (build note 70) fetches no page ahead // then, and the browser drops a page it fetched before: that page would // not show the commit leaving makes. function uncommitted (saver) { document.documentElement.toggleAttribute('data-mapa-uncommitted', saver.committable()) } // refetch is the page's island as the server would give it now: a GET, // which writes nothing. async function refetch () { const response = await fetch(location.pathname, { credentials: 'same-origin' }) if (!response.ok) return null const fresh = new DOMParser().parseFromString(await response.text(), 'text/html') const island = fresh.getElementById('mapa-editor') return island ? JSON.parse(island.textContent) : null } // refreshLinks draws the Links panel and the page's foot again after a // commit: they read committed text only (§6.8). async function refreshLinks () { let html try { const response = await fetch(location.pathname, { credentials: 'same-origin' }) if (!response.ok) return html = await response.text() } catch { return } const fresh = new DOMParser().parseFromString(html, 'text/html') for (const selector of ['#mapa-links-body', 'footer[mapa-foot-refs]']) { const now = document.querySelector(selector) const next = fresh.querySelector(selector) if (now && next) now.replaceChildren(...next.childNodes) } } // isLeaving is a click that leaves this page for another inside Mapa. function leavingHref (event) { if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null const link = event.target.closest?.('a[href]') if (!link || link.target || link.hasAttribute('download')) return null const url = new URL(link.href, location.href) if (url.origin !== location.origin) return null if (url.pathname === location.pathname && url.search === location.search) return null return url.href } // settled reads typing the view has not taken in yet: ProseMirror reads // some DOM changes on a short timer, and leaving must not miss them. function settled (view) { view.domObserver?.flush?.() } function wire (view, saver, article, images) { // Leaving with an upload in flight asks first, as unsaved text does // (images §4.2). const leave = href => { if (inFlight(view.state) === 0) return saver.leave(href) notices.leaving(article, 'uploading', () => saver.leave(href)) } images.leave = leave window.addEventListener('beforeunload', event => { if (inFlight(view.state) > 0) event.preventDefault() }) document.addEventListener('click', event => { const href = leavingHref(event) // The draft bar's "Show the saved version" looks; it must not commit // the draft it is offering to show beside, and what was typed is // still stored first (review M2). if (href && event.target.closest?.('[mapa-unsaved] a[href]')) { event.preventDefault() closeOpen() settled(view) saver.hold() // A failed flush does not go: the person is told, and may leave // anyway, knowing what is lost (review round 4). saver.flush().then(stored => { if (stored) location.assign(href) else saver.deps.ui.leaving('failed', () => { saver.stopped = true; location.assign(href) }) }, () => saver.deps.ui.leaving('failed', () => { saver.stopped = true; location.assign(href) })) return } if (!href) return // A description being typed goes with the page (Fable M2). closeOpen() settled(view) if (!saver.committable() && inFlight(view.state) === 0) return event.preventDefault() leave(href) }) // The Navigation API says when the page is being reloaded; where // there is none, a reload commits as a close does. let reloading = false globalThis.navigation?.addEventListener?.('navigate', event => { reloading = event.navigationType === 'reload' }) window.addEventListener('pagehide', () => { closeOpen() settled(view) saver.closing({ reloading }) }) window.addEventListener('pageshow', event => { if (event.persisted) saver.shown() }) draftBar(saver) menuCommands(view, images) notices.status(saver.own || saver.offered ? 'saved' : 'idle') } // menuCommands binds the Edit and Insert menus to the editor (§3.4); // mapa.js binds them on the Markdown textarea instead. Insert → Link to // a page is ⌘L's: over a selection it links the words (build note 81); // Date… opens the date picker (build note 83). function menuCommands (view, images) { const commands = { ...blockCommands(view.state.schema), undo: safeUndo, redo: safeRedo, 'select-all': selectAll, 'insert-link': linkPage(openPageLink), 'insert-date-pick': pickDate, 'insert-date': insertToday, 'insert-image': images.choose } for (const control of document.querySelectorAll('[data-mapa-command]')) { const command = commands[control.getAttribute('data-mapa-command')] if (!command) continue control.disabled = false control.addEventListener('click', event => { event.preventDefault() control.closest('details')?.removeAttribute('open') view.focus() command(view.state, view.dispatch, view) }) } } // draftBar is the bar over a draft (§6.8): Save commits it, offered or // not; Discard drops the version this tab holds and shows the page. function draftBar (saver) { const bar = document.querySelector('[mapa-unsaved]:not([mapa-editor-notice])') if (!bar) return for (const formNode of bar.querySelectorAll('form')) { const save = /\/draft\/save$/u.test(formNode.getAttribute('action')) formNode.addEventListener('submit', async event => { event.preventDefault() if (save) { // Safari's press moves no focus: an open description goes too. closeOpen() const outcome = await saver.commit({ explicit: true }) if (outcome === 'saved' || outcome === 'merged') bar.remove() return } saver.stopped = true const reply = await post(formNode.getAttribute('action'), { version: saver.version }) location.assign(reply.json?.href ?? location.pathname) }) } }