// The shared draft's editor (phase 13), on our page and on a party's link. // The text is a list of pieces {k, t, c, s}: "same" (agreed text), "ins" // (added by side s), "del" (crossed out by side s) and "mark" (highlighted // by side s, c = its comment). Edits work on that list and redraw, so no // side can change the text as it stands or another side's marks; the // server checks the same rule (reviews::check_save). One side edits at a // time: Edit takes the draft for a while that each save renews; the others // see the saves within seconds, as the page asks for news every 3 seconds. // No inline script: the Content Security Policy allows none. (function () { "use strict"; var root = document.querySelector("[data-draft]"); if (!root) return; var data = JSON.parse(document.getElementById("dr-data").textContent); var base = data.base; var csrf = data.csrf; var ed = document.getElementById("dr-text"); var $ = function (id) { return document.getElementById(id); }; var state = data.state; var me = state.me; var rev = state.rev; var pieces = []; var editing = false; var dirty = false; var saving = false; var lastSave = 0; var history = []; var lastSel = null; var sides = {}; var saveTimer = null; // ---- talking to the server function post(action, fields) { var body = new URLSearchParams(); body.set("csrf", csrf); body.set("rev", String(rev)); // a save makes the next revision, whose pieces the editor has body.set("have", String(action === "save" ? rev + 1 : rev)); Object.keys(fields || {}).forEach(function (k) { body.set(k, fields[k]); }); return fetch(base + "/" + action, { method: "POST", credentials: "same-origin", headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, body: body.toString(), }).then(function (r) { return r .json() .catch(function () { return { ok: false, error: "The server did not answer properly. Reload the page." }; }) .then(function (j) { if (j.state) take(j.state, !j.ok); if (!j.ok && j.error) say(j.error); return j; }); }); } function poll() { if (document.hidden) return; fetch(base + "/state?rev=" + rev, { credentials: "same-origin", headers: { accept: "application/json" } }) .then(function (r) { return r.ok ? r.json() : null; }) .then(function (s) { if (s) take(s, false); }) .catch(function () {}); } // A state from the server: the pieces replace ours unless we are the // editor with our own edits, or `force` (a refused change). function take(s, force) { state = s; sides = {}; (s.sides || []).forEach(function (x) { sides[x.side] = x; }); if (s.pieces && (!editing || force)) { pieces = s.pieces.map(function (p) { return { k: p[0], t: p[1], c: p[2] || "", s: p[3] || "" }; }); dirty = false; draw(null); } // only one side edits: the server's revision is always the one to // build on, also with edits of ours not saved yet rev = s.rev; if (editing && !(s.editor && s.editor.mine)) { stopEditing(); say("Your editing time ran out, or someone else took the draft. Press Edit to go on."); } panels(); } // ---- drawing function color(side) { return sides[side] ? sides[side].color : 5; } function nameOf(side) { return sides[side] ? sides[side].name : "a former party"; } // which change each piece belongs to, as the server counts them function changeOf() { var n = 0, open = null; return pieces.map(function (p) { if (p.k === "ins" || p.k === "del") { if (open !== p.s) { n++; open = p.s; } return n; } open = null; return 0; }); } function draw(caret) { var top = ed.scrollTop; var of = changeOf(); var markNo = 0; ed.textContent = ""; pieces.forEach(function (p, i) { var tag = p.k === "ins" ? "ins" : p.k === "del" ? "del" : p.k === "mark" ? "mark" : "span"; var el = document.createElement(tag); el.textContent = p.t; el.setAttribute("data-i", i); if (p.k !== "same") { el.className = "w" + color(p.s); el.title = (p.k === "ins" ? "Added by " : p.k === "del" ? "Crossed out by " : "Highlighted by ") + nameOf(p.s) + (p.c ? ": " + p.c : ""); } if (of[i] && (i === 0 || of[i - 1] !== of[i])) el.setAttribute("data-ch", of[i]); if (p.k === "mark") el.setAttribute("data-mk", ++markNo); ed.appendChild(el); }); var last = pieces[pieces.length - 1]; if (!last || last.t.charAt(last.t.length - 1) === "\n") ed.appendChild(document.createElement("br")); ed.scrollTop = top; if (caret != null) place(caret); } function short(t, n) { t = t.replace(/\s+/g, " ").trim(); return t.length > n ? t.slice(0, n) + "…" : t; } function li(cls) { var el = document.createElement("li"); if (cls) el.className = cls; return el; } function button(label, cls, fn) { var b = document.createElement("button"); b.type = "button"; b.className = "btn sm " + (cls || ""); b.textContent = label; b.addEventListener("click", fn); return b; } function dot(side) { var d = document.createElement("span"); d.className = "drdot w" + color(side); d.setAttribute("aria-hidden", "true"); return d; } function panels() { var locked = state.state === "locked"; var other = state.editor && !state.editor.mine; // the bar var text; if (locked) { text = "Locked: every side agreed. The text is version " + state.locked_version + " and never changes."; } else if (editing) { text = saving || dirty ? "You are editing. Saving…" : "You are editing. Every change is saved."; } else if (other) { text = state.editor.name + " is editing. Their changes show here as they save."; } else { text = "Open for edits. Last change " + state.changed + "."; } $("dr-state").textContent = text; $("dr-edit").hidden = locked || editing; $("dr-edit").disabled = !!other; $("dr-done").hidden = !editing; $("dr-tools").hidden = !editing; ed.contentEditable = editing ? "true" : "false"; ed.classList.toggle("on", editing); // the changes var list = $("dr-changes"); list.textContent = ""; var ch = []; var of = changeOf(); pieces.forEach(function (p, i) { if (!of[i]) return; var c = ch[of[i] - 1]; if (!c) c = ch[of[i] - 1] = { n: of[i], s: p.s, removed: "", added: "" }; if (p.k === "del") c.removed += p.t; else c.added += p.t; }); ch.forEach(function (c) { var el = li(); el.appendChild(dot(c.s)); var what = document.createElement("span"); what.className = "drwhat"; var who = document.createElement("b"); who.textContent = c.n + ". " + nameOf(c.s) + " "; what.appendChild(who); if (c.removed) { var d = document.createElement("del"); d.textContent = short(c.removed, 60); what.appendChild(d); } if (c.added) { var a = document.createElement("ins"); a.textContent = short(c.added, 60); what.appendChild(a); } what.addEventListener("click", function () { show("[data-ch='" + c.n + "']"); }); el.appendChild(what); if (!locked) { var acts = document.createElement("span"); acts.className = "dracts"; if (c.s !== me) { acts.appendChild(button("Accept", "pri", function () { settle("accept", c.n); })); acts.appendChild(button("Reject", "ghost", function () { settle("reject", c.n); })); } else { acts.appendChild(button("Withdraw", "ghost", function () { settle("reject", c.n); })); } el.appendChild(acts); } list.appendChild(el); }); $("dr-changes-n").textContent = ch.length ? "(" + ch.length + ")" : ""; if (!ch.length) { var none = li("muted"); none.textContent = "None: the text stands as it is."; list.appendChild(none); } // the highlights var marks = $("dr-marks"); marks.textContent = ""; var k = 0; pieces.forEach(function (p) { if (p.k !== "mark") return; var n = ++k; var el = li(); el.appendChild(dot(p.s)); var what = document.createElement("span"); what.className = "drwhat"; var m = document.createElement("mark"); m.textContent = short(p.t, 50); what.appendChild(m); var c = document.createElement("span"); c.className = "sub"; c.textContent = nameOf(p.s) + (p.c ? ": " + p.c : ""); what.appendChild(c); what.addEventListener("click", function () { show("[data-mk='" + n + "']"); }); el.appendChild(what); if (!locked) { var acts = document.createElement("span"); acts.className = "dracts"; acts.appendChild(button("Resolve", "ghost", function () { act("resolve", { k: String(n) }); })); el.appendChild(acts); } marks.appendChild(el); }); $("dr-marks-n").textContent = k ? "(" + k + ")" : ""; $("dr-marks-box").hidden = !k; // the sides and their agreement var sl = $("dr-sides"); sl.textContent = ""; var legend = $("dr-legend"); legend.textContent = ""; (state.sides || []).forEach(function (x) { var el = li(x.agreed ? "ok" : ""); el.appendChild(dot(x.side)); var t = document.createElement("span"); t.textContent = x.name + (x.side === me ? " (you)" : "") + ": " + (x.agreed ? "agreed, " + x.by + ", " + x.at : "not agreed yet"); el.appendChild(t); sl.appendChild(el); var lg = li(); lg.appendChild(dot(x.side)); lg.appendChild(document.createTextNode(x.name)); legend.appendChild(lg); }); var mine = sides[me] && sides[me].agreed; var agree = $("dr-agree"); agree.disabled = locked || ch.length > 0 || k > 0 || mine || !!other || dirty; $("dr-agree-form").hidden = locked; $("dr-agree-note").textContent = locked ? "" : ch.length || k ? "Accept or reject the open changes and resolve the highlights first: you agree to the text as it stands." : mine ? "You agree to this text. A new change would ask everyone again." : state.have + " of " + state.need + " sides agree. When all do, the text locks as a contract version."; } function show(sel) { var el = ed.querySelector(sel); if (!el) return; el.scrollIntoView({ block: "center", behavior: "smooth" }); el.classList.add("flash"); setTimeout(function () { el.classList.remove("flash"); }, 1200); } function say(t) { $("dr-note").textContent = t || ""; } // ---- caret positions as offsets into the whole text function lenOf(el) { return el.nodeType === 1 && el.hasAttribute("data-i") ? el.textContent.length : 0; } function offsetOf(node, off) { var n = 0, x; if (node === ed) { x = ed.firstChild; for (var i = 0; x && i < off; i++, x = x.nextSibling) n += lenOf(x); return n; } var el = node.nodeType === 3 ? node.parentNode : node; while (el && el.parentNode !== ed) el = el.parentNode; if (!el) return null; for (x = ed.firstChild; x && x !== el; x = x.nextSibling) n += lenOf(x); if (node.nodeType === 3) return n + off; return n + (off > 0 ? lenOf(el) : 0); } function current() { var s = window.getSelection(); if (!s || !s.rangeCount) return null; var r = s.getRangeAt(0); if (!ed.contains(r.startContainer) || !ed.contains(r.endContainer)) return null; var a = offsetOf(r.startContainer, r.startOffset); var b = offsetOf(r.endContainer, r.endOffset); if (a == null || b == null) return null; return { s: Math.min(a, b), e: Math.max(a, b) }; } function place(pos) { var acc = 0, s = window.getSelection(), r = document.createRange(); for (var x = ed.firstChild; x; x = x.nextSibling) { var len = lenOf(x); if (len && pos <= acc + len) { r.setStart(x.firstChild, pos - acc); r.collapse(true); s.removeAllRanges(); s.addRange(r); lastSel = { s: pos, e: pos }; return; } acc += len; } r.selectNodeContents(ed); r.collapse(false); s.removeAllRanges(); s.addRange(r); lastSel = { s: acc, e: acc }; } // ---- the edits, on a flat form: one entry per UTF-16 unit function flat() { var f = { t: [], k: [], c: [], a: [] }; pieces.forEach(function (p) { for (var i = 0; i < p.t.length; i++) { f.t.push(p.t[i]); f.k.push(p.k); f.c.push(p.c); f.a.push(p.s); } }); return f; } function build(f) { var res = []; for (var i = 0; i < f.t.length; i++) { var l = res[res.length - 1]; if (l && l.k === f.k[i] && l.c === f.c[i] && l.s === f.a[i]) l.t += f.t[i]; else res.push({ k: f.k[i], t: f.t[i], c: f.c[i], s: f.a[i] }); } pieces = res; } // what this side may not touch: anything crossed out, and the other // sides' additions and highlights function fixed(f, i) { return f.k[i] === "del" || (f.k[i] !== "same" && f.a[i] !== me); } function changed() { dirty = true; clearTimeout(saveTimer); saveTimer = setTimeout(save, 700); panels(); } function remember() { history.push(JSON.stringify(pieces)); if (history.length > 300) history.shift(); } // crosses [s, e) out; returns how many units of it stay function crossOut(f, s, e) { var out = { t: [], k: [], c: [], a: [] }, kept = 0, blocked = 0; for (var i = 0; i < f.t.length; i++) { var inside = i >= s && i < e; if (inside && f.k[i] === "ins" && f.a[i] === me) continue; out.t.push(f.t[i]); if (inside) kept++; if (inside && !fixed(f, i)) { out.k.push("del"); out.c.push(""); out.a.push(me); } else { if (inside && f.k[i] !== "del") blocked++; out.k.push(f.k[i]); out.c.push(f.c[i]); out.a.push(f.a[i]); } } f.t = out.t; f.k = out.k; f.c = out.c; f.a = out.a; if (blocked) say("Another side's additions and highlights stay: accept, reject or resolve them in the list."); return kept; } function insert(f, p, text) { // never inside another side's addition: after it while (p > 0 && p < f.t.length && f.k[p] === "ins" && f.a[p] !== me && f.k[p - 1] === "ins" && f.a[p - 1] === f.a[p]) p++; // what is crossed out comes first, then what replaces it while (p < f.t.length && f.k[p] === "del") p++; var u = text.split(""); var fill = function (v) { return u.map(function () { return v; }); }; f.t.splice.apply(f.t, [p, 0].concat(u)); f.k.splice.apply(f.k, [p, 0].concat(fill("ins"))); f.c.splice.apply(f.c, [p, 0].concat(fill(""))); f.a.splice.apply(f.a, [p, 0].concat(fill(me))); return p + u.length; } function isLow(ch) { var n = ch ? ch.charCodeAt(0) : 0; return n >= 0xdc00 && n <= 0xdfff; } function type(r, text) { text = text.replace(/\r\n?/g, "\n"); remember(); var f = flat(); var p = r.s; if (r.e > r.s) p = r.s + crossOut(f, r.s, r.e); var end = insert(f, p, text); build(f); draw(end); changed(); } function strike(r, atEnd) { remember(); var f = flat(); var kept = crossOut(f, r.s, r.e); build(f); draw(atEnd ? r.s + kept : r.s); changed(); } function back(p, unit) { var f = flat(); while (p > 0 && fixed(f, p - 1)) p--; if (p === 0) return place(p); var a = p - 1; if (unit === "char") { if (a > 0 && isLow(f.t[a])) a--; } else if (unit === "word") { while (a > 0 && /\s/.test(f.t[a])) a--; while (a > 0 && !/\s/.test(f.t[a - 1]) && !fixed(f, a - 1)) a--; } else { while (a > 0 && f.t[a - 1] !== "\n") a--; } strike({ s: a, e: p }, false); } function forward(p, unit) { var f = flat(), n = f.t.length; while (p < n && fixed(f, p)) p++; if (p === n) return place(p); var b = p + 1; if (unit === "char") { if (b < n && isLow(f.t[b])) b++; } else if (unit === "word") { while (b < n && /\s/.test(f.t[b])) b++; while (b < n && !/\s/.test(f.t[b]) && !fixed(f, b)) b++; } else { while (b < n && f.t[b] !== "\n") b++; } strike({ s: p, e: b }, true); } function highlight(r) { if (!r || r.s === r.e) return say("Select the words to highlight first."); var comment = ($("dr-comment").value || "").trim().slice(0, 500); remember(); var f = flat(); for (var i = r.s; i < r.e; i++) { if (f.k[i] === "same" || (f.k[i] === "mark" && f.a[i] === me)) { f.k[i] = "mark"; f.c[i] = comment; f.a[i] = me; } } build(f); $("dr-comment").value = ""; draw(r.e); changed(); } function restore(r) { if (!r) return; var f = flat(); var s = r.s, e = r.e; var own = function (i) { return f.k[i] !== undefined && f.k[i] !== "same" && f.a[i] === me; }; if (s === e) { var at = own(s) ? s : own(s - 1) ? s - 1 : -1; if (at < 0) return say("Select what to restore, or put the caret in one of your own marks."); var kind = f.k[at]; s = at; e = at; while (s > 0 && own(s - 1) && f.k[s - 1] === kind) s--; while (e < f.t.length && own(e) && f.k[e] === kind) e++; } remember(); var out = { t: [], k: [], c: [], a: [] }; for (var i = 0; i < f.t.length; i++) { var mine = i >= s && i < e && own(i); if (mine && f.k[i] === "ins") continue; out.t.push(f.t[i]); out.k.push(mine ? "same" : f.k[i]); out.c.push(mine ? "" : f.c[i]); out.a.push(mine ? "" : f.a[i]); } build(out); draw(s); changed(); } function undo() { if (!history.length) return say("Nothing to undo."); var caret = current(); pieces = JSON.parse(history.pop()); draw(caret ? caret.s : null); changed(); } // what the browser changed itself (a keyboard's composition), taken as // an edit function resync() { var mine = pieces.map(function (p) { return p.t; }).join(""); var now = ed.textContent; if (mine === now) return; var a = 0; while (a < mine.length && a < now.length && mine[a] === now[a]) a++; var b = 0; while (b < mine.length - a && b < now.length - a && mine[mine.length - 1 - b] === now[now.length - 1 - b]) b++; var added = now.slice(a, now.length - b); remember(); var f = flat(); var p = a + crossOut(f, a, mine.length - b); var end = added ? insert(f, p, added) : p; build(f); draw(end); changed(); } // ---- editing: take, save, give up function save() { if (!editing || !dirty) return Promise.resolve(); if (saving) { clearTimeout(saveTimer); saveTimer = setTimeout(save, 400); return Promise.resolve(); } saving = true; dirty = false; panels(); var json = JSON.stringify(pieces.map(function (p) { return [p.k, p.t, p.c, p.s]; })); return post("save", { pieces: json }) .then(function (j) { saving = false; lastSave = Date.now(); if (!j.ok) stopEditing(); panels(); }) .catch(function () { saving = false; dirty = true; say("Not saved: the connection dropped. It tries again in a moment."); saveTimer = setTimeout(save, 3000); }); } function startEditing() { post("take").then(function (j) { if (!j.ok) return; editing = true; lastSave = Date.now(); say(""); panels(); ed.focus(); }); } function stopEditing() { editing = false; dirty = false; clearTimeout(saveTimer); panels(); } function done() { save().then(function () { // not editing any more before the answer comes, which shows nobody // editing stopEditing(); post("release"); }); } function act(action, fields) { var go = function () { return post(action, fields).then(function (j) { if (j.ok) say(""); }); }; if (editing && dirty) save().then(go); else go(); } function settle(action, n) { act(action, { n: String(n) }); } // ---- events ed.addEventListener("beforeinput", function (ev) { if (!editing) return ev.preventDefault(); var t = ev.inputType || ""; if (t === "insertCompositionText") return; ev.preventDefault(); var r = current(); if (!r) return; if (t === "historyUndo") return undo(); if (t.indexOf("insert") === 0) { var text = ev.data; if (t === "insertParagraph" || t === "insertLineBreak") text = "\n"; if (text == null && ev.dataTransfer) text = ev.dataTransfer.getData("text/plain"); if (t === "insertFromDrop" || !text) return; if (t === "insertReplacementText" && ev.getTargetRanges) { var tr = ev.getTargetRanges()[0]; if (tr) { var s = offsetOf(tr.startContainer, tr.startOffset); var e = offsetOf(tr.endContainer, tr.endOffset); if (s != null && e != null) r = { s: s, e: e }; } } return type(r, text); } if (t.indexOf("delete") === 0 && t !== "deleteByDrag") { if (r.e > r.s) return strike(r, false); var unit = /Word/.test(t) ? "word" : /Line/.test(t) ? "line" : "char"; if (/Backward/.test(t)) back(r.s, unit); else forward(r.s, unit); } }); ed.addEventListener("input", function (ev) { if (editing && !ev.isComposing) resync(); }); ed.addEventListener("compositionend", function () { setTimeout(resync, 0); }); ed.addEventListener("drop", function (ev) { ev.preventDefault(); }); ed.addEventListener("keydown", function (ev) { if ((ev.ctrlKey || ev.metaKey) && !ev.shiftKey && (ev.key === "z" || ev.key === "Z")) { ev.preventDefault(); if (editing) undo(); } }); document.addEventListener("selectionchange", function () { var r = current(); if (r) lastSel = r; }); root.addEventListener("click", function (ev) { var b = ev.target.closest && ev.target.closest("[data-rv]"); if (!b || !editing) return; var what = b.getAttribute("data-rv"); var r = current() || lastSel; if (what === "undo") return undo(); if (!r) return say("Put the caret in the text, or select a part of it, first."); if (what === "del") { if (r.s === r.e) return say("Select the words to cross out first."); strike(r, false); } else if (what === "mark") highlight(r); else if (what === "restore") restore(r); ed.focus(); }); $("dr-edit").addEventListener("click", startEditing); $("dr-done").addEventListener("click", done); $("dr-agree").addEventListener("click", function () { var nameBox = $("dr-name"); var name = nameBox ? nameBox.value.trim() : "staff"; if (!name) { nameBox.focus(); return say("Write your name: it goes with your agreement."); } try { if (nameBox) localStorage.setItem("draft-name", name); } catch (e) { /* storage blocked */ } if (!window.confirm("Agree to the text as it stands now? When every side has agreed, it locks.")) return; act("agree", { name: name }); }); if ($("dr-name")) { try { $("dr-name").value = localStorage.getItem("draft-name") || ""; } catch (e) { /* storage blocked */ } } window.addEventListener("pagehide", function () { if (!editing) return; var body = new URLSearchParams(); body.set("csrf", csrf); if (dirty) { body.set("rev", String(rev)); body.set("pieces", JSON.stringify(pieces.map(function (p) { return [p.k, p.t, p.c, p.s]; }))); navigator.sendBeacon(base + "/save", body); } var rel = new URLSearchParams(); rel.set("csrf", csrf); navigator.sendBeacon(base + "/release", rel); }); window.addEventListener("beforeunload", function (ev) { if (dirty || saving) { ev.preventDefault(); ev.returnValue = ""; } }); // news every 3 seconds; while editing, a sign of life keeps the draft setInterval(function () { if (editing) { if (!dirty && !saving && Date.now() - lastSave > 20000) { lastSave = Date.now(); post("take"); } } else { poll(); } }, 3000); document.addEventListener("visibilitychange", function () { if (!document.hidden && !editing) poll(); }); take(state, true); })();