One shared draft a contract, locked when all agree (phase 13, step 2)
CI / secret scan (push) Successful in 6s
CI / fmt, clippy, tests (push) Successful in 1m27s
CI / release (push) Skipped

Until a contract is set, it is one open text for every side, as Alex
asked: our team edits it in the app, each other party on its link. Edits
are tracked changes in the author's color (crossed out, added,
highlighted with a comment) until the other side accepts or rejects
them. When no change or highlight is open and Lanna Desk and every party
agree, the text becomes a contract version that never changes, and the
draft locks.

- One side edits at a time: Edit takes the draft for 45 seconds, which
  every save renews; Done editing, leaving the page or silence gives it
  up. The editor saves 0.7 s after the last keystroke; the other pages
  ask for news every 3 s, so each side sees edits, who edits, agreements
  and the lock without reloading.
- A save may only touch the saver's own marks (reviews::check_save);
  accept, reject (or withdraw) and resolve are their own steps, journaled
  with the text concerned. A later change voids the agreements given.
- Notices: the other side's edits (one a half hour of editing), settled
  changes, agreements, the lock. The bell in the top bar counts the
  unseen (every 15 s); Notices lists them and marks them seen.
- The draft as a diff: the standing text against every open change taken.
- Migration 0015: contract_drafts, draft_saves and draft_agreements (both
  kept unchanged by a trigger), notices, notice_reads; drops step 1's
  review_rounds (only the demo held any). The review links stay as each
  party's way in.
- Property tests for the save rule and settling, the fuzz text target
  runs the parser, the save check and settling; integration tests play
  both sides to the lock. The demo's recording agreement has an open
  draft with the label's changes and a notice.
- PLAN: phase 13 rewritten; step 3 is the PDF and signing.
This commit is contained in:
grabowski committed 2026-11-23 16:14:14 +07:00
1 parent a4155548b8
commit 3dd9ab60e8
36 files changed
+3812 -2161

No files matched your search

+225
View File
@@ -2380,3 +2380,228 @@ details.move[open] .mini {
grid-template-columns: 2.4em 2.4em 1fr;
}
}
/* ---- phase 13 step 2: the bell and the shared draft */
.topacts {
display: flex;
align-items: center;
gap: 8px;
}
.ib.bell {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
text-decoration: none;
}
.ib.bell.has {
border-color: var(--label);
}
.bellcount {
position: absolute;
top: -6px;
right: -7px;
min-width: 18px;
height: 18px;
padding: 0 5px;
border-radius: 9px;
font: 700 11px/18px var(--sans);
text-align: center;
color: #fff;
background: var(--bad);
}
.notices {
list-style: none;
margin: 0;
padding: 0;
}
.notices li {
display: flex;
flex-wrap: wrap;
gap: 4px 10px;
align-items: baseline;
padding: 10px 16px;
border-bottom: 1px solid var(--line);
}
.notices li:last-child {
border-bottom: 0;
}
.notices li.new {
background: var(--accent-s);
}
.notices li a {
flex: 1 1 260px;
}
.minihead {
font-size: 13px;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--label);
margin: 14px 0 6px;
}
/* the sides' colors: Lanna Desk first */
.w0 { --who: #2563c9; }
.w1 { --who: #8b3fd9; }
.w2 { --who: #0e8a7e; }
.w3 { --who: #c2570c; }
.w4 { --who: #b3245f; }
.w5 { --who: #6b7280; }
:root[data-theme="dark"] .w0 { --who: #7aa7ff; }
:root[data-theme="dark"] .w1 { --who: #c39bff; }
:root[data-theme="dark"] .w2 { --who: #4fd1c0; }
:root[data-theme="dark"] .w3 { --who: #ffa55c; }
:root[data-theme="dark"] .w4 { --who: #ff7ab0; }
:root[data-theme="dark"] .w5 { --who: #a5adba; }
.dr ins {
text-decoration: none;
color: var(--who);
background: color-mix(in srgb, var(--who) 13%, transparent);
border-bottom: 2px solid var(--who);
}
.dr del {
color: color-mix(in srgb, var(--who) 80%, var(--fg));
background: color-mix(in srgb, var(--who) 9%, transparent);
text-decoration: line-through 2px var(--who);
}
.dr mark {
color: inherit;
background: color-mix(in srgb, #f5c000 38%, transparent);
border-bottom: 2px dotted var(--who);
}
.dr del + ins {
margin-left: 2px;
}
/* the party's page of the draft takes the width the editor needs */
.cmain:has(#draft-editor) {
max-width: 1240px;
}
.dr .flash {
outline: 3px solid var(--accent);
outline-offset: 2px;
}
.drwrap .rvedit:not(.on) {
cursor: default;
caret-color: transparent;
}
.drwrap .rvedit.on {
border-color: var(--label);
}
.drbar {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
align-items: center;
justify-content: space-between;
padding: 10px 12px;
margin-bottom: 10px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--panel);
}
.drstate {
font-weight: 600;
}
.drbtns {
display: flex;
gap: 8px;
}
.drcols {
display: grid;
grid-template-columns: minmax(0, 1fr) 320px;
gap: 18px;
align-items: start;
}
.drside {
position: sticky;
top: calc(var(--toph) + 12px);
max-height: calc(100vh - var(--toph) - 24px);
overflow-y: auto;
}
.drside .minihead:first-child {
margin-top: 0;
}
.drlist,
.drsides,
.drlegend {
list-style: none;
margin: 0;
padding: 0;
}
.drlist li,
.drsides li {
display: flex;
gap: 8px;
align-items: baseline;
padding: 7px 0;
border-bottom: 1px dashed var(--line);
font-size: 14px;
}
.drwhat {
flex: 1;
min-width: 0;
cursor: pointer;
overflow-wrap: anywhere;
}
.drwhat del {
color: var(--bad);
margin-right: 4px;
}
.drwhat ins {
color: var(--ok);
text-decoration: none;
border-bottom: 1px solid var(--ok);
}
.drwhat mark {
color: inherit;
background: color-mix(in srgb, #f5c000 38%, transparent);
}
.drwhat .sub {
display: block;
}
.dracts {
display: flex;
gap: 4px;
flex: none;
}
.drdot {
flex: none;
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--who);
transform: translateY(1px);
}
.drsides li.ok {
color: var(--ok);
}
.drlegend {
display: flex;
flex-wrap: wrap;
gap: 6px 14px;
margin-top: 6px;
font-size: 13px;
color: var(--mute);
}
.drlegend li {
display: flex;
gap: 6px;
align-items: baseline;
}
.drname {
display: grid;
gap: 4px;
margin: 10px 0 8px;
font-size: 13px;
}
#dr-agree {
margin-top: 10px;
}
@media (max-width: 1000px) {
.drcols {
grid-template-columns: 1fr;
}
.drside {
position: static;
max-height: none;
}
}
+27
View File
@@ -192,6 +192,33 @@
});
document.addEventListener("DOMContentLoaded", applyShownWhen);
// ---- the bell: how many notices this staff member has not seen, asked
// for now and every 15 seconds while the page is open
function bell() {
var count = document.getElementById("bell-count");
if (!count || !window.fetch) return;
fetch("/notices/count", { credentials: "same-origin", headers: { accept: "application/json" } })
.then(function (r) {
return r.ok ? r.json() : null;
})
.then(function (j) {
if (!j) return;
count.hidden = !j.unread;
count.textContent = j.unread > 99 ? "99+" : String(j.unread);
var b = document.getElementById("bell");
b.setAttribute("aria-label", j.unread ? "Notices, " + j.unread + " new" : "Notices");
b.classList.toggle("has", j.unread > 0);
})
.catch(function () {
/* offline for a moment: the next try tells */
});
}
document.addEventListener("DOMContentLoaded", function () {
if (!document.getElementById("bell-count")) return;
bell();
setInterval(bell, 15000);
});
// a label's Print button
document.querySelectorAll("[data-print]").forEach(function (b) {
b.addEventListener("click", function () {
+809
View File
@@ -0,0 +1,809 @@
// 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);
})();
-452
View File
@@ -1,452 +0,0 @@
// The review editor (phase 13): the other side marks a contract version up.
// The text is a list of pieces {k, t, c}: "same" (ours, unchanged), "ins"
// (typed by them), "del" (ours, crossed out) and "mark" (ours, highlighted,
// c = its comment). Every edit works on that list and redraws the editor,
// so nothing of ours can vanish: deleting our text crosses it out, deleting
// their own typing removes it. The server checks the same rule
// (`reviews::check`). No inline script: the Content Security Policy allows
// none.
(function () {
"use strict";
var ed = document.querySelector("[data-rv-editor]");
if (!ed) return;
var form = ed.closest("form");
var out = document.getElementById("rv-pieces");
var count = document.getElementById("rv-count");
var note = document.getElementById("rv-note");
var commentBox = document.getElementById("rv-comment");
var pieces = JSON.parse(document.getElementById("rv-data").textContent).map(function (p) {
return { k: p[0], t: p[1], c: p[2] || "" };
});
var history = [];
var lastSel = null;
var dirty = false;
var sending = false;
// ---- the flat form: one entry per UTF-16 unit, for the edits
function flat() {
var t = [], k = [], c = [];
pieces.forEach(function (p) {
for (var i = 0; i < p.t.length; i++) {
t.push(p.t[i]);
k.push(p.k);
c.push(p.c);
}
});
return { t: t, k: k, c: c };
}
function build(f) {
var res = [];
for (var i = 0; i < f.t.length; i++) {
var last = res[res.length - 1];
if (last && last.k === f.k[i] && last.c === f.c[i]) {
last.t += f.t[i];
} else {
res.push({ k: f.k[i], t: f.t[i], c: f.c[i] });
}
}
pieces = res;
}
function remember() {
history.push(JSON.stringify(pieces));
if (history.length > 300) history.shift();
dirty = true;
}
// ---- drawing, and caret positions as offsets into the whole text
function draw(caret) {
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.c) el.title = p.c;
ed.appendChild(el);
});
// a last empty line shows only with something after it
var last = pieces[pieces.length - 1];
if (!last || last.t.charAt(last.t.length - 1) === "\n") {
ed.appendChild(document.createElement("br"));
}
out.value = JSON.stringify(
pieces.map(function (p) {
return [p.k, p.t, p.c];
})
);
tell();
if (caret != null) place(caret);
}
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;
var s = window.getSelection();
var 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
// Crosses [s, e) out; returns how many units of it stay (theirs go).
function crossOut(f, s, e) {
var t = [], k = [], c = [], kept = 0;
for (var i = 0; i < f.t.length; i++) {
if (i >= s && i < e) {
if (f.k[i] === "ins") continue;
kept++;
t.push(f.t[i]);
k.push("del");
c.push("");
} else {
t.push(f.t[i]);
k.push(f.k[i]);
c.push(f.c[i]);
}
}
f.t = t;
f.k = k;
f.c = c;
return kept;
}
function insert(f, p, text) {
var units = text.split("");
var ks = units.map(function () {
return "ins";
});
var cs = units.map(function () {
return "";
});
f.t.splice.apply(f.t, [p, 0].concat(units));
f.k.splice.apply(f.k, [p, 0].concat(ks));
f.c.splice.apply(f.c, [p, 0].concat(cs));
}
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);
// what is crossed out comes first, then what replaces it
while (p < f.t.length && f.k[p] === "del") p++;
insert(f, p, text);
build(f);
draw(p + text.length);
}
function strike(r, caretAtEnd) {
remember();
var f = flat();
var kept = crossOut(f, r.s, r.e);
build(f);
draw(caretAtEnd ? r.s + kept : r.s);
}
// one character, or a word, or the line before the caret, skipping what
// is crossed out already
function back(p, unit) {
var f = flat();
while (p > 0 && f.k[p - 1] === "del") 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])) a--;
} else {
while (a > 0 && f.t[a - 1] !== "\n") a--;
}
strike({ s: a, e: p }, false);
}
function forward(p, unit) {
var f = flat();
var n = f.t.length;
while (p < n && f.k[p] === "del") 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])) 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) {
say("Select the words to highlight first.");
return;
}
var comment = (commentBox.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.k[i] = "mark";
f.c[i] = comment;
}
}
build(f);
commentBox.value = "";
draw(r.e);
}
// takes the marks back from the selection, or from the mark at the caret
function restore(r) {
if (!r) return;
var f = flat();
var s = r.s, e = r.e;
if (s === e) {
var k = f.k[s] !== "same" && f.k[s] !== undefined ? f.k[s] : f.k[s - 1];
if (!k || k === "same") {
say("Select what to restore, or put the caret in a mark.");
return;
}
var at = f.k[s] === k ? s : s - 1;
s = at;
e = at;
while (s > 0 && f.k[s - 1] === k) s--;
while (e < f.t.length && f.k[e] === k) e++;
}
remember();
var t = [], ks = [], cs = [];
for (var i = 0; i < f.t.length; i++) {
if (i >= s && i < e) {
if (f.k[i] === "ins") continue;
t.push(f.t[i]);
ks.push("same");
cs.push("");
} else {
t.push(f.t[i]);
ks.push(f.k[i]);
cs.push(f.c[i]);
}
}
build({ t: t, k: ks, c: cs });
draw(s);
}
function undo() {
if (!history.length) return say("Nothing to undo.");
var caret = current();
pieces = JSON.parse(history.pop());
draw(caret ? Math.min(caret.s, total()) : null);
}
function total() {
return pieces.reduce(function (n, p) {
return n + p.t.length;
}, 0);
}
// what the browser changed itself (a keyboard's composition, an edit it
// would not let us cancel): compared with our text, taken as an edit
function resync() {
var mine = pieces
.map(function (p) {
return p.t;
})
.join("");
var theirs = ed.textContent;
if (mine === theirs) return;
var a = 0;
while (a < mine.length && a < theirs.length && mine[a] === theirs[a]) a++;
var b = 0;
while (
b < mine.length - a &&
b < theirs.length - a &&
mine[mine.length - 1 - b] === theirs[theirs.length - 1 - b]
) {
b++;
}
var added = theirs.slice(a, theirs.length - b);
remember();
var f = flat();
var p = a + crossOut(f, a, mine.length - b);
insert(f, p, added);
build(f);
draw(p + added.length);
}
// ---- telling what is there
function say(text) {
note.textContent = text;
}
function tell() {
var changes = 0, marks = 0, open = false;
pieces.forEach(function (p) {
if (p.k === "ins" || p.k === "del") {
if (!open) changes++;
open = true;
} else {
open = false;
if (p.k === "mark") marks++;
}
});
count.textContent =
changes + (changes === 1 ? " change, " : " changes, ") + marks + (marks === 1 ? " highlight" : " highlights");
}
// ---- events
ed.addEventListener("beforeinput", function (ev) {
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 (!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();
undo();
}
});
document.addEventListener("selectionchange", function () {
var r = current();
if (!r) return;
lastSel = r;
var p = pieces;
var acc = 0;
for (var i = 0; i < p.length; i++) {
if (r.s >= acc && r.s < acc + p[i].t.length) {
if (p[i].k === "mark") say(p[i].c ? "Highlighted: " + p[i].c : "Highlighted, without a comment.");
else if (p[i].k === "del") say("Crossed out. Restore takes it back.");
else if (p[i].k === "ins") say("Added by you.");
else say("");
return;
}
acc += p[i].t.length;
}
});
document.addEventListener("click", function (ev) {
var b = ev.target.closest && ev.target.closest("[data-rv]");
if (!b) 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();
});
form.addEventListener("submit", function (ev) {
var changed = pieces.some(function (p) {
return p.k !== "same";
});
if (!changed && !window.confirm("Send it back without any change or highlight?")) {
ev.preventDefault();
return;
}
sending = true;
});
window.addEventListener("beforeunload", function (ev) {
if (dirty && !sending) {
ev.preventDefault();
ev.returnValue = "";
}
});
draw(null);
})();