oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1// saver.mjs — autosave, commit and rebase (spec §6.5). Everything the
2// page writes goes through here, and every write is a POST from this
3// tab: nothing runs on the server.
4//
5// - Autosave fires 1.2s after typing stops, with the §6.4 structure
6// check, and only when the text differs from what was last stored.
7// It writes the person's draft, never the page.
8// - A tab's own draft: sessionStorage keeps the last draft version this
9// tab wrote (mapa-draft:<drafts>), so a reload still knows it. Only an
10// own draft commits by itself (⌘S, two minutes idle, leaving inside
11// Mapa, closing the tab); an offered one commits only on Save.
12// - The reply's merge: a clean one is applied when nothing was typed
13// since the send, the table rebuilt against it, and the base moved by
14// the version-checked rebase POST; three tries at most, then the
15// commit's own merge settles it. A conflict is shown inline (the ui's
16// job, conflict.mjs) and only the person's choice commits it.
17// - Some states hold commits but never the text (review H1, M2): a
18// conflict open, a page deleted under the editor, the draft bar's
19// "Show the saved version". Typing still autosaves the draft, and a
20// closing tab still writes it, without commit=1.
21// - A commit is a reply carrying a revision; anything else (an emptied
22// day, a page deleted under the commit) commits nothing (review H2).
23// - A new scratch page's first autosave is its first commit, keyed by a
24// token the tab draws once (D12, build note 31).
25//
26// The editor, the network, storage, timers and the page around it are
27// all passed in, so the gates can drive it without a browser.
28
29import { cleanBody, goTrimSpace, Grammar } from './markup.mjs'
30
31export const AUTOSAVE_DELAY = 1200
32export const IDLE_COMMIT = 2 * 60 * 1000
33// keepaliveCap is under the browsers' 64KB keepalive limit, with room
34// for the other fields.
35export const KEEPALIVE_CAP = 60 * 1024
36const RETRIES = 3
37
38export function drawToken (random = () => Math.random()) {
39 const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
40 let token = ''
41 for (let index = 0; index < 24; index++) token += alphabet[Math.floor(random() * alphabet.length)]
42 return token
43}
44
45export class Saver {
46 constructor (island, deps) {
47 this.deps = deps
48 this.drafts = island.drafts
49 this.page = island.page ?? ''
50 this.token = island.first ? (deps.token ?? drawToken)() : null
51 this.base = island.draft ? island.draft.base : island.base
52 this.version = island.draft ? island.draft.version : '0'
53 this.own = Boolean(island.draft) && this.stored() === island.draft.version
54 // closed is the version this tab's last page sent to be committed as
55 // it went: a page loaded meanwhile (a reload) may still show it.
56 this.closed = Boolean(island.draft) && this.stored('mapa-closing:') === island.draft.version
57 this.offered = Boolean(island.draft) && !this.own
58 // saved is the text the server holds for this tab: the draft's, or
59 // the committed page's.
60 this.saved = cleanBody(island.source)
61 this.loadedVersion = this.version
62 this.dirty = false
63 this.inflight = null
64 this.tries = new Map()
65 this.conflict = null
66 // gone: the page was deleted while this tab wrote. Its text goes on
67 // being stored as the draft, which Today offers as a scratch page,
68 // and nothing commits (review H1).
69 this.gone = false
70 // orphan: the page was deleted before this tab stored any draft on
71 // it, so the store refuses the draft (404) and nothing typed is
72 // stored. The bar offers it as a new scratch page; a close makes one
73 // (review round 4, M-B).
74 this.orphan = false
75 // holding: commits are held (the draft bar's Show the saved version)
76 // while the text is still stored (review M2).
77 this.holding = false
78 // resolving: Resolve's POST is out; the editor takes no typing until
79 // its answer is applied (review M1).
80 this.resolving = false
81 this.stopped = false
82 this.failures = 0
83 // unacked is the text of an autosave that never answered (offline,
84 // or aborted by post's timeout): it may have landed all the same.
85 this.unacked = null
86 this.timers = { autosave: null, idle: null, retry: null }
87 }
88
89 get key () { return `mapa-draft:${this.drafts}` }
90
91 stored (prefix = 'mapa-draft:') {
92 try { return this.deps.storage?.get(prefix + this.drafts) ?? null } catch { return null }
93 }
94
95 remember () {
96 try { this.deps.storage?.set(this.key, this.version) } catch {}
97 }
98
99 forget () {
100 try { this.deps.storage?.remove(this.key) } catch {}
101 }
102
103 status (state) { this.deps.ui?.status?.(state) }
104
105 later (name, fn, ms) {
106 const timers = this.deps.timers ?? globalThis
107 if (this.timers[name] !== null) timers.clearTimeout(this.timers[name])
108 this.timers[name] = timers.setTimeout(() => {
109 this.timers[name] = null
110 fn()
111 }, ms)
112 }
113
114 cancel (name) {
115 const timers = this.deps.timers ?? globalThis
116 if (this.timers[name] !== null) timers.clearTimeout(this.timers[name])
117 this.timers[name] = null
118 }
119
120 // changed is the person typing: the draft becomes this tab's own.
121 changed () {
122 if (this.stopped) return
123 this.dirty = true
124 this.own = true
125 this.offered = false
126 this.cancel('idle')
127 this.later('autosave', () => this.autosave(), this.deps.delay ?? AUTOSAVE_DELAY)
128 }
129
130 // unsaved is whether the tab holds text the server does not.
131 unsaved () {
132 return this.dirty || this.deps.editor.current() !== this.saved
133 }
134
135 // committable is whether there is a draft of this tab's to commit.
136 committable () {
137 return this.own && (this.unsaved() || this.version !== '0')
138 }
139
140 // mayCommit is whether the draft may commit by itself now: never with
141 // a choice open, a page deleted, or commits held.
142 mayCommit () {
143 return !this.conflict && !this.gone && !this.holding
144 }
145
146 // hold keeps the draft from committing from now on, while what is
147 // typed is still stored (the draft bar's Show the saved version).
148 hold () {
149 this.holding = true
150 this.cancel('idle')
151 }
152
153 // autosave sends the text when it differs from what is stored (or
154 // always, with force: to ask for the merge again). It resolves true
155 // when the text is stored.
156 autosave (force = false) {
157 if (this.stopped || this.orphan) return Promise.resolve(false)
158 if (this.inflight) return this.inflight.then(() => this.autosave(force))
159 this.cancel('autosave')
160 const body = this.deps.editor.prepare()
161 if (!force && body === this.saved) {
162 this.dirty = false
163 return Promise.resolve(true)
164 }
165 this.dirty = false
166 this.status('saving')
167 const send = this.token ? this.first(body) : this.send(body)
168 this.inflight = send.finally(() => { this.inflight = null })
169 return this.inflight
170 }
171
172 async send (body) {
173 let reply
174 try {
175 reply = await this.deps.post(this.drafts,
176 { base: this.base, version: this.version, body })
177 } catch {
178 this.unacked = body
179 return this.offline()
180 }
181 if (reply.status === 409) {
182 this.stale(reply.json)
183 return false
184 }
185 this.unacked = null
186 if (reply.status === 404) return this.orphaned()
187 if (reply.status !== 200) return this.offline()
188 this.failures = 0
189 this.stored_(body, reply.json)
190 await this.behind(reply.json.merge, body)
191 return true
192 }
193
194 // stored_ takes an autosave's answer for body.
195 stored_ (body, reply) {
196 this.version = reply.version
197 this.saved = body
198 this.own = true
199 this.remember()
200 this.status(this.gone ? 'draft' : 'saved')
201 if (this.mayCommit()) this.later('idle', () => this.commit(), this.deps.idle ?? IDLE_COMMIT)
202 }
203
204 // offline keeps the text and tries again, then says it failed.
205 offline () {
206 this.dirty = true
207 this.failures++
208 if (this.failures > RETRIES) {
209 this.status('failed')
210 return false
211 }
212 this.status('retrying')
213 this.later('retry', () => this.autosave(), (this.deps.delay ?? AUTOSAVE_DELAY) * 2 ** this.failures)
214 return false
215 }
216
217 // first is a new scratch page's autosave before it has an address:
218 // the first one creates the page, any later one with the token is a
219 // draft on it. An empty page creates nothing.
220 async first (body) {
221 if (goTrimSpace(body) === '') {
222 this.status('idle')
223 return true
224 }
225 let reply
226 try {
227 reply = await this.deps.post('/scratch', { first: this.token, version: this.version, body })
228 } catch {
229 return this.offline()
230 }
231 if (reply.status === 422) {
232 this.status('idle')
233 return true
234 }
235 if (reply.status !== 200) return this.offline()
236 this.failures = 0
237 const answer = reply.json
238 this.token = null
239 this.page = answer.page
240 this.drafts = `/p/${answer.page}/draft`
241 this.deps.replaceURL?.(answer.href)
242 if (answer.version === undefined) {
243 this.base = answer.revision
244 this.saved = body
245 this.status('saved')
246 return true
247 }
248 if (answer.revision !== undefined) this.base = this.base === '0' ? answer.revision : this.base
249 this.stored_(body, answer)
250 await this.behind(answer.merge, body)
251 return true
252 }
253
254 // behind takes the merge an autosave's reply carried, if any. A reply
255 // without a conflict ends any choice on show, whatever it carries
256 // (review M4): a clean merge not applied because of typing included.
257 async behind (merge, sent) {
258 if (this.conflict && !merge?.conflict) this.settled()
259 if (!merge) return
260 if (merge.gone) {
261 this.lost()
262 return
263 }
264 if (merge.noBase) {
265 this.cancel('idle')
266 this.deps.ui?.notice?.('noBase', { page: this.page })
267 return
268 }
269 if (merge.conflict) {
270 this.cancel('idle')
271 if (this.deps.editor.current() !== sent) {
272 this.later('autosave', () => this.autosave(true), 0)
273 return
274 }
275 // The same hunks for a newer version (an edit elsewhere) keep the
276 // choice on show, and what the person has picked in it.
277 if (this.conflict && sameHunks(this.conflict, merge)) {
278 this.conflict = { ...this.conflict, version: this.version, sent }
279 return
280 }
281 this.conflict = { against: merge.against, version: this.version, hunks: merge.hunks, sent }
282 this.deps.ui?.conflict?.(this.conflict)
283 return
284 }
285 await this.rebase(merge.against, merge.body, sent)
286 }
287
288 // orphaned is a 404 from the drafts route: the page was deleted, and
289 // this tab has no draft on it for the store to keep. Nothing more is
290 // sent there; the bar offers the text as a new scratch page.
291 orphaned () {
292 this.cancel('idle')
293 this.cancel('retry')
294 this.dirty = true
295 this.gone = true
296 this.status('orphan')
297 if (!this.orphan) this.deps.ui?.notice?.('orphan', {})
298 this.orphan = true
299 return false
300 }
301
302 // lost is the page deleted under the editor (review H1): the text is
303 // kept as the draft, still autosaved, and nothing commits. The bar
304 // offers Save as a scratch page or Discard.
305 lost () {
306 this.cancel('idle')
307 this.status('draft')
308 if (this.gone) return
309 this.gone = true
310 this.deps.ui?.notice?.('gone', { page: this.page, version: this.version })
311 }
312
313 // rebase is §6.5's clean merge: apply M, rebuild, check, move the base.
314 async rebase (against, merged, sent) {
315 if (this.deps.editor.current() !== sent) {
316 this.later('autosave', () => this.autosave(true), 0)
317 return
318 }
319 const tries = this.tries.get(against) ?? 0
320 if (tries >= RETRIES) return
321 const { ok } = this.deps.editor.apply(merged)
322 if (!ok) {
323 this.tries.set(against, tries + 1)
324 return
325 }
326 const body = this.deps.editor.current()
327 let reply
328 try {
329 reply = await this.deps.post(this.drafts,
330 { base: this.base, version: this.version, body, rebase: against })
331 } catch {
332 return
333 }
334 if (reply.status === 409) {
335 this.stale(reply.json)
336 return
337 }
338 if (reply.status !== 200) return
339 this.base = against
340 this.version = reply.json.version
341 this.saved = body
342 this.remember()
343 }
344
345 // stale is the 409 a newer draft from another tab answers: this tab
346 // shows that draft, offered, and never overwrites it (build note 31).
347 stale (reply) {
348 this.cancel('idle')
349 if (reply?.committed) {
350 this.recover()
351 return
352 }
353 if (this.landed(reply)) return
354 this.deps.editor.apply(reply.body)
355 this.version = reply.version
356 this.saved = this.deps.editor.current()
357 this.dirty = false
358 this.own = false
359 this.offered = true
360 this.forget()
361 this.deps.ui?.notice?.('newer', {})
362 this.status('saved')
363 }
364
365 // landed is a 409 whose newer draft is this tab's own autosave that
366 // never answered but was stored (review round 4): the tab takes its
367 // version and goes on, typing since included, instead of replacing
368 // the typing with it.
369 landed (reply) {
370 const sent = this.unacked
371 this.unacked = null
372 if (sent === null || reply?.body !== cleanBody(sent)) return false
373 this.version = reply.version
374 this.saved = sent
375 this.own = true
376 this.remember()
377 this.status('saved')
378 if (this.deps.editor.current() !== this.saved) this.later('autosave', () => this.autosave(), 0)
379 return true
380 }
381
382 // recover is a draft committed meanwhile: by this tab's own closing
383 // request as it went (build note 38), or by another tab. Nothing stops
384 // (review H1): what is typed from here is a new draft. When the page
385 // now holds exactly what the draft held, it starts from that revision;
386 // otherwise from the old base, and the server's merge keeps both
387 // sides. An offered draft, which this tab never typed into, shows the
388 // page as it now is.
389 async recover () {
390 const held = this.saved
391 let fresh = null
392 try { fresh = await this.deps.refetch?.() } catch {}
393 const page = fresh && !fresh.draft ? fresh : null
394 if (page && cleanBody(page.source) === held) this.base = page.base
395 this.version = '0'
396 this.forget()
397 this.offered = false
398 if (this.own) {
399 this.dirty = true
400 this.later('autosave', () => this.autosave(true), 0)
401 return
402 }
403 if (page && this.deps.editor.current() === held) {
404 this.deps.editor.apply(page.source)
405 this.base = page.base
406 this.saved = this.deps.editor.current()
407 }
408 this.deps.ui?.notice?.('committed', {})
409 }
410
411 // flush stores what is typed; false when it could not be stored.
412 async flush () {
413 this.cancel('autosave')
414 if (this.unsaved() || this.inflight) {
415 const stored = await this.autosave()
416 if (!stored || this.unsaved()) return false
417 }
418 return true
419 }
420
421 // commit commits the draft: the person's own, or any on Save
422 // (explicit). It answers what happened, for leaving.
423 async commit ({ explicit = false } = {}) {
424 if (this.stopped || (!this.own && !explicit)) return 'none'
425 if (this.orphan) return 'orphan'
426 if (this.conflict) return 'conflict'
427 this.cancel('idle')
428 if (!(await this.flush())) {
429 if (this.orphan) return 'orphan'
430 return this.own && !this.stopped ? 'flush-failed' : 'stale'
431 }
432 // The flush's own reply may have opened a choice or found the page
433 // deleted: then the text is stored, and nothing commits.
434 if (this.conflict) return 'conflict'
435 if (this.gone || this.holding) return this.gone ? 'gone' : 'held'
436 if (this.version === '0') return 'none'
437 const sent = this.saved
438 let reply
439 try {
440 reply = await this.deps.post(`${this.drafts}/save`, { version: this.version })
441 } catch {
442 return 'commit-failed'
443 }
444 if (reply.status === 409) {
445 this.stale(reply.json)
446 return 'stale'
447 }
448 if (reply.status !== 200) return 'commit-failed'
449 return this.committed(reply.json, sent)
450 }
451
452 // committed takes a commit's answer. Only a reply carrying a revision
453 // is a commit (review H2).
454 async committed (answer, sent) {
455 if (answer.empty) {
456 // An emptied day: the server dropped the draft and wrote nothing.
457 // The next text typed is a new draft.
458 this.version = '0'
459 this.forget()
460 this.offered = false
461 this.status('idle')
462 this.deps.ui?.committed?.({})
463 return 'empty'
464 }
465 if (answer.gone) {
466 this.lost()
467 return 'gone'
468 }
469 if (!answer.saved) {
470 if (/\/conflict$/u.test(answer.href ?? '')) {
471 await this.autosave(true)
472 return this.conflict ? 'conflict' : 'nobase'
473 }
474 // Kept: committed, but a newer draft of this person's stays; the
475 // autosave's 409 brings it here, offered.
476 await this.autosave(true)
477 return 'kept'
478 }
479 if (answer.revision === undefined) return 'commit-failed'
480 this.version = '0'
481 this.forget()
482 this.offered = false
483 this.status('saved')
484 // A day's first commit makes its page: Resolve and Make team page
485 // need its address.
486 const made = /^\/p\/([^/?#]+)/u.exec(answer.href ?? '')
487 if (made && !this.page) this.page = made[1]
488 if (answer.merged && this.deps.editor.current() === sent) {
489 this.deps.editor.apply(answer.body)
490 this.saved = this.deps.editor.current()
491 this.base = answer.revision
492 } else if (!answer.merged) {
493 this.base = answer.revision
494 }
495 this.deps.ui?.committed?.(answer)
496 return answer.merged ? 'merged' : 'saved'
497 }
498
499 // resolve posts the person's choice for each conflicting hunk, with
500 // the version whose reply carried them (§6.5, N3). Text typed since
501 // that reply is stored first, so Resolve commits from the text on
502 // screen, and the editor takes no typing until the answer is applied:
503 // the answer never lands over text it did not include (review M1).
504 async resolve (choices) {
505 if (!this.conflict || !this.page || this.resolving) return 'none'
506 this.resolving = true
507 try {
508 return await this.resolveNow(choices)
509 } finally {
510 this.resolving = false
511 }
512 }
513
514 async resolveNow (choices) {
515 const shown = this.conflict
516 if (this.deps.editor.current() !== shown.sent) {
517 if (!(await this.flush())) return 'failed'
518 // A different choice came back: it is on show, to choose again.
519 if (this.conflict?.hunks !== shown.hunks) return 'conflicted'
520 }
521 const conflict = this.conflict
522 const fields = { current: conflict.against, version: conflict.version, grammar: String(Grammar) }
523 choices.forEach((choice, index) => { fields[`choice-${index}`] = choice })
524 let reply
525 try {
526 reply = await this.deps.post(`/p/${this.page}/resolve`, fields)
527 } catch {
528 return 'failed'
529 }
530 if (reply.status !== 200) return 'failed'
531 const { outcome, revision, body } = reply.json
532 if ((outcome === 'saved' || outcome === 'merged') && this.deps.editor.current() === conflict.sent) {
533 this.settled()
534 this.deps.editor.apply(body)
535 this.saved = this.deps.editor.current()
536 this.base = revision
537 this.version = '0'
538 this.forget()
539 this.status('saved')
540 this.deps.ui?.committed?.(reply.json)
541 return 'saved'
542 }
543 if (outcome === 'noBase') {
544 this.deps.ui?.notice?.('noBase', { page: this.page })
545 return 'nobase'
546 }
547 await this.autosave(true)
548 return 'conflicted'
549 }
550
551 // took is a body the server wrote for this page and answered (Make
552 // team page's note): the editor shows it and takes its revision.
553 took (body, revision) {
554 this.deps.editor.apply(body)
555 this.saved = this.deps.editor.current()
556 this.base = revision
557 this.version = '0'
558 this.forget()
559 this.deps.ui?.committed?.({})
560 }
561
562 // renamed is a rename of this page, made over revision from, which
563 // minted to (title.mjs). A rename's revision holds exactly from's
564 // body, so a base of from is a base of to: the store moved the
565 // person's draft with it (carryDrafts), and this tab's base follows,
566 // so a draft it starts from here is not merged against a revision
567 // that changed nothing. Any other base stays; the merge settles it.
568 renamed (from, to) {
569 if (from && from !== '0' && to && this.base === from) this.base = to
570 }
571
572 // settled clears the inline choice.
573 settled () {
574 this.conflict = null
575 this.deps.ui?.conflict?.(null)
576 }
577
578 // leave is following a link inside Mapa (§6.5): commit first, then
579 // go; or stay, with the choice, when there is one to make.
580 async leave (href) {
581 if (!this.committable()) return this.deps.navigate(href)
582 const outcome = await this.commit()
583 if (outcome === 'conflict') {
584 this.deps.ui?.leaving?.('conflict', () => {
585 this.forget()
586 this.stopped = true
587 this.deps.navigate(href)
588 })
589 return
590 }
591 if (outcome === 'flush-failed' || outcome === 'orphan') {
592 this.deps.ui?.leaving?.(outcome === 'orphan' ? 'orphan' : 'failed', () => {
593 this.stopped = true
594 this.deps.navigate(href)
595 })
596 return
597 }
598 this.deps.navigate(href)
599 }
600
601 // settle is a page loaded while its draft was being committed by the
602 // page before (a reload, build note 38): it asks the server again, a
603 // GET, until the draft is gone or plainly stays, and takes what the
604 // page now holds as its base.
605 async settle (tries = 8, wait = 150) {
606 if (!this.closed) return
607 for (let round = 0; round < tries; round++) {
608 if (round > 0) await new Promise(resolve => (this.deps.timers ?? globalThis).setTimeout(resolve, wait))
609 let fresh = null
610 try { fresh = await this.deps.refetch?.() } catch {}
611 if (!fresh || fresh.draft?.version === this.version) continue
612 if (this.version !== this.loadedVersion) return
613 if (!fresh.draft) this.settled_(fresh)
614 else this.newer(fresh)
615 this.closed = false
616 return
617 }
618 this.closed = false
619 }
620
621 // settled_ is the draft found committed. When the page holds exactly
622 // its text, the tab goes on from that revision. Otherwise a merge put
623 // a teammate's text in too: what is typed from here is a new draft
624 // from the old base, as recover() does, so the server's merge keeps
625 // both, and a close sends version 0, never the committed version,
626 // which the store would refuse (review round 4, M-A).
627 settled_ (fresh) {
628 if (cleanBody(fresh.source) === this.saved) {
629 this.base = fresh.base
630 this.deps.ui?.committed?.({ settled: true })
631 }
632 this.version = '0'
633 this.forget()
634 }
635
636 // newer is a draft other than the one this page loaded, found while
637 // settling (another tab wrote it). With nothing typed here yet the tab
638 // shows it, offered, so typing goes on from it instead of being
639 // replaced by it at the next autosave's 409 (review round 4).
640 newer (fresh) {
641 if (this.unsaved()) return
642 this.deps.editor.apply(fresh.source)
643 this.saved = this.deps.editor.current()
644 this.version = fresh.draft.version
645 this.base = fresh.draft.base
646 this.own = false
647 this.offered = true
648 this.forget()
649 this.deps.ui?.notice?.('newer', {})
650 }
651
652 // closing is pagehide (D3): one keepalive POST, with commit=1, the
653 // tab's draft version and any text not yet sent; past the keepalive
654 // cap it carries no text and commits the last autosave. While commits
655 // are held (a choice open, a page deleted, Show the saved version),
656 // the text not yet sent is still written, as the draft only (review
657 // M2). The text is the structure check's, as autosave's is.
658 closing ({ reloading = false } = {}) {
659 if (this.stopped) return
660 if (this.token) return this.closingFirst()
661 const body = this.deps.editor.prepare()
662 if (this.orphan) return this.closingOrphan(body)
663 const unsent = body !== this.saved
664 if (!this.mayCommit()) {
665 if (unsent && this.own && byteLength(body) <= KEEPALIVE_CAP) this.keep(body)
666 return
667 }
668 if (!this.committable()) return
669 // A reload is not a close: a draft already stored stays this tab's
670 // own, and the page it loads offers it to no one but this tab.
671 if (reloading && !unsent && !this.dirty) return
672 const fields = { commit: '1', version: this.version, base: this.base }
673 if (unsent && byteLength(body) <= KEEPALIVE_CAP) fields.body = body
674 // Still settling: the version the page showed may be committed
675 // already, or not; settling=1 asks the store to take either, so the
676 // text is written whichever it was (build note 38, review M3).
677 if (this.closed && this.version === this.loadedVersion) fields.settling = '1'
678 if (fields.body === undefined && this.version === '0') return
679 try { this.deps.storage?.set(`mapa-closing:${this.drafts}`, this.version) } catch {}
680 this.deps.post(this.drafts, fields, { keepalive: true }).catch(() => {})
681 this.cancel('autosave')
682 this.cancel('idle')
683 this.dirty = false
684 this.saved = body
685 this.version = '0'
686 this.forget()
687 }
688
689 // closingFirst is a new scratch page closing before its first commit
690 // was answered: the text goes with the token, as autosave's would.
691 closingFirst () {
692 if (!this.committable()) return
693 const body = this.deps.editor.prepare()
694 if (goTrimSpace(body) !== '' && byteLength(body) <= KEEPALIVE_CAP) {
695 this.deps.post('/scratch', { first: this.token, version: this.version, body },
696 { keepalive: true }).catch(() => {})
697 }
698 this.dirty = false
699 }
700
701 // closingOrphan keeps what was typed on a page deleted before any of
702 // it was stored: one keepalive POST /scratch makes it a scratch page
703 // of the person's own, as the bar's button would have.
704 closingOrphan (body) {
705 if (!this.own || goTrimSpace(body) === '' || byteLength(body) > KEEPALIVE_CAP) return
706 this.deps.post('/scratch', { body }, { keepalive: true }).catch(() => {})
707 this.stopped = true
708 }
709
710 // keep writes the text as the draft only, on the way out.
711 keep (body) {
712 this.deps.post(this.drafts, { base: this.base, version: this.version, body },
713 { keepalive: true }).catch(() => {})
714 this.cancel('autosave')
715 this.cancel('idle')
716 this.dirty = false
717 this.saved = body
718 }
719
720 // shown is pageshow from the back/forward cache: with nothing
721 // unsaved, the page is loaded again; otherwise autosave at once.
722 shown () {
723 if (this.unsaved()) {
724 this.autosave(true)
725 return
726 }
727 this.deps.reload?.()
728 }
729}
730
731// sameHunks is whether a reply's conflict is the one on show: the same
732// revision and the same three sides of every hunk.
733function sameHunks (conflict, merge) {
734 if (conflict.against !== merge.against || conflict.hunks.length !== merge.hunks.length) return false
735 return conflict.hunks.every((hunk, index) => {
736 const other = merge.hunks[index]
737 return hunk.base === other.base && hunk.mine === other.mine && hunk.theirs === other.theirs
738 })
739}
740
741function byteLength (text) {
742 return new TextEncoder().encode(text).length
743}
744