Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
1228 lines (1135 loc) · 53.7 KB
/
Copy pathcontent.js
File metadata and controls
1228 lines (1135 loc) · 53.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* The Overleaf-side interface.
*
* How it gets your project: it asks Overleaf for the same zip the Download →
* Source menu item produces, using the session you are already logged into.
* That is deliberately the least clever option available -- no scraping of the
* editor's DOM, which would only ever see the file you have open and would
* break every time Overleaf ships a new editor.
*
* Everything renders inside a shadow root, so Overleaf's stylesheet and this
* panel cannot reach into each other.
*/
(() => {
"use strict";
const M = globalThis.mechcheck;
if (!M) { console.error("mechcheck: engine did not load"); return; }
const getProjectId = () => (location.pathname.match(/\/project\/([0-9a-fA-F]{16,32})/) || [])[1] || null;
const PROJECT_ID = getProjectId();
let host = null, root = null;
let lastResult = null, running = false;
let lastOutputAttempts = [];
let lastAdopted = [], lastConfigPath = null;
let pendingCompileRecheck = false, compileTimer = null;
/* A paper being submitted to CHI, as everywhere else. A thesis picks the
thesis profile, and the project's own mechcheck.yaml overrides both. */
const DEFAULTS = { profile: "paper", stage: "submission", venue: "chi",
verify: false, autorun: false, onCompile: true, markers: true, notes: true };
async function getSettings() {
try {
const stored = await chrome.storage.sync.get("settings");
return { ...DEFAULTS, ...(stored.settings || {}) };
} catch (err) { return { ...DEFAULTS }; }
}
/* ---------- getting the project ---------- */
async function fetchProjectZip(projectId = getProjectId()) {
if (!projectId) throw new Error("No Overleaf project is open in this tab.");
const res = await fetch(`/project/${projectId}/download/zip`, {
credentials: "same-origin",
cache: "no-store",
headers: { "Accept": "application/zip" },
});
if (!res.ok) throw new Error(`Overleaf refused the download (HTTP ${res.status}). `
+ "Reload the page and make sure you are still signed in.");
const buffer = await res.arrayBuffer();
if (buffer.byteLength < 30) throw new Error("Overleaf returned an empty project.");
return M.readZip(buffer);
}
/* The compiled log and PDF unlock the compile, page-count and PDF-metadata
checks -- including ANON006, which reads the author name out of the PDF
and is the classic way a carefully anonymised paper de-anonymises itself.
Guessing the URL does not work: Overleaf serves output from
/project/<id>/build/<buildId>/output/<file>, with a clsiserverid query
parameter that routes to the machine holding that build. Neither is
knowable from the outside.
The editor downloads both files to show you the PDF. Browsers cap
performance.getEntriesByType("resource") at ~250 entries, so a long
editing session loses new compiles unless we also listen via a
PerformanceObserver -- which simultaneously tells us the moment Overleaf
finishes a fresh compile so we can recheck automatically. */
const OUTPUT_PATTERNS = [
/\/(?:download\/)?project\/([0-9a-fA-F]+)\/build\/([\w-]+)\/output\/([\w.-]+)/,
/\/project\/([0-9a-fA-F]+)\/output\/([\w.-]+)/,
];
const observedOutputs = new Map();
const selfFetchedUrls = new Set();
let lastCompiledBuildKey = null;
function resolveUrl(url) {
try { return new URL(String(url), location.href).href; }
catch (err) { return String(url || ""); }
}
function matchOutputUrl(url, projectId = getProjectId()) {
const s = String(url || "");
let m = OUTPUT_PATTERNS[0].exec(s);
if (m) {
if (projectId && m[1].toLowerCase() !== projectId.toLowerCase()) return null;
return { projectId: m[1].toLowerCase(), buildId: m[2], name: m[3], url: s };
}
m = OUTPUT_PATTERNS[1].exec(s);
if (m) {
if (projectId && m[1].toLowerCase() !== projectId.toLowerCase()) return null;
return { projectId: m[1].toLowerCase(), buildId: null, name: m[2], url: s };
}
return null;
}
function scheduleCompileRecheck() {
if (compileTimer) clearTimeout(compileTimer);
compileTimer = setTimeout(async () => {
compileTimer = null;
const settings = await getSettings();
if (settings.onCompile !== false && (lastResult || settings.autorun)) {
if (running) { pendingCompileRecheck = true; return; }
run();
} else if (root && lastResult) {
const btn = root.querySelector(".recheck");
if (btn) btn.classList.add("stale");
setStatus("New compile ready — click ↻ to recheck");
}
}, 800);
}
function handleOutputResource(url, isLive = true) {
if (selfFetchedUrls.has(url) || selfFetchedUrls.has(resolveUrl(url))) return false;
const hit = matchOutputUrl(url, getProjectId());
if (!hit) return false;
const prevUrl = observedOutputs.get(hit.name);
observedOutputs.set(hit.name, hit.url);
if (!/\.(pdf|log)$/i.test(hit.name)) return false;
const buildKey = hit.buildId ? `${hit.projectId}:${hit.buildId}` : `${hit.projectId}:${hit.url}`;
if (!isLive) {
lastCompiledBuildKey = buildKey;
return true;
}
if (buildKey === lastCompiledBuildKey || hit.url === prevUrl) return false;
lastCompiledBuildKey = buildKey;
scheduleCompileRecheck();
return true;
}
function startWatchingResources() {
try {
for (const entry of performance.getEntriesByType("resource"))
handleOutputResource(entry.name, false);
} catch (err) { /* resource timing unavailable */ }
if (typeof PerformanceObserver !== "function") return;
try {
let bootstrapped = false;
const obs = new PerformanceObserver(list => {
const live = bootstrapped;
for (const entry of list.getEntries()) handleOutputResource(entry.name, live);
bootstrapped = true;
});
obs.observe({ type: "resource", buffered: true });
// If buffered entries do not fire synchronously, switch live mode on next tick.
setTimeout(() => { bootstrapped = true; }, 0);
} catch (err) { /* ignore unsupported observer options */ }
}
function discoverOutputUrls(projectId = getProjectId()) {
const found = new Map();
try {
for (const entry of performance.getEntriesByType("resource")) {
const hit = matchOutputUrl(entry.name, projectId);
if (hit) found.set(hit.name, hit.url);
}
} catch (err) { /* resource timing unavailable */ }
for (const [name, url] of observedOutputs) {
if (matchOutputUrl(url, projectId)) found.set(name, url);
}
return found;
}
async function fetchOutputs(files, projectId = getProjectId()) {
const discovered = discoverOutputUrls(projectId);
const attempts = [];
// Whatever the editor actually fetched, in the form it fetched it.
for (const [name, url] of discovered) {
if (/\.(log|pdf)$/i.test(name)) attempts.push([name, url]);
}
// The editor fetches the log too, but if only the PDF is in the timeline,
// the log sits beside it under the same build.
const pdfUrl = discovered.get("output.pdf");
if (pdfUrl && !discovered.has("output.log"))
attempts.push(["output.log", pdfUrl.replace(/output\.pdf/, "output.log")]);
// Last resort: the path older Overleaf versions served.
if (projectId) {
attempts.push(["output.log", `/project/${projectId}/output/output.log`]);
attempts.push(["output.pdf", `/project/${projectId}/output/output.pdf`]);
}
const tried = [];
const fetchedHere = new Set();
for (const [name, url] of attempts) {
if (fetchedHere.has(name)) continue;
const absUrl = resolveUrl(url);
selfFetchedUrls.add(url);
selfFetchedUrls.add(absUrl);
try {
const res = await fetch(url, { credentials: "same-origin", cache: "no-store" });
tried.push(`${url.split("?")[0]} -> ${res.status}`);
if (!res.ok) continue;
const buf = new Uint8Array(await res.arrayBuffer());
if (buf.byteLength > 100) {
files.set(name, buf);
fetchedHere.add(name);
}
} catch (err) {
tried.push(`${url.split("?")[0]} -> ${err.message}`);
} finally {
setTimeout(() => { selfFetchedUrls.delete(url); selfFetchedUrls.delete(absUrl); }, 2000);
}
}
lastOutputAttempts = tried;
return files;
}
/* ---------- running ---------- */
const relayFetch = async (url, key) => {
try {
const reply = await chrome.runtime.sendMessage({ type: "mechcheck:fetch", url, key });
return reply && reply.ok ? reply.data : undefined;
} catch (err) {
return undefined; // extension reloaded mid-run, or the worker was evicted
}
};
/* A project that carries a mechcheck.yaml has already decided its profile,
stage and venue. Adopt them rather than making the student match three
controls to a file they may not know is there; the rest of the file
(disabled rules, ignore lists, the project's own vocabulary) the engine
reads for itself. */
function adoptProjectConfig(files, settings) {
lastAdopted = [];
const project = M.readProjectConfig(files);
lastConfigPath = project ? project.path : null;
if (!project || !root) return;
for (const key of ["profile", "stage", "venue"]) {
const value = project.data[key];
if (value === undefined || value === null) continue;
const node = root.querySelector("." + key);
const wanted = String(value);
if (!node || ![...node.options].some(o => o.value === wanted) || settings[key] === wanted) continue;
node.value = wanted;
settings[key] = wanted;
lastAdopted.push(`${key} = ${wanted}`);
}
}
function setRunningState(busy) {
if (!root) return;
const checkBtn = root.querySelector(".check");
if (checkBtn) {
checkBtn.disabled = !!busy;
checkBtn.textContent = busy ? "Checking…" : (lastResult ? "Recheck" : "Check");
}
const recheckBtn = root.querySelector(".recheck");
if (recheckBtn) {
recheckBtn.disabled = !!busy;
recheckBtn.classList.toggle("running", !!busy);
if (busy) recheckBtn.classList.remove("stale");
}
const recheckHead = root.querySelector(".recheck-head");
if (recheckHead) {
recheckHead.disabled = !!busy;
recheckHead.textContent = busy ? "↻ Checking…" : "↻ Recheck";
}
}
async function run() {
if (running) return;
running = true;
ensureUI();
setRunningState(true);
const settings = await getSettings();
setStatus("Asking Overleaf for the project…");
try {
const pid = getProjectId();
const files = await fetchProjectZip(pid);
setStatus("Reading the compiled output…");
await fetchOutputs(files, pid);
adoptProjectConfig(files, settings);
setStatus(`Checking ${files.size} file${files.size === 1 ? "" : "s"}…`);
const result = await M.runChecks(files, {
...settings,
fetchJson: settings.verify ? relayFetch : undefined,
onProgress: (frac, id) => setProgress(frac),
});
lastResult = result;
render(result, settings);
} catch (err) {
renderError(err);
} finally {
running = false;
setRunningState(false);
setProgress(0);
if (pendingCompileRecheck) {
pendingCompileRecheck = false;
run();
}
}
}
/* ---------- the panel ---------- */
const CSS = `
:host { all: initial; }
* { box-sizing: border-box; }
.wrap {
/* Clear of the bottom-right corner: other Overleaf extensions put their own
button there, and two overlapping circles is nobody's idea of a good time. */
position: fixed; right: 16px; bottom: 96px; z-index: 2147483000;
font-family: -apple-system, "Segoe UI", system-ui, sans-serif;
color-scheme: light dark;
}
.launcher-bar {
display: inline-flex; align-items: stretch; margin-top: 6px;
background: #3a4ea8; color: #fff; border-radius: 999px; overflow: hidden;
box-shadow: 0 2px 6px rgba(0,0,0,.2), 0 10px 30px -12px rgba(0,0,0,.5);
}
.launcher {
display: flex; align-items: center; gap: 8px;
background: transparent; color: #fff; border: none;
padding: 10px 14px 10px 16px; font-size: 13px; font-weight: 600; cursor: pointer;
}
.launcher:hover, .recheck:hover { background: rgba(0,0,0,.14); }
.launcher .badge {
background: rgba(255,255,255,.22); border-radius: 999px; padding: 1px 7px;
font-variant-numeric: tabular-nums; font-size: 12px;
}
.launcher .badge.err { background: #b23026; }
.recheck {
position: relative; display: inline-flex; align-items: center; justify-content: center;
background: transparent; color: #fff; border: none;
border-left: 1px solid rgba(255,255,255,.2);
padding: 0 13px; font-size: 15px; font-weight: 700; cursor: pointer;
}
.recheck:disabled { opacity: .65; cursor: wait; }
.recheck.running span { display: inline-block; animation: mc-spin .85s linear infinite; }
.recheck.stale::after {
content: ""; position: absolute; top: 7px; right: 7px; width: 6px; height: 6px;
border-radius: 999px; background: #f5b942;
}
@keyframes mc-spin { to { transform: rotate(360deg); } }
.fix-actions { display: flex; gap: 6px; padding: 8px 12px; border-bottom: 1px solid #eef1f6; }
.panel {
width: min(440px, calc(100vw - 32px)); max-height: min(680px, calc(100vh - 90px));
background: #fff; color: #171a21; border: 1px solid #d8dde6; border-radius: 10px;
box-shadow: 0 4px 12px rgba(0,0,0,.12), 0 24px 60px -20px rgba(0,0,0,.4);
display: flex; flex-direction: column; overflow: hidden; font-size: 13px;
}
@media (prefers-color-scheme: dark) {
.panel { background: #151922; color: #e5e8ef; border-color: #2a303c; }
.head, .foot { background: #1c212c !important; border-color: #2a303c !important; }
.finding { border-color: #21262f !important; }
.ctx { background: #0e1116 !important; color: #a3abbd !important; }
select, .btn { background: #1c212c !important; color: #e5e8ef !important; border-color: #2a303c !important; }
.rule { background: #1c212c !important; }
}
.head {
display: flex; align-items: center; gap: 8px; padding: 10px 12px;
border-bottom: 1px solid #d8dde6; background: #f7f8fa;
}
.head .title { font-weight: 600; flex: 1; }
.head .close { background: none; border: none; font-size: 18px; cursor: pointer; color: inherit; opacity: .6; padding: 0 4px; }
.head .close:hover { opacity: 1; }
.controls { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 12px; border-bottom: 1px solid #d8dde6; }
select, .btn {
font: inherit; font-size: 12px; padding: 4px 8px; border: 1px solid #d8dde6;
border-radius: 5px; background: #fff; color: inherit; cursor: pointer;
}
.btn.primary { background: #3a4ea8; color: #fff; border-color: #3a4ea8; font-weight: 600; }
.btn:disabled { opacity: .5; cursor: not-allowed; }
label.toggle { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; cursor: pointer; }
.summary { display: flex; gap: 6px; padding: 8px 12px; border-bottom: 1px solid #d8dde6; flex-wrap: wrap; }
.pill {
font-size: 12px; padding: 3px 9px; border-radius: 999px; border: 1px solid #d8dde6;
background: #fff; cursor: pointer; font-variant-numeric: tabular-nums; color: inherit;
}
.pill[aria-pressed="false"] { opacity: .45; }
.pill.err { border-color: #b23026; color: #b23026; }
.pill.warn { border-color: #9a6207; color: #9a6207; }
.stats { font-size: 11px; opacity: .65; padding: 0 12px 8px; }
.body { overflow-y: auto; flex: 1; }
.finding { padding: 8px 12px; border-bottom: 1px solid #eef1f6; display: flex; gap: 8px; }
.stripe { width: 3px; border-radius: 2px; flex: none; background: #9aa2b4; }
.finding.error .stripe { background: #b23026; }
.finding.warn .stripe { background: #9a6207; }
.finding .main { min-width: 0; flex: 1; display: flex; flex-direction: column; gap: 3px; }
.finding .top { display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; }
.rule { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 11px;
background: #eef1f6; border-radius: 3px; padding: 1px 5px; }
.loc { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 11px; opacity: .6; }
.msg { line-height: 1.45; }
.ctx { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 11px;
background: #f7f8fa; border-radius: 4px; padding: 4px 6px; overflow-x: auto; white-space: pre; }
.fix { font-size: 12px; opacity: .8; }
.empty { padding: 28px 16px; text-align: center; opacity: .75; line-height: 1.6; }
.empty b { display: block; font-size: 15px; margin-bottom: 4px; opacity: 1; }
.note { padding: 8px 12px; font-size: 12px; background: #fff8e6; border-bottom: 1px solid #f0e3bd; color: #6b4d09; }
.note.bad { background: #fdecea; border-color: #f5c6c2; color: #8c231b; }
.foot { padding: 6px 12px; font-size: 11px; opacity: .6; border-top: 1px solid #d8dde6; background: #f7f8fa;
display: flex; justify-content: space-between; gap: 8px; }
.progress { height: 2px; background: #eef1f6; }
.progress i { display: block; height: 100%; background: #3a4ea8; width: 0; transition: width .15s linear; }
.hidden { display: none !important; }
`;
function ensureUI() {
if (host) return;
host = document.createElement("div");
host.id = "mechcheck-host";
root = host.attachShadow({ mode: "open" });
root.innerHTML = `<style>${CSS}</style>
<div class="wrap">
<div class="panel hidden" part="panel">
<div class="head">
<span class="title">mechcheck</span>
<button class="btn recheck-head" title="Recheck project (Alt+Shift+M)">↻ Recheck</button>
<button class="close" title="Close">×</button>
</div>
<div class="controls">
<select class="profile" title="Profile"></select>
<select class="stage" title="Stage"></select>
<select class="venue" title="Venue"></select>
<label class="toggle"><input type="checkbox" class="verify"> verify refs</label>
<label class="toggle" title="Recheck automatically whenever Overleaf finishes compiling"><input type="checkbox" class="onCompile" checked> on compile</label>
<label class="toggle"><input type="checkbox" class="markers" checked> mark lines</label>
<label class="toggle"><input type="checkbox" class="notes" checked> explain inline</label>
<button class="btn primary check">Check</button>
<button class="btn fix" disabled>Fix</button>
</div>
<div class="progress"><i></i></div>
<div class="note hidden"></div>
<div class="summary hidden"></div>
<div class="stats"></div>
<div class="body"></div>
<div class="foot"><span class="status">Ready</span><span class="copy btn">Copy report</span></div>
</div>
<div class="launcher-bar">
<button class="launcher">mechcheck<span class="badge hidden"></span></button>
<button class="recheck" title="Recheck project (Alt+Shift+M)" aria-label="Recheck project"><span>↻</span></button>
</div>
</div>`;
document.documentElement.appendChild(host);
const q = sel => root.querySelector(sel);
q(".launcher").addEventListener("click", () => {
const p = q(".panel");
p.classList.toggle("hidden");
if (!p.classList.contains("hidden") && !lastResult && !running) run();
});
q(".recheck").addEventListener("click", () => run());
q(".recheck-head").addEventListener("click", () => run());
q(".close").addEventListener("click", () => q(".panel").classList.add("hidden"));
q(".check").addEventListener("click", run);
q(".fix").addEventListener("click", () => showFixes());
q(".copy").addEventListener("click", copyReport);
fillSelect(q(".profile"), Object.keys(M.PROFILES).map(k => [k, k]));
fillSelect(q(".stage"), Object.keys(M.STAGES).map(k => [k, k]));
fillSelect(q(".venue"), [["", "no venue"]].concat(
Object.entries(M.VENUES).map(([k, v]) => [k, v.name])));
for (const sel of [".profile", ".stage", ".venue", ".verify"]) {
q(sel).addEventListener("change", async () => {
// Merge into what is stored: writing only these four dropped autorun,
// markers and notes every time a dropdown changed.
try {
const stored = (await chrome.storage.sync.get("settings")).settings || {};
await chrome.storage.sync.set({ settings: {
...stored, profile: q(".profile").value, stage: q(".stage").value,
venue: q(".venue").value, verify: q(".verify").checked,
} });
} catch (err) { /* ignore */ }
if (lastResult) run();
});
}
q(".onCompile").addEventListener("change", async () => {
const on = q(".onCompile").checked;
try {
const stored = await chrome.storage.sync.get("settings");
await chrome.storage.sync.set({ settings: { ...(stored.settings || {}), onCompile: on } });
} catch (err) { /* ignore */ }
setStatus(on ? "Will recheck automatically on Overleaf compile" : "Auto-recheck on compile is off");
});
// Marks are a view of the last result, not part of the check, so this
// toggle redraws rather than re-running anything.
q(".markers").addEventListener("change", async () => {
const on = q(".markers").checked;
const placed = setMarkersEnabled(on);
try {
const stored = await chrome.storage.sync.get("settings");
await chrome.storage.sync.set({ settings: { ...(stored.settings || {}), markers: on } });
} catch (err) { /* settings are a convenience; the toggle still worked */ }
if (on) setStatus(placed ? `${placed} line${placed === 1 ? "" : "s"} marked in the editor`
: "Nothing to mark in the file you have open");
});
q(".notes").addEventListener("change", async () => {
const on = q(".notes").checked;
const written = setAnnotationsEnabled(on);
try {
const stored = await chrome.storage.sync.get("settings");
await chrome.storage.sync.set({ settings: { ...(stored.settings || {}), notes: on } });
} catch (err) { /* settings are a convenience; the toggle still worked */ }
// Notes are only drawn for the lines on screen, so nothing drawn does
// not mean nothing found -- and saying it did would be a lie the
// moment you scrolled.
if (on) setStatus(written ? `${written} line${written === 1 ? "" : "s"} explained in the editor`
: "No findings on the lines you can see");
});
getSettings().then(s => {
q(".profile").value = s.profile; q(".stage").value = s.stage;
q(".venue").value = s.venue; q(".verify").checked = !!s.verify;
q(".onCompile").checked = s.onCompile !== false;
q(".markers").checked = s.markers !== false;
markersEnabled = s.markers !== false;
q(".notes").checked = s.notes !== false;
annotationsEnabled = s.notes !== false;
if (s.autorun) run();
});
}
function fillSelect(select, pairs) {
select.innerHTML = "";
for (const [value, label] of pairs) {
const opt = document.createElement("option");
opt.value = value; opt.textContent = label;
select.appendChild(opt);
}
}
const setStatus = text => { if (root) root.querySelector(".status").textContent = text; };
const setProgress = frac => { if (root) root.querySelector(".progress i").style.width = Math.round(frac * 100) + "%"; };
function setNote(text, bad) {
if (!root) return;
const note = root.querySelector(".note");
note.classList.toggle("hidden", !text);
note.classList.toggle("bad", !!bad);
note.textContent = text || "";
}
const filters = { error: true, warn: true, info: true };
function render(result, settings) {
ensureUI();
// Whatever is on screen is the current result: the marker toggle, the
// fix button and the report all read it back from here.
lastResult = result;
const q = sel => root.querySelector(sel);
const counts = { error: 0, warn: 0, info: 0 };
// Totals cover everything found, including what the per-rule cap held back.
for (const f of result.findings.concat(result.truncated || []))
counts[M.SEV_NAME[f.severity]]++;
const badge = root.querySelector(".badge");
const total = counts.error + counts.warn;
badge.classList.toggle("hidden", total === 0);
badge.classList.toggle("err", counts.error > 0);
badge.textContent = String(total);
const summary = q(".summary");
summary.classList.remove("hidden");
summary.innerHTML = "";
for (const key of ["error", "warn", "info"]) {
const b = document.createElement("button");
b.className = "pill" + (key === "error" ? " err" : key === "warn" ? " warn" : "");
b.setAttribute("aria-pressed", String(filters[key]));
b.textContent = `${counts[key]} ${key}`;
b.addEventListener("click", () => { filters[key] = !filters[key]; render(result, settings); });
summary.appendChild(b);
}
const s = result.stats;
q(".stats").textContent = `${s.main} · ${s.words.toLocaleString()} words · `
+ `${s.references} reference${s.references === 1 ? "" : "s"} · ${s.floats} float${s.floats === 1 ? "" : "s"}`
+ (s.pages ? ` · ${s.pages} pages` : "")
+ (s.hasLog ? "" : " · no .log, compile checks skipped")
+ (Object.keys(result.truncatedByRule || {}).length
? " · repeated findings listed once: "
+ Object.entries(result.truncatedByRule).sort()
.map(([r, n]) => `${r} +${n}`).join(", ")
: "");
// When the output files could not be reached, say what was tried rather
// than leaving a bare "skipped" that nobody can act on.
q(".stats").title = s.hasLog ? "" :
("Tried:\n" + (lastOutputAttempts.join("\n") || "nothing — the editor had not "
+ "fetched the output yet in this page load. Recompile, then check again."));
const config = s.configPath
? `Using this project's ${s.configPath}`
+ (lastAdopted.length ? `, which set ${lastAdopted.join(" · ")}. ` : ". ")
: "";
if (s.mainGuessed)
setNote(config + `Guessed ${s.main} as the main file — no file had both \\documentclass and \\begin{document}.`, true);
else if (settings.verify && s.netBlocked)
setNote(config + "Reference lookups could not reach the internet. Everything else ran.", true);
else if (!settings.verify)
setNote(config + "Reference verification is off. Turn on “verify refs” to check that your citations exist.");
else setNote(config);
const body = q(".body");
body.innerHTML = "";
const shown = result.findings.filter(f => filters[M.SEV_NAME[f.severity]]);
if (!result.findings.length) {
body.innerHTML = `<div class="empty"><b>Nothing mechanical left to fix.</b>The remaining work is the thinking.</div>`;
} else if (!shown.length) {
body.innerHTML = `<div class="empty">Nothing matches these filters.</div>`;
}
for (const f of shown) {
const row = document.createElement("div");
row.className = "finding " + M.SEV_NAME[f.severity];
const stripe = document.createElement("div"); stripe.className = "stripe";
const main = document.createElement("div"); main.className = "main";
const top = document.createElement("div"); top.className = "top";
const rule = document.createElement("span"); rule.className = "rule"; rule.textContent = f.rule;
const loc = document.createElement("span"); loc.className = "loc";
loc.textContent = f.file ? f.file + (f.line ? ":" + f.line : "") : "";
top.append(rule, loc);
const msg = document.createElement("div"); msg.className = "msg"; msg.textContent = f.message;
main.append(top, msg);
if (f.context) {
const ctx = document.createElement("div"); ctx.className = "ctx"; ctx.textContent = f.context;
main.appendChild(ctx);
}
if (f.fix) {
const fix = document.createElement("div"); fix.className = "fix"; fix.textContent = "Fix: " + f.fix;
main.appendChild(fix);
}
row.append(stripe, main);
body.appendChild(row);
}
const fixable = result.findings.concat(result.truncated || []).filter(f => f.edit).length;
const fixButton = root.querySelector(".fix");
fixButton.disabled = !fixable;
fixButton.textContent = fixable ? `Fix ${fixable}` : "Fix";
const checkButton = root.querySelector(".check");
if (checkButton && !running) checkButton.textContent = "Recheck";
const recheckBtn = root.querySelector(".recheck");
if (recheckBtn) recheckBtn.classList.remove("stale");
// Put the findings beside the lines they are about, in Overleaf's own
// editor. Nothing is written into the project; see placeMarkers.
markersEnabled = settings.markers !== false;
annotationsEnabled = settings.notes !== false;
const marked = placeMarkers(result);
placeAnnotations(result);
if (markersEnabled || annotationsEnabled) startWatchingEditor();
setStatus(`${counts.error} error${counts.error === 1 ? "" : "s"}, ${counts.warn} warning${counts.warn === 1 ? "" : "s"}`
+ (result.suppressed.length ? ` · ${result.suppressed.length} silenced` : "")
+ (marked ? ` · ${marked} marked in the editor` : ""));
}
function renderError(err) {
ensureUI();
clearMarkers(); // marks from an earlier run would now be lying
clearAnnotations(); // and so would the notes beside the lines
root.querySelector(".panel").classList.remove("hidden");
root.querySelector(".body").innerHTML =
`<div class="empty"><b>Could not check this project</b>${escapeHtml(err.message || String(err))}</div>`;
setStatus("Failed");
setNote("");
}
/* A content script cannot edit the Overleaf document -- it is a CRDT synced
over a websocket, and writing into it behind the editor's back is a good
way to corrupt somebody's paper. Handing over the corrected file is the
honest option: copy, select all in Overleaf, paste. */
function showFixes(result) {
// Defaulting to the last run keeps the click handler trivial; taking a
// result explicitly is what lets the harness exercise this path.
const target = (result && result.findings) ? result : lastResult;
if (!target) return;
const fx = M.applyFixes(target);
const body = root.querySelector(".body");
body.innerHTML = "";
if (!fx.files.size) {
body.innerHTML = `<div class="empty">Nothing here can be fixed automatically.</div>`;
return;
}
const actions = document.createElement("div");
actions.className = "fix-actions";
const backBtn = document.createElement("button");
backBtn.className = "btn back-findings";
backBtn.textContent = "← Back to findings";
backBtn.addEventListener("click", async () => render(target, await getSettings()));
const recheckAfterBtn = document.createElement("button");
recheckAfterBtn.className = "btn primary recheck-after-fix";
recheckAfterBtn.textContent = "↻ Recheck now";
recheckAfterBtn.addEventListener("click", () => run());
actions.append(backBtn, recheckAfterBtn);
body.appendChild(actions);
const intro = document.createElement("div");
intro.className = "note";
intro.textContent = `${fx.applied.length} fix(es) ready. Copy the corrected file, then in `
+ "Overleaf open it, select all, and paste — then click Recheck now. Only rules with "
+ "exactly one right answer are fixed; alt text and anything needing judgement are left alone.";
body.appendChild(intro);
for (const [path, text] of fx.files) {
const n = fx.applied.filter(a => a.path === path).length;
const row = document.createElement("div");
row.className = "finding";
const stripe = document.createElement("div"); stripe.className = "stripe";
const main = document.createElement("div"); main.className = "main";
const top = document.createElement("div"); top.className = "top";
const name = document.createElement("span"); name.className = "rule"; name.textContent = path;
const count = document.createElement("span"); count.className = "loc";
count.textContent = `${n} change${n === 1 ? "" : "s"}`;
top.append(name, count);
const button = document.createElement("button");
button.className = "btn primary";
button.textContent = "Copy corrected file";
button.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(text);
button.textContent = "Copied — paste over the file in Overleaf";
} catch (err) {
button.textContent = "Could not copy (clipboard blocked)";
}
});
const what = document.createElement("div");
what.className = "fix";
what.textContent = fx.applied.filter(a => a.path === path)
.slice(0, 6).map(a => a.describe).join(" · ");
main.append(top, what, button);
row.append(stripe, main);
body.appendChild(row);
}
setStatus(`${fx.applied.length} fix(es) ready to copy`);
}
const escapeHtml = s => String(s).replace(/[&<>"]/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c]));
function reportMarkdown(result) {
const counts = { error: 0, warn: 0, info: 0 };
for (const f of result.findings.concat(result.truncated || []))
counts[M.SEV_NAME[f.severity]]++;
const lines = [`# mechcheck — ${result.stats.main}`, "",
`${counts.error} errors, ${counts.warn} warnings, ${counts.info} notes`, ""];
for (const f of result.findings) {
const icon = { error: "❌", warn: "⚠️", info: "ℹ️" }[M.SEV_NAME[f.severity]];
lines.push(`- ${icon} \`${f.rule}\` ${f.file || ""}${f.line ? ":" + f.line : ""} — ${f.message}`);
}
const held = Object.entries(result.truncatedByRule || {}).sort();
if (held.length) {
lines.push("", `_Additional repeated findings held back (${(result.truncated || []).length} total): `
+ held.map(([r, n]) => `\`${r}\` +${n}`).join(", ") + "._");
}
return lines.join("\n");
}
async function copyReport() {
if (!lastResult) return;
try {
await navigator.clipboard.writeText(reportMarkdown(lastResult));
setStatus("Report copied");
} catch (err) {
setStatus("Could not copy — check clipboard permission");
}
}
/* ---- marks beside the lines, in Overleaf's own editor ----------------
Every finding already carries a file and a line. Drawing a mark at that
line puts the problem where the problem is, instead of in a list the
reader has to map back onto the source themselves.
Display only, and deliberately so. An extension must not edit an
Overleaf document -- it is a CRDT synced over a websocket, and writing
into it behind the editor's back is how you corrupt somebody's paper --
but a mark in the gutter writes nothing. Nothing here is saved, sent, or
visible to anyone else.
All of it is feature-detected against markup this cannot control. If
Overleaf changes its editor, every function here finds nothing, places
nothing, and the panel carries on exactly as before. */
const MARK_CLASS = "mechcheck-gutter-mark";
const MARK_STYLES = "mechcheck-marker-styles";
let markerObserver = null, markersEnabled = true;
function injectMarkerStyles() {
if (document.getElementById(MARK_STYLES)) return;
const style = document.createElement("style");
style.id = MARK_STYLES;
// These live in Overleaf's own DOM rather than the panel's shadow root,
// so the class name is distinctive enough not to collide with anything.
style.textContent = `
.${MARK_CLASS} { position: absolute; left: 1px; top: 1px; bottom: 1px; width: 3px;
border-radius: 2px; background: #9a6207; cursor: help; z-index: 5; }
.${MARK_CLASS}.error { background: #b23026; }
.${MARK_CLASS}.info { background: #3a4ea8; }
.${NOTE_LAYER} { position: absolute; inset: 0; overflow: hidden;
pointer-events: none; z-index: 4; }
.${NOTE_RULE} { position: absolute; height: 2px; border-radius: 1px;
background: #9a6207; opacity: .85; }
.${NOTE_RULE}.error { background: #b23026; }
.${NOTE_RULE}.info { background: #3a4ea8; }
.${NOTE_CLASS} { position: absolute; pointer-events: auto; cursor: help;
font: 11px/1.45 ui-sans-serif, system-ui, sans-serif;
padding: 0 6px; border-radius: 3px; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis;
color: #fff; background: #9a6207; opacity: .92; }
.${NOTE_CLASS}.error { background: #b23026; }
.${NOTE_CLASS}.info { background: #3a4ea8; }`;
(document.head || document.documentElement).appendChild(style);
}
const editorRoot = () => document.querySelector(".cm-editor");
/** The file the editor is showing, as the file tree names it.
*
* Reading textContent off the tree row is wrong, and live Overleaf is where
* that showed: the row renders its icons as Material Symbols ligatures, so
* the text of the row for main.tex is "descriptionmain.texmore_vertMenu".
* Ask for the name four ways, cheapest and most explicit first. */
function itemName(node) {
if (!node) return null;
const label = ((node.getAttribute && node.getAttribute("aria-label")) || "").trim();
if (label) return label;
for (const hint of [".item-name", '[class*="item-name"]']) {
const inner = node.querySelector && node.querySelector(hint);
const text = inner && (inner.textContent || "").trim();
if (text) return text.split("\n")[0].trim();
}
const clone = node.cloneNode(true);
for (const junk of clone.querySelectorAll(
'[aria-hidden="true"], .material-symbols, .visually-hidden, button, svg, ul, [role="group"]')) {
junk.remove();
}
const name = (clone.textContent || "").trim().split("\n")[0].trim();
return name || null;
}
function selectedTreeItem() {
for (const selector of ['[role="tree"] [aria-selected="true"]',
'[role="tree"] li.selected',
".file-tree li.selected", ".file-tree-item.selected"]) {
let node = null;
try { node = document.querySelector(selector); } catch (err) { continue; }
if (node) return node;
}
return null;
}
function openFileName() {
const node = selectedTreeItem();
return node ? itemName(node) : null;
}
function openFilePath() {
const node = selectedTreeItem();
if (!node) return null;
const parts = [];
let cur = node;
while (cur && cur !== document.body) {
if ((cur.getAttribute && cur.getAttribute("role") === "treeitem") || cur === node) {
const n = itemName(cur);
if (n) parts.unshift(n);
}
if (cur.getAttribute && cur.getAttribute("role") === "tree") break;
cur = cur.parentElement;
}
return parts.length ? parts.join("/") : itemName(node);
}
/** Findings for the open file, grouped by the line they sit on. */
function findingsByLine(result, fileName) {
const byLine = new Map();
if (!fileName) return byLine;
const hasSlash = fileName.includes("/");
for (const f of (result.findings || []).concat(result.truncated || [])) {
if (!f.line || !f.file) continue;
// Match folder-qualified path when available; fall back to basename.
const match = hasSlash
? (f.file === fileName || f.file.endsWith("/" + fileName))
: (f.file.split("/").pop() === fileName);
if (!match) continue;
if (!byLine.has(f.line)) byLine.set(f.line, []);
byLine.get(f.line).push(f);
}
return byLine;
}
function clearMarkers() {
for (const mark of document.querySelectorAll("." + MARK_CLASS)) mark.remove();
}
/** Run fn without the observer listening.
*
* Everything below draws into the DOM the observer watches, so without
* this it retriggers itself forever. */
function withObserverPaused(fn) {
const watching = markerObserver !== null;
if (watching) markerObserver.disconnect();
try { return fn(); }
catch (err) { return 0; }
finally { if (watching) startWatchingEditor(); }
}
/** Draw a mark beside every visible line that has a finding. */
function placeMarkers(result) {
return withObserverPaused(() => drawMarkers(result));
}
function drawMarkers(result) {
const target = result || lastResult;
const editor = editorRoot();
if (!markersEnabled || !target || !editor) { clearMarkers(); return 0; }
injectMarkerStyles();
{
clearMarkers();
const byLine = findingsByLine(target, openFilePath());
let placed = 0;
// Only the line-number gutter: the fold and lint gutters carry their own
// .cm-gutterElement children, and a mark belongs beside a number.
const gutter = editor.querySelector(".cm-lineNumbers") || editor;
for (const element of gutter.querySelectorAll(".cm-gutterElement")) {
// CodeMirror keeps a hidden zero-height element holding the widest
// number, to size the gutter. It is not a line, and on a long enough
// document its number collides with a real one.
if (element.offsetHeight === 0) continue;
const line = parseInt((element.textContent || "").trim(), 10);
if (!Number.isInteger(line)) continue;
const here = byLine.get(line);
if (!here) continue;
const worst = here.reduce((a, b) => (b.severity > a.severity ? b : a));
const mark = document.createElement("span");
mark.className = `${MARK_CLASS} ${M.SEV_NAME[worst.severity]}`;
mark.setAttribute("data-mechcheck-line", String(line));
mark.title = here.map(f => `${f.rule}: ${f.message}`).join("\n");
if (getComputedStyle(element).position === "static") element.style.position = "relative";
element.appendChild(mark);
placed++;
}
return placed;
}
}
let treeObserver = null, resizeObserver = null;
/** The editor renders only the lines you can see, so re-place on every change. */
function startWatchingEditor() {
const editor = editorRoot();
if (!editor || typeof MutationObserver !== "function") return;
const scheduleRedraw = () => {
if (scrollQueued) return;
scrollQueued = true;
const pass = () => { scrollQueued = false; redrawDecorations(); };
if (typeof requestAnimationFrame === "function") requestAnimationFrame(pass);
else setTimeout(pass, 16);
};
if (!markerObserver) {
let queued = false;
markerObserver = new MutationObserver(() => {
if (queued) return; // one pass per frame, not per mutation
queued = true;
const pass = () => { queued = false; redrawDecorations(); };
if (typeof requestAnimationFrame === "function") requestAnimationFrame(pass);
else setTimeout(pass, 16);
});
}
markerObserver.observe(editor, { childList: true, subtree: true });
// Switching files in Overleaf's file tree can reuse CodeMirror nodes; watch selection too.
const tree = document.querySelector('[role="tree"], .file-tree');
if (tree && !treeObserver) {
treeObserver = new MutationObserver(scheduleRedraw);
treeObserver.observe(tree, { attributes: true, attributeFilter: ["aria-selected", "class"], childList: true, subtree: true });
}
// Dragging the editor/PDF split divider shifts line widths and end-of-line positions.
if (typeof ResizeObserver === "function" && !resizeObserver) {
resizeObserver = new ResizeObserver(scheduleRedraw);
resizeObserver.observe(editor);
}
// Scrolling inside already-rendered content moves the lines without
// changing the DOM, so the observer alone would leave the overlay behind.
const scroller = editor.querySelector(".cm-scroller");
if (scroller && !scroller.dataset.mechcheckScroll) {
scroller.dataset.mechcheckScroll = "1";
scroller.addEventListener("scroll", scheduleRedraw, { passive: true });
}
}
/** Both kinds of decoration, in one pause of the observer. */
function redrawDecorations() {
return withObserverPaused(() => {
const marks = drawMarkers();
const notes = drawAnnotations();
return { marks, notes };
});
}
function setMarkersEnabled(on) {
markersEnabled = !!on;
if (!markersEnabled) {
clearMarkers();
if (!annotationsEnabled && markerObserver) { markerObserver.disconnect(); markerObserver = null; }
return 0;
}
const placed = placeMarkers();
startWatchingEditor();