| 1 | // page.mjs — the editor on a page (spec §6.8, §6.9). It reads the JSON |
| 2 | // island, mounts on the <article mapa-body> the server drew (whose HTML |
| 3 | // is the editor's own, L4), and wires saving to the page around it. |
| 4 | // Before the mount the article is the readable page, not editable, so a |
| 5 | // key pressed early types nothing; after it, the same boxes hold the same |
| 6 | // text (L5). |
| 7 | |
| 8 | import { EditorState } from 'prosemirror-state' |
| 9 | import { EditorView } from 'prosemirror-view' |
| 10 | import { dropCursor } from 'prosemirror-dropcursor' |
| 11 | import { gapCursor } from 'prosemirror-gapcursor' |
| 12 | import { createSchema } from './schema.mjs' |
| 13 | import { useDates } from './dates.mjs' |
| 14 | import { mount, fidelityPlugin } from './fidelity.mjs' |
| 15 | import { editorAdapter } from './adapter.mjs' |
| 16 | import { clipboardPlugin } from './clipboard.mjs' |
| 17 | import { Resolutions } from './resolutions.mjs' |
| 18 | import { chipViews } from './chipview.mjs' |
| 19 | import { Saver } from './saver.mjs' |
| 20 | import { keys } from './keys.mjs' |
| 21 | import { blockCommands, selectAll, safeUndo, safeRedo } from './commands.mjs' |
| 22 | import { history } from 'prosemirror-history' |
| 23 | import { rules } from './inputrules.mjs' |
| 24 | import * as notices from './notices.mjs' |
| 25 | import { conflictPlugin, showConflict } from './conflict.mjs' |
| 26 | import { suggestPlugin } from './suggest.mjs' |
| 27 | import { slashPlugin } from './slash.mjs' |
| 28 | import { bubblePlugin, linkPaste, openPageLink } from './bubble.mjs' |
| 29 | import { linkPage } from './pagelink.mjs' |
| 30 | import { pickDate, insertToday } from './datepicker.mjs' |
| 31 | import { anchorsPlugin } from './anchors.mjs' |
| 32 | import { makeTeamPage, movingPlugin } from './maketeam.mjs' |
| 33 | import { tasksPlugin } from './tasks.mjs' |
| 34 | import { accessoryPlugin } from './accessory.mjs' |
| 35 | import { post } from './post.mjs' |
| 36 | import { startTitle } from './title.mjs' |
| 37 | import { writeAreaPlugin } from './writearea.mjs' |
| 38 | import { ImageAnswers, imageViews, imagesPlugin, describeAt } from './imageview.mjs' |
| 39 | import { uploadsPlugin, droppingPlugin, chooser, inFlight } from './upload.mjs' |
| 40 | import { imageBubblePlugin, live } from './imagebubble.mjs' |
| 41 | import { closeOpen } from './altinset.mjs' |
| 42 | import { columnsPlugin } from './columns.mjs' |
| 43 | |
| 44 | // post is a same-origin form POST that answers JSON, with a timeout. |
| 45 | export { post } |
| 46 | |
| 47 | const storage = { |
| 48 | get: key => sessionStorage.getItem(key), |
| 49 | set: (key, value) => sessionStorage.setItem(key, value), |
| 50 | remove: key => sessionStorage.removeItem(key) |
| 51 | } |
| 52 | |
| 53 | // idleDelay is two minutes; a test may shorten it with data-mapa-idle |
| 54 | // on <html>, as mapa.js reads it. Nothing in the app sets it. |
| 55 | function idleDelay () { |
| 56 | const shorter = Number(document.documentElement.getAttribute('data-mapa-idle')) |
| 57 | return shorter > 0 ? shorter : undefined |
| 58 | } |
| 59 | |
| 60 | export function start () { |
| 61 | const island = document.getElementById('mapa-editor') |
| 62 | let article = island?.nextElementSibling |
| 63 | while (article?.nodeName === 'SCRIPT') article = article.nextElementSibling |
| 64 | if (!article || !article.matches('article[mapa-body]')) return null |
| 65 | const data = JSON.parse(island.textContent) |
| 66 | // Dates in the reader's locale, before any chip or list is drawn. |
| 67 | useDates(data.dates) |
| 68 | const resolutions = new Resolutions(data.links, |
| 69 | async keys => (await post('/links/resolve', { target: keys })).json) |
| 70 | // Images are answered for this page (images §4.5): the island's for |
| 71 | // the text mounted over, /links/resolve's for an id typed later. |
| 72 | const answers = new ImageAnswers(data.images, async ids => |
| 73 | (await post('/links/resolve', { image: ids, page: data.page ?? '' })).json?.images) |
| 74 | const schema = createSchema((target, anchor) => resolutions.answer(target, anchor), |
| 75 | id => answers.answer(id)) |
| 76 | const { doc, fidelity } = mount(schema, data.source) |
| 77 | const holder = { view: null } |
| 78 | const editor = editorAdapter(holder, fidelity) |
| 79 | const saver = new Saver(data, { |
| 80 | editor, post, storage, idle: idleDelay(), |
| 81 | ui: ui(article, holder), |
| 82 | // href may be a function, read when leaving: a Remove confirm page's |
| 83 | // way back is the page's address after the commit (imagebubble.mjs). |
| 84 | navigate: href => location.assign(typeof href === 'function' ? href() : href), |
| 85 | replaceURL: href => history_(href), |
| 86 | reload: () => location.reload(), |
| 87 | refetch |
| 88 | }) |
| 89 | holder.saver = saver |
| 90 | const images = imageHooks(article, answers, saver) |
| 91 | holder.view = view(article, schema, doc, fidelity, resolutions, saver, editor, images) |
| 92 | wire(holder.view, saver, article, images) |
| 93 | const title = startTitle({ post, hooks: renameHooks(holder.view, saver) }) |
| 94 | saver.settle() |
| 95 | // A new page (New team page, New scratch page) opens with the caret in |
| 96 | // its body (§4.7); a day, the home page, does not take focus. |
| 97 | if (data.source.trim() === '' && !data.drafts.startsWith('/d/')) holder.view.focus() |
| 98 | performance.mark('mapa-mounted') |
| 99 | return { view: holder.view, saver, fidelity, resolutions, title, answers } |
| 100 | } |
| 101 | |
| 102 | // imageHooks are what uploads and the image bubble tell the page: the |
| 103 | // answers, the live region, the alt field, a bar's sentence, and |
| 104 | // leaving for a Remove confirm page (images §4). |
| 105 | function imageHooks (article, answers, saver) { |
| 106 | const hooks = { |
| 107 | answers, |
| 108 | say: live(), |
| 109 | // Not while another image's field has the person's attention |
| 110 | // (Fable L9): the upload is said instead. |
| 111 | alt: (view, pos) => document.activeElement?.closest?.('[mapa-alt]') |
| 112 | ? hooks.say('Image added') : describeAt(view, pos, 'upload'), |
| 113 | notice: text => notices.show(article, text), |
| 114 | leave: href => saver.leave(href), |
| 115 | // ⌘S in an image's description field (altinset.mjs). |
| 116 | save: () => saver.commit({ explicit: true }) |
| 117 | } |
| 118 | hooks.choose = chooser(hooks) |
| 119 | return hooks |
| 120 | } |
| 121 | |
| 122 | // renameHooks are what a rename in place changes in the editor |
| 123 | // (title.mjs): its name, and the saver's base, which follows the rename |
| 124 | // when it was the revision the rename was made over. |
| 125 | function renameHooks (view, saver) { |
| 126 | return { |
| 127 | renamed: ({ title, from, to }) => { |
| 128 | view.dom.setAttribute('aria-label', `Page text, ${title}`) |
| 129 | saver.renamed(from, to) |
| 130 | }, |
| 131 | refresh: refreshLinks |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | function history_ (href) { |
| 136 | window.history.replaceState(null, '', href) |
| 137 | } |
| 138 | |
| 139 | // privateNote is whether this page is a note of the viewer's own (a |
| 140 | // day, a scratch page, or one the File menu offers to make a team page |
| 141 | // from): only those offer Make team page (§6.7). |
| 142 | function privateNote (saver) { |
| 143 | return saver.drafts.startsWith('/d/') || Boolean(saver.token) || |
| 144 | Boolean(document.querySelector('[estilo-menubar] a[href$="/share"]')) |
| 145 | } |
| 146 | |
| 147 | // moved says where the blocks went, until the page is next opened. |
| 148 | function moved (article, title, href) { |
| 149 | const link = document.createElement('a') |
| 150 | link.href = href |
| 151 | link.textContent = title |
| 152 | const text = document.createElement('span') |
| 153 | text.append('Moved to ', link, '.') |
| 154 | notices.show(article, text) |
| 155 | } |
| 156 | |
| 157 | // suggestions is /links/suggest's answer for [[ (unchanged, §6.6). |
| 158 | async function suggestions (query) { |
| 159 | const response = await fetch(`/links/suggest?q=${encodeURIComponent(query)}`, |
| 160 | { credentials: 'same-origin' }) |
| 161 | return response.ok ? (await response.json()).suggestions ?? [] : [] |
| 162 | } |
| 163 | |
| 164 | function title () { |
| 165 | return document.querySelector('h1[mapa-title]')?.textContent.trim() ?? '' |
| 166 | } |
| 167 | |
| 168 | function view (article, schema, doc, fidelity, resolutions, saver, editor, images) { |
| 169 | const share = privateNote(saver) |
| 170 | ? makeTeamPage({ saver, fidelity, post, notify: (title, href) => moved(article, title, href) }) |
| 171 | : null |
| 172 | const state = EditorState.create({ |
| 173 | doc, |
| 174 | plugins: [ |
| 175 | suggestPlugin({ ask: suggestions, resolutions }), columnsPlugin(), |
| 176 | slashPlugin({ 'insert-image': images.choose }), |
| 177 | bubblePlugin({ makeTeamPage: share, ask: suggestions, resolutions }), |
| 178 | anchorsPlugin({ title }), movingPlugin(), |
| 179 | tasksPlugin(), writeAreaPlugin(), accessoryPlugin({ makeTeamPage: share, linkPage: linkPage(openPageLink), image: images.choose }), |
| 180 | imagesPlugin(images.answers), uploadsPlugin(), droppingPlugin(images), imageBubblePlugin(images), |
| 181 | ...keys(schema, { save: () => saver.commit({ explicit: true }), linkPage: linkPage(openPageLink) }), |
| 182 | ...rules(schema), history(), dropCursor(), gapCursor(), |
| 183 | fidelityPlugin(fidelity), linkPaste(), |
| 184 | clipboardPlugin(fidelity, { |
| 185 | page: () => saver.page ?? '', |
| 186 | copy: ids => post('/images/copy', { id: ids }), |
| 187 | refused: why => notices.show(article, `Not pasted: ${why}`), |
| 188 | copied: reply => { |
| 189 | for (const image of Object.values(reply ?? {})) { |
| 190 | images.answers.set(image.id, { width: image.width, height: image.height }) |
| 191 | } |
| 192 | } |
| 193 | }), |
| 194 | conflictPlugin({ |
| 195 | fidelity, |
| 196 | isRemote: () => editor.remote, |
| 197 | isBusy: () => saver.resolving, |
| 198 | resolve: choices => saver.resolve(choices) |
| 199 | }) |
| 200 | ] |
| 201 | }) |
| 202 | const editorView = new EditorView({ mount: article }, { |
| 203 | state, |
| 204 | nodeViews: { ...chipViews(resolutions), ...imageViews(images.answers, images) }, |
| 205 | attributes: { |
| 206 | role: 'textbox', 'aria-multiline': 'true', |
| 207 | 'aria-label': `Page text, ${title()}`, spellcheck: 'true' |
| 208 | }, |
| 209 | dispatchTransaction (tr) { |
| 210 | this.updateState(this.state.apply(tr)) |
| 211 | if (tr.docChanged && !editor.remote) { |
| 212 | saver.changed() |
| 213 | uncommitted(saver) |
| 214 | } |
| 215 | }, |
| 216 | // A plain click on a chip follows it (§6.6), through leaving. |
| 217 | handleClickOn (view, pos, node, nodePos, event) { |
| 218 | if (!['wikilink', 'datelink'].includes(node.type.name)) return false |
| 219 | if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false |
| 220 | const href = view.nodeDOM(nodePos)?.getAttribute?.('href') |
| 221 | if (!href) return false |
| 222 | event.preventDefault() |
| 223 | closeOpen() |
| 224 | saver.leave(href) |
| 225 | return true |
| 226 | } |
| 227 | }) |
| 228 | shareFromMenu(editorView, share) |
| 229 | return editorView |
| 230 | } |
| 231 | |
| 232 | // shareFromMenu: with blocks selected, File → Make team page… starts |
| 233 | // from the selection, as the bubble does; with none, it is the page of |
| 234 | // checkboxes it always was. |
| 235 | function shareFromMenu (view, share) { |
| 236 | const link = document.querySelector('[estilo-menubar] a[href$="/share"]') |
| 237 | if (!link || !share) return |
| 238 | link.addEventListener('click', event => { |
| 239 | if (view.state.selection.empty) return |
| 240 | event.preventDefault() |
| 241 | link.closest('details')?.removeAttribute('open') |
| 242 | share(view) |
| 243 | }) |
| 244 | } |
| 245 | |
| 246 | // ui is the saver's view of the page around the editor. |
| 247 | function ui (article, holder) { |
| 248 | return { |
| 249 | status: state => { |
| 250 | notices.status(state) |
| 251 | if (holder.saver) uncommitted(holder.saver) |
| 252 | }, |
| 253 | notice: (kind, info) => flushFirst(notices.notice(article, kind, info), holder.saver), |
| 254 | leaving: (kind, go) => flushFirst(notices.leaving(article, kind, go), holder.saver), |
| 255 | conflict: conflict => showConflict(holder.view, conflict), |
| 256 | // After a commit the draft bar's "unsaved changes" are saved, and the |
| 257 | // panel reads the new committed text. |
| 258 | committed: () => { |
| 259 | document.querySelector('[mapa-unsaved]:not([mapa-editor-notice])')?.remove() |
| 260 | refreshLinks() |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | // flushFirst makes a bar's forms store what is typed before they post: |
| 266 | // Save as a scratch page takes the draft as stored, and Discard names |
| 267 | // the version this tab now holds (review H1). A form that carries the |
| 268 | // text itself (POST /scratch, for a page deleted before anything was |
| 269 | // stored) is given it instead. When the flush fails the form is not |
| 270 | // sent, and the bar says so (review round 4). |
| 271 | function flushFirst (bar, saver) { |
| 272 | for (const formNode of bar?.querySelectorAll?.('form') ?? []) { |
| 273 | formNode.addEventListener('submit', async event => { |
| 274 | event.preventDefault() |
| 275 | const body = formNode.querySelector('input[name="body"]') |
| 276 | if (body) { |
| 277 | body.value = saver.deps.editor.prepare() |
| 278 | } else if (!(await saver.flush())) { |
| 279 | notSent(bar, saver) |
| 280 | return |
| 281 | } else { |
| 282 | const version = formNode.querySelector('input[name="version"]') |
| 283 | if (version) version.value = saver.version |
| 284 | } |
| 285 | saver.stopped = true |
| 286 | formNode.submit() |
| 287 | }) |
| 288 | } |
| 289 | return bar |
| 290 | } |
| 291 | |
| 292 | // notSent tells the person a bar's action waited for a save that failed. |
| 293 | function notSent (bar, saver) { |
| 294 | saver.status('failed') |
| 295 | let line = bar.querySelector('[mapa-not-sent]') |
| 296 | if (!line) { |
| 297 | line = document.createElement('p') |
| 298 | line.setAttribute('mapa-not-sent', '') |
| 299 | line.setAttribute('role', 'alert') |
| 300 | bar.append(line) |
| 301 | } |
| 302 | line.textContent = 'Not done: what you typed could not be saved first. Check your connection and try again.' |
| 303 | } |
| 304 | |
| 305 | // uncommitted marks <html> while this tab holds text that leaving would |
| 306 | // commit. The speculation ruleset (build note 70) fetches no page ahead |
| 307 | // then, and the browser drops a page it fetched before: that page would |
| 308 | // not show the commit leaving makes. |
| 309 | function uncommitted (saver) { |
| 310 | document.documentElement.toggleAttribute('data-mapa-uncommitted', saver.committable()) |
| 311 | } |
| 312 | |
| 313 | // refetch is the page's island as the server would give it now: a GET, |
| 314 | // which writes nothing. |
| 315 | async function refetch () { |
| 316 | const response = await fetch(location.pathname, { credentials: 'same-origin' }) |
| 317 | if (!response.ok) return null |
| 318 | const fresh = new DOMParser().parseFromString(await response.text(), 'text/html') |
| 319 | const island = fresh.getElementById('mapa-editor') |
| 320 | return island ? JSON.parse(island.textContent) : null |
| 321 | } |
| 322 | |
| 323 | // refreshLinks draws the Links panel and the page's foot again after a |
| 324 | // commit: they read committed text only (§6.8). |
| 325 | async function refreshLinks () { |
| 326 | let html |
| 327 | try { |
| 328 | const response = await fetch(location.pathname, { credentials: 'same-origin' }) |
| 329 | if (!response.ok) return |
| 330 | html = await response.text() |
| 331 | } catch { |
| 332 | return |
| 333 | } |
| 334 | const fresh = new DOMParser().parseFromString(html, 'text/html') |
| 335 | for (const selector of ['#mapa-links-body', 'footer[mapa-foot-refs]']) { |
| 336 | const now = document.querySelector(selector) |
| 337 | const next = fresh.querySelector(selector) |
| 338 | if (now && next) now.replaceChildren(...next.childNodes) |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | // isLeaving is a click that leaves this page for another inside Mapa. |
| 343 | function leavingHref (event) { |
| 344 | if (event.defaultPrevented || event.button !== 0 || event.metaKey || |
| 345 | event.ctrlKey || event.shiftKey || event.altKey) return null |
| 346 | const link = event.target.closest?.('a[href]') |
| 347 | if (!link || link.target || link.hasAttribute('download')) return null |
| 348 | const url = new URL(link.href, location.href) |
| 349 | if (url.origin !== location.origin) return null |
| 350 | if (url.pathname === location.pathname && url.search === location.search) return null |
| 351 | return url.href |
| 352 | } |
| 353 | |
| 354 | // settled reads typing the view has not taken in yet: ProseMirror reads |
| 355 | // some DOM changes on a short timer, and leaving must not miss them. |
| 356 | function settled (view) { |
| 357 | view.domObserver?.flush?.() |
| 358 | } |
| 359 | |
| 360 | function wire (view, saver, article, images) { |
| 361 | // Leaving with an upload in flight asks first, as unsaved text does |
| 362 | // (images §4.2). |
| 363 | const leave = href => { |
| 364 | if (inFlight(view.state) === 0) return saver.leave(href) |
| 365 | notices.leaving(article, 'uploading', () => saver.leave(href)) |
| 366 | } |
| 367 | images.leave = leave |
| 368 | window.addEventListener('beforeunload', event => { |
| 369 | if (inFlight(view.state) > 0) event.preventDefault() |
| 370 | }) |
| 371 | document.addEventListener('click', event => { |
| 372 | const href = leavingHref(event) |
| 373 | // The draft bar's "Show the saved version" looks; it must not commit |
| 374 | // the draft it is offering to show beside, and what was typed is |
| 375 | // still stored first (review M2). |
| 376 | if (href && event.target.closest?.('[mapa-unsaved] a[href]')) { |
| 377 | event.preventDefault() |
| 378 | closeOpen() |
| 379 | settled(view) |
| 380 | saver.hold() |
| 381 | // A failed flush does not go: the person is told, and may leave |
| 382 | // anyway, knowing what is lost (review round 4). |
| 383 | saver.flush().then(stored => { |
| 384 | if (stored) location.assign(href) |
| 385 | else saver.deps.ui.leaving('failed', () => { saver.stopped = true; location.assign(href) }) |
| 386 | }, () => saver.deps.ui.leaving('failed', () => { saver.stopped = true; location.assign(href) })) |
| 387 | return |
| 388 | } |
| 389 | if (!href) return |
| 390 | // A description being typed goes with the page (Fable M2). |
| 391 | closeOpen() |
| 392 | settled(view) |
| 393 | if (!saver.committable() && inFlight(view.state) === 0) return |
| 394 | event.preventDefault() |
| 395 | leave(href) |
| 396 | }) |
| 397 | // The Navigation API says when the page is being reloaded; where |
| 398 | // there is none, a reload commits as a close does. |
| 399 | let reloading = false |
| 400 | globalThis.navigation?.addEventListener?.('navigate', event => { |
| 401 | reloading = event.navigationType === 'reload' |
| 402 | }) |
| 403 | window.addEventListener('pagehide', () => { |
| 404 | closeOpen() |
| 405 | settled(view) |
| 406 | saver.closing({ reloading }) |
| 407 | }) |
| 408 | window.addEventListener('pageshow', event => { if (event.persisted) saver.shown() }) |
| 409 | draftBar(saver) |
| 410 | menuCommands(view, images) |
| 411 | notices.status(saver.own || saver.offered ? 'saved' : 'idle') |
| 412 | } |
| 413 | |
| 414 | // menuCommands binds the Edit and Insert menus to the editor (§3.4); |
| 415 | // mapa.js binds them on the Markdown textarea instead. Insert → Link to |
| 416 | // a page is ⌘L's: over a selection it links the words (build note 81); |
| 417 | // Date… opens the date picker (build note 83). |
| 418 | function menuCommands (view, images) { |
| 419 | const commands = { |
| 420 | ...blockCommands(view.state.schema), undo: safeUndo, redo: safeRedo, 'select-all': selectAll, |
| 421 | 'insert-link': linkPage(openPageLink), 'insert-date-pick': pickDate, |
| 422 | 'insert-date': insertToday, 'insert-image': images.choose |
| 423 | } |
| 424 | for (const control of document.querySelectorAll('[data-mapa-command]')) { |
| 425 | const command = commands[control.getAttribute('data-mapa-command')] |
| 426 | if (!command) continue |
| 427 | control.disabled = false |
| 428 | control.addEventListener('click', event => { |
| 429 | event.preventDefault() |
| 430 | control.closest('details')?.removeAttribute('open') |
| 431 | view.focus() |
| 432 | command(view.state, view.dispatch, view) |
| 433 | }) |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | // draftBar is the bar over a draft (§6.8): Save commits it, offered or |
| 438 | // not; Discard drops the version this tab holds and shows the page. |
| 439 | function draftBar (saver) { |
| 440 | const bar = document.querySelector('[mapa-unsaved]:not([mapa-editor-notice])') |
| 441 | if (!bar) return |
| 442 | for (const formNode of bar.querySelectorAll('form')) { |
| 443 | const save = /\/draft\/save$/u.test(formNode.getAttribute('action')) |
| 444 | formNode.addEventListener('submit', async event => { |
| 445 | event.preventDefault() |
| 446 | if (save) { |
| 447 | // Safari's press moves no focus: an open description goes too. |
| 448 | closeOpen() |
| 449 | const outcome = await saver.commit({ explicit: true }) |
| 450 | if (outcome === 'saved' || outcome === 'merged') bar.remove() |
| 451 | return |
| 452 | } |
| 453 | saver.stopped = true |
| 454 | const reply = await post(formNode.getAttribute('action'), { version: saver.version }) |
| 455 | location.assign(reply.json?.href ?? location.pathname) |
| 456 | }) |
| 457 | } |
| 458 | } |
| 459 | |