Files
visa/static/review-editor.js
T
grabowski a4155548b8
CI / secret scan (push) Successful in 5s
CI / fmt, clippy, tests (push) Successful in 49s
CI / release (push) Skipped
The other side reviews a draft (phase 13, step 1)
A lawyer sends a contract version to one of its parties with a link. On
it the other side marks the text up in an editor that keeps every change
visible, as tracked changes do: deleting our text crosses it out in red,
typing is marked as added in green, and the highlighter marks a passage
in yellow with a comment. Restore and Undo take marks back. They send it
back once a round; each later version comes on the same link.

- Migration 0014: review_links (token kept as a SHA-256, one open link a
  party) and review_rounds (the reply written once: their pieces, text,
  SHA-256, name, message; a trigger refuses any other change and every
  delete). Journal entries "sent for review", "review returned" (with the
  fingerprint of their text) and "review link closed"; audit entity
  "review".
- The reply is a list of pieces (same, ins, del, mark). The server checks
  that the pieces without the added ones are exactly the version sent, so
  nothing changes unseen (reviews::check).
- Our review page: their message, the changes numbered with the words
  around them and a box each, the highlights with comments, a git-style
  diff (line numbers, - and + lines, the changed words marked, three lines
  of context per hunk) and their markup. "Take the ticked changes" opens
  the contract page with the version form filled with our text plus those
  changes.
- static/review-editor.js: edits work on the pieces and redraw, so our
  text cannot vanish; keyboard compositions and edits the browser will not
  cancel are compared with the text and taken as edits.
- Property tests (any markup is accepted and taken back exactly; markup
  that changes our text unseen is refused), the fuzz text target runs
  reviews::check, integration tests, and the demo has the label's review
  of the recording agreement.
- PLAN: phase 13.
2026-11-23 15:31:43 +07:00

453 lines
13 KiB
JavaScript

// 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);
})();