-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredact.js
More file actions
351 lines (319 loc) · 12.4 KB
/
Copy pathredact.js
File metadata and controls
351 lines (319 loc) · 12.4 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
import { PDFDocument, decodePDFRawStream, PDFRawStream, PDFName, rgb } from "./vendor/pdf-lib.esm.min.js";
import { redactContentStream } from "./redact-engine.js";
const dropzone = document.getElementById("dropzone");
const fileInput = document.getElementById("fileInput");
const fileListEl = document.getElementById("fileList");
const actionsEl = document.getElementById("actions");
const redactBtn = document.getElementById("redactBtn");
const redactBtnLabel = document.getElementById("redactBtnLabel");
const clearBtn = document.getElementById("clearBtn");
const resultEl = document.getElementById("result");
const redactPanel = document.getElementById("redactPanel");
const redactMeta = document.getElementById("redactMeta");
const pageInput = document.getElementById("pageInput");
const xInput = document.getElementById("xInput");
const yInput = document.getElementById("yInput");
const wInput = document.getElementById("wInput");
const hInput = document.getElementById("hInput");
const addRectBtn = document.getElementById("addRectBtn");
const rectListEl = document.getElementById("rectList");
const pageSizeHint = document.getElementById("pageSizeHint");
/** @type {{file: File, pageCount: number, pageSizes: {w:number,h:number,rotation:number}[]} | null} */
let loaded = null;
/** @type {{page: number, x: number, y: number, w: number, h: number}[]} */
let rects = [];
const proofLiveText = document.getElementById("proofLiveText");
let requestsSinceLoad = 0;
if ("PerformanceObserver" in window) {
try {
new PerformanceObserver((list) => {
requestsSinceLoad += list.getEntries().length;
if (proofLiveText) {
proofLiveText.textContent = `${requestsSinceLoad} network request${
requestsSinceLoad === 1 ? "" : "s"
} since page load · verified live, not our word for it`;
}
}).observe({ type: "resource", buffered: false });
} catch (e) {
// observer unsupported — static claim stays as-is
}
}
function formatSize(bytes) {
if (bytes < 1024) return `${bytes} B`;
const kb = bytes / 1024;
if (Math.round(kb) < 1024) return `${kb.toFixed(0)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function escapeHtml(str) {
const div = document.createElement("div");
div.textContent = str;
return div.innerHTML.replace(/"/g, """).replace(/'/g, "'");
}
function renderFile() {
fileListEl.innerHTML = "";
if (!loaded) return;
const li = document.createElement("li");
li.className = "file-row";
li.innerHTML = `
<span class="handle" aria-hidden="true">◆</span>
<span class="name">${escapeHtml(loaded.file.name)} — ${loaded.pageCount} page${loaded.pageCount === 1 ? "" : "s"}</span>
<span class="size">${formatSize(loaded.file.size)}</span>
`;
fileListEl.appendChild(li);
}
function renderRects() {
rectListEl.innerHTML = "";
rects.forEach((r, i) => {
const li = document.createElement("li");
li.className = "file-row";
li.innerHTML = `
<span class="handle" aria-hidden="true">▪</span>
<span class="name">Page ${r.page} — x:${r.x}, y:${r.y}, w:${r.w}, h:${r.h} pt</span>
<button class="remove" type="button" data-idx="${i}" aria-label="Remove area on page ${r.page} (x:${r.x}, y:${r.y})">✕</button>
`;
rectListEl.appendChild(li);
});
redactBtn.disabled = rects.length === 0;
}
rectListEl.addEventListener("click", (e) => {
const btn = e.target.closest("button[data-idx]");
if (!btn) return;
const i = parseInt(btn.dataset.idx, 10);
rects.splice(i, 1);
renderRects();
const nextIndex = Math.min(i, rects.length - 1);
const nextBtn = rectListEl.querySelector(`button[data-idx="${nextIndex}"]`);
(nextBtn || addRectBtn)?.focus();
});
function updatePageSizeHint() {
if (!loaded) return;
const p = parseInt(pageInput.value, 10);
const size = loaded.pageSizes[p - 1];
pageSizeHint.textContent = size
? `Page ${p} is ${Math.round(size.w)} × ${Math.round(size.h)} pt (origin bottom-left).` +
(size.rotation !== 0
? ` Note: this page has a ${size.rotation}° rotation flag — these coordinates are in the page's underlying, unrotated space and may not line up with what you see in a viewer.`
: "")
: `Page number out of range (1–${loaded.pageCount}).`;
}
pageInput.addEventListener("input", updatePageSizeHint);
function updateActions() {
actionsEl.hidden = !loaded;
redactPanel.hidden = !loaded;
resultEl.hidden = true;
rects = [];
renderRects();
if (!loaded) return;
redactMeta.textContent = `${loaded.pageCount} page${loaded.pageCount === 1 ? "" : "s"} detected`;
pageInput.value = "1";
updatePageSizeHint();
}
async function loadFile(file) {
try {
const bytes = await file.arrayBuffer();
const doc = await PDFDocument.load(bytes, { ignoreEncryption: true });
const pageSizes = doc.getPages().map((p) => {
const box = p.getMediaBox();
return {
w: box.width,
h: box.height,
x: box.x,
y: box.y,
rotation: ((p.getRotation().angle % 360) + 360) % 360,
};
});
loaded = { file, pageCount: doc.getPageCount(), pageSizes };
renderFile();
updateActions();
} catch (err) {
loaded = null;
fileInput.value = "";
renderFile();
updateActions();
resultEl.hidden = false;
resultEl.className = "result result-error";
resultEl.setAttribute("role", "alert");
resultEl.setAttribute("aria-live", "assertive");
resultEl.innerHTML = `<span><strong>Couldn't load file.</strong> ${escapeHtml(
"This file may be corrupted or password-protected."
)}</span>`;
}
}
dropzone.addEventListener("click", () => fileInput.click());
dropzone.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
fileInput.click();
}
});
fileInput.addEventListener("change", (e) => {
const file = e.target.files[0];
if (file) loadFile(file);
});
["dragenter", "dragover"].forEach((evt) =>
dropzone.addEventListener(evt, (e) => {
e.preventDefault();
dropzone.classList.add("dragover");
})
);
["dragleave", "drop"].forEach((evt) =>
dropzone.addEventListener(evt, (e) => {
e.preventDefault();
dropzone.classList.remove("dragover");
})
);
dropzone.addEventListener("drop", (e) => {
const file = e.dataTransfer?.files?.[0];
if (file) loadFile(file);
});
clearBtn.addEventListener("click", () => {
loaded = null;
fileInput.value = "";
renderFile();
updateActions();
});
addRectBtn.addEventListener("click", () => {
if (!loaded) return;
const page = parseInt(pageInput.value, 10);
const x = parseFloat(xInput.value);
const y = parseFloat(yInput.value);
const w = parseFloat(wInput.value);
const h = parseFloat(hInput.value);
if (!Number.isFinite(page) || page < 1 || page > loaded.pageCount) {
return showError(`Page must be between 1 and ${loaded.pageCount}.`);
}
if (![x, y, w, h].every(Number.isFinite) || w <= 0 || h <= 0) {
return showError("x, y, width, and height must be numbers, with width and height greater than 0.");
}
const size = loaded.pageSizes[page - 1];
if (x < 0 || y < 0 || x + w > size.w || y + h > size.h) {
return showError(
`That area falls outside page ${page} (${Math.round(size.w)} × ${Math.round(size.h)} pt). Check x, y, width, and height against the page size shown above.`
);
}
rects.push({ page, x, y, w, h });
renderRects();
});
function showError(message) {
resultEl.hidden = false;
resultEl.className = "result result-error";
resultEl.setAttribute("role", "alert");
resultEl.setAttribute("aria-live", "assertive");
resultEl.innerHTML = `<span><strong>Couldn't add that area.</strong> ${escapeHtml(message)}</span>`;
}
function baseName(fileName) {
return fileName.replace(/\.pdf$/i, "");
}
async function redactPdf() {
const src = await PDFDocument.load(await loaded.file.arrayBuffer(), { ignoreEncryption: true });
const byPage = new Map();
for (const r of rects) {
const idx = r.page - 1;
// User-entered x/y are relative to the page's visible bottom-left corner (as shown
// in the page-size hint), but pdf-lib's drawing/content-stream coordinates are in
// absolute PDF user space. For a PDF whose MediaBox has a non-zero origin (common in
// scanned or print-production files), these differ — offset by the box's own x/y so
// the redacted rectangle (and the text it removes) lands where the user intended.
const { x: boxX, y: boxY } = loaded.pageSizes[idx];
if (!byPage.has(idx)) byPage.set(idx, []);
byPage.get(idx).push([r.x + boxX, r.y + boxY, r.x + r.w + boxX, r.y + r.h + boxY]);
}
let totalRemoved = 0;
for (const [pageIndex, pageRects] of byPage.entries()) {
const page = src.getPage(pageIndex);
const contentsField = page.node.Contents();
const refs = contentsField.array ? contentsField.array : [contentsField];
let combined = "";
for (const ref of refs) {
const streamObj = src.context.lookup(ref);
combined += new TextDecoder("latin1").decode(decodePDFRawStream(streamObj).decode()) + "\n";
}
const { text, removedCount } = redactContentStream(combined, pageRects);
totalRemoved += removedCount;
const encodedBytes = Uint8Array.from([...text].map((c) => c.charCodeAt(0)));
const dict = src.context.obj({ Length: encodedBytes.length });
const newStream = PDFRawStream.of(dict, encodedBytes);
const newRef = src.context.register(newStream);
page.node.set(PDFName.of("Contents"), newRef);
for (const [x0, y0, x1, y1] of pageRects) {
page.drawRectangle({
x: x0,
y: y0,
width: x1 - x0,
height: y1 - y0,
color: rgb(0, 0, 0),
});
}
}
const bytes = await src.save();
return {
blob: new Blob([bytes], { type: "application/pdf" }),
fileName: `${baseName(loaded.file.name)}-redacted.pdf`,
areaCount: rects.length,
removedCount: totalRemoved,
};
}
redactBtn.addEventListener("click", async () => {
redactBtn.disabled = true;
const originalLabel = redactBtnLabel.textContent;
redactBtnLabel.textContent = "Redacting…";
resultEl.hidden = true;
const startedAt = performance.now();
const requestsBefore = requestsSinceLoad;
try {
const { blob, fileName, areaCount, removedCount } = await redactPdf();
const url = URL.createObjectURL(blob);
setTimeout(() => URL.revokeObjectURL(url), 30000);
const elapsedMs = Math.round(performance.now() - startedAt);
const requestsDuring = requestsSinceLoad - requestsBefore;
resultEl.hidden = false;
resultEl.className = "result";
resultEl.setAttribute("role", "status");
resultEl.setAttribute("aria-live", "polite");
resultEl.innerHTML = `
<span><strong>Done.</strong> ${areaCount} area${areaCount === 1 ? "" : "s"} redacted
(${removedCount} text run${removedCount === 1 ? "" : "s"} removed from the file, plus black boxes drawn) —
${elapsedMs}ms, ${requestsDuring} network requests, entirely on this device.</span>
<a class="btn btn-primary" href="${url}" download="${escapeHtml(fileName)}">Download ${escapeHtml(fileName)}</a>
`;
} catch (err) {
resultEl.hidden = false;
resultEl.className = "result result-error";
resultEl.setAttribute("role", "alert");
resultEl.setAttribute("aria-live", "assertive");
resultEl.innerHTML = `<span><strong>Redaction failed.</strong> ${escapeHtml(
"This file may be corrupted or password-protected."
)}</span>`;
} finally {
redactBtn.disabled = rects.length === 0;
redactBtn.focus();
redactBtnLabel.textContent = originalLabel;
}
});
const proForm = document.getElementById("proForm");
const proNote = document.getElementById("proNote");
proForm.addEventListener("submit", async (e) => {
e.preventDefault();
const email = document.getElementById("proEmail").value.trim();
if (!email) return;
const proSubmitBtn = proForm.querySelector('button[type="submit"]');
proSubmitBtn.disabled = true;
const saved = JSON.parse(localStorage.getItem("clientpdf_waitlist") || "[]");
saved.push({ email, at: new Date().toISOString() });
localStorage.setItem("clientpdf_waitlist", JSON.stringify(saved));
try {
await fetch("https://formsubmit.co/ajax/analytics@antikode.com", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({
email,
_subject: "ClientPDF Pro waitlist signup",
source: location.pathname,
}),
});
} catch (err) {
// Local copy above already preserves the signup even if this fails.
}
proForm.hidden = true;
proNote.hidden = false;
});