-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentScript.js
More file actions
496 lines (449 loc) · 15.6 KB
/
contentScript.js
File metadata and controls
496 lines (449 loc) · 15.6 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
// FACT HANDLING
let trackedFacts = new Set();
let formFacts = new Set();
let rawFacts = undefined;
let factDict;
let debug = function () {};
let history = [];
// Load debug state
chrome.storage.local.get("isDebug", (data) => {
const isDebug = data.isDebug || false;
if (data.isDebug) debug = console.log.bind(window.console);
else debug = function () {};
});
// Set debug state
const setDebug = (isDebug) => {
if (isDebug) debug = console.log.bind(window.console);
else debug = function () {};
window.postMessage({ type: "CONTENT_TOGGLE_PAGE_DEBUG", isDebug }, "*");
chrome.storage.local.set({ isDebug });
};
// Listen for messages from popup.js and background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
debug("Received message", message);
if (message.action === "refreshValues") {
debug("Received refreshValues message from popup");
loadFacts();
sendResponse({ status: "Refreshing values" });
}
// TOGGLE DEBUG
if (message.action === "BG_TOGGLE_DEBUG") {
console.log(
"Toggling flamingo debug msgs ",
message.isDebug ? "on" : "off"
);
setDebug(message.isDebug);
}
if (message.action === "PP_LOAD_FACT_GRAPH") {
window.postMessage(
{ type: "CONTENT_REQ_FACTGRAPH", factGraph: message.factgraph },
"*"
);
sendResponse({ status: "Requested reload" });
}
// TOGGLE DEBUG
if (message.action === "LOG_MESSAGE") {
console.log(
`${message.source} Log: ${message.message}`
);
setDebug(message.isDebug);
}
});
// Listen for fact values sent back from the page script
window.addEventListener("message", function (event) {
// Check if the message is from the correct origin and contains fact data
// RETURN FACT
if (event.source === window && event.data.type === "PAGE_FACT_VALUE") {
debug("CS: Received message", event.data.type, event.data);
const { factName, id, value, complete, status } = event.data;
updateFactOnPage(factName, event.data);
}
// RETURN DICT
if (event.source === window && event.data.type === "PAGE_FACT_DICT") {
debug("CS: Received message", event.data.type);
factDict = event.data.debugFacts.map((fact) => {
return {
factName:
fact.Lgov_irs_factgraph_definitions_fact_FactConfigElement__f_path,
};
});
factDict.forEach(
(t) => (t.factNamePrepared = fuzzysort.prepare(t.factName))
);
factDict = factDict.map((t) => t.factNamePrepared);
}
// ADD FACT
if (event.source === window && event.data.type === "PAGE_ADD_FACT") {
debug("CS: Received message", event.data.type, event.data);
trackFact(event.data.factName.trim(), event.data.persist);
}
// PAGE SCRIPT READY
if (event.source === window && event.data.type === "PAGE_SCRIPT_READY") {
debug("CS: Received message", event.data.type);
loadFacts();
}
// CLEAR FACTS
if (event.source === window && event.data.type === "PAGE_CLEAR_FACTS") {
debug("CS: Received message", event.data.type);
clearFacts(event.data.which);
}
// FACT GRAPH
if (event.source === window && event.data.type === "PAGE_FACT_GRAPH") {
debug("CS: Received message", event.data.type, event.data);
// TODO move history add to an onchanged listener
factGraphJSON = event.data.factGraph;
factGraph = JSON.parse(factGraphJSON);
addHistory(factGraphJSON, event.data.url);
chrome.storage.local.set({ factGraph }, () => {
// debug("factGraph stored to local storage", factGraph)
populateHotLinks(factGraph);
});
}
// PAGE RAW FACTS
if (event.source === window && event.data.type === "PAGE_RAW_FACTS") {
debug("CS: Received message", event.data.type, event.data);
rawFacts = event.data.rawFacts;
if (rawFacts) {
telescopeEnable(true);
} else {
telescopeEnable(false);
}
chrome.storage.local.set({ rawFacts }, () => {
debug("rawFacts stored to local storage ", {rawFacts});
});
}
});
// ON LOAD
// Inject the page script
const script = document.createElement("script");
script.src = chrome.runtime.getURL("pageScript.js");
(document.head || document.documentElement).appendChild(script);
// Refresh all facts when any button on the page is clicked
document.addEventListener("click", (event) => {
if (event.target.classList.contains("delete-btn")) {
debug("Deleting fact", event.target.closest("tr").dataset.fact);
removeRow(event.target);
}
if (event.target.classList.contains("copy-btn")) {
debug("Copying fact", event.target.closest("tr").dataset.fact);
copyFact(event.target);
}
if (event.target.classList.contains("persist-btn")) {
debug("Persisting fact", event.target.closest("tr").dataset.fact);
persistFact(event.target);
}
if (event.target.classList.contains("telescope-btn")) {
debug("Telescoping fact", event.target.closest("tr").dataset.fact);
handleTelescopeFact(event.target);
}
if (event.target.tagName === "BUTTON") {
debug("Refreshing facts");
refreshValues();
}
});
// Function to update the UI with the fact value
function updateFactOnPage(factName, data) {
const { complete, value, status } = data;
const fail = status === "FAIL";
// Clean data
let cleanedValue = value || "--";
let match =
typeof value === "string" && value.match(/Enum\(Some\(([^)]*)\),.*\)/);
if (match) {
cleanedValue = match[1];
}
match = typeof value === "string" && value.match(/Collection\(Vector\(([^)]*)\)\)/);
if (match) {
cleanedValue = `Collection[${match[1]}]`;
}
const completeSvg = chrome.runtime.getURL("assets/circle-dot-filled.svg");
const incompleteSvg = chrome.runtime.getURL("assets/circle-dashed.svg");
const failSvg = chrome.runtime.getURL("assets/circle-off.svg");
const iconImg = document.createElement("img");
iconImg.src = complete ? completeSvg : fail ? failSvg : incompleteSvg;
const statusString = complete ? "Complete" : fail ? "Error" : "Incomplete";
iconImg.alt = statusString;
iconImg.title = statusString;
iconImg.classList.add(complete ? "svg-green" : fail ? "svg-red" : "svg-gray");
iconImg.classList.add("icon-img");
const statusCells = document.querySelectorAll(`[data-fact='${factName}'] .status`);
statusCells.forEach((cell) => {
cell.innerHTML = "";
cell.appendChild(iconImg.cloneNode());
cell.parentElement.classList.add(statusString.toLowerCase());
});
const tableValues = document.querySelectorAll(`[data-fact='${factName}'] .value`);
tableValues.forEach((valueSpan) => {
valueSpan.closest('tr').classList.add(statusString.toLowerCase());
valueSpan.innerHTML = "";
valueSpan.appendChild(iconImg.cloneNode());
valueSpan.appendChild(document.createTextNode(cleanedValue));
if (complete) {
valueSpan.classList.add("complete");
} else {
valueSpan.classList.remove("complete");
}
});
updateTelescopeFacts(factName, cleanedValue, complete, iconImg);
}
function saveFacts() {
chrome.storage.local.set({ trackedFacts: Array.from(trackedFacts) }, () => {
debug("trackedFacts saved to local storage", trackedFacts);
});
}
function loadFacts() {
chrome.storage.local.get("trackedFacts", (data) => {
debug("Loading facts from local storage", data.trackedFacts);
trackedFacts = new Set(data.trackedFacts || []);
// Add facts to the UI
trackedFacts.forEach((fact) => {
addFactRow(fact, true); // Add stored facts
});
});
}
// Initialize the UI
const container = injectUI();
// Load history
chrome.storage.local.get("history", (data) => {
history = data.history || [];
createHistory(history);
});
chrome.storage.onChanged.addListener((changes, local) => {
if (changes.factGraph) {
debug("storage:factGraph changed", changes);
populateHotLinks(factGraph);
}
});
// Add listeners
const hotLinkSelect = document.getElementById("hotlink-select");
if (hotLinkSelect) {
hotLinkSelect.addEventListener("change", (e) => {
const link = e.target.value;
if (link) {
window.location.href = link;
}
});
}
const factInput = document.getElementById("fact-input");
if (factInput) {
factInput.addEventListener("input", (e) => {
const factSuggestions = document.getElementById("fact-suggestions");
if (!factDict) {
// the first time request the dictionary
window.postMessage({ type: "CONTENT_REQ_DICT" }, "*");
} else {
const options = {
limit: 20,
threshold: 0.5,
};
const results = fuzzysort.go(e.target.value, factDict, options);
factSuggestions.innerHTML = "";
results.slice(0, 10).forEach((result) => {
const option = document.createElement("option");
option.value = result.target;
factSuggestions.appendChild(option);
});
}
});
// Fact Input Event Listeners
factInput.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
let factName = this.value;
// if the format is weird pick the first suggestion?
const factSuggestions = document.getElementById("fact-suggestions");
if (!factName.match(/\/[a-zA-Z0-9\*]*/)) {
this.value = factSuggestions.options[0].value;
factName = this.value;
}
if (!factName.includes("*")) {
trackFact(factName, true);
this.value = ""; // Clear the input after sending
} else {
const collectionIdInput = document.getElementById(
"collection-id-input"
);
collectionIdInput.focus();
}
}
});
}
function addFact() {
let factPath = document.getElementById("fact-input").value;
const collectionId = document.getElementById("collection-id-input").value;
if (factPath) {
if (factPath.includes("*") && collectionId) {
factPath = factPath.replace("*", collectionId);
}
trackFact(factPath, true);
}
}
// This function adds a fact the persisted list
// and adds a row to the table.
function trackFact(factName, persist) {
factName = factName.trim();
if (persist) {
trackedFacts.add(factName);
saveFacts();
} else {
formFacts.add(factName);
}
addFactRow(factName, persist);
}
// This function adds a fact to the persisted list
function persistFact(persistBtn) {
const row = persistBtn.closest("tr");
const concreteFactName = row.dataset.fact;
trackFact(concreteFactName, true);
}
function truncateFactNameInTable(factName) {
const MAX_LENGTH = 65
const TRUNCATED_PART = 30
if (factName.length > MAX_LENGTH) {
return factName.substring(0, TRUNCATED_PART) + "..." + factName.substring(factName.length - TRUNCATED_PART);
}
return factName;
}
// Add fact row to the table
function addFactRow(factName, persist) {
if (factName) {
const tbodyId = persist ? `track-facts` : `form-facts`;
// if not in table already
if (
document.getElementById(tbodyId) &&
!document.querySelector(`#facts-table #${tbodyId} [data-fact='${factName}']`)
) {
// Add it
const tbody = document.querySelector(`#facts-table #${tbodyId}`);
const row = document.createElement("tr");
row.setAttribute("data-fact", factName);
const deleteIcon = chrome.runtime.getURL("assets/trash-x.svg");
const copyIcon = chrome.runtime.getURL("assets/copy.svg");
const persistIcon = chrome.runtime.getURL(
"assets/square-rounded-plus.svg"
);
const telescopeIcon = chrome.runtime.getURL("assets/eye-spark.svg");
let rowContent = `
<td class="fact-name" title="${factName}">${truncateFactNameInTable(factName)}</td>
<td class="fact-value"><span class="value">?</span></td>
<td>
<div class="fact-actions">
<button class="usa-button usa-button--unstyled"><img class="copy-btn" src="${copyIcon}" title="Copy factname" alt="copy"></button>`;
if (rawFacts) {
rowContent += `<button class="usa-button usa-button--unstyled"><img class="telescope-btn" src="${telescopeIcon}" title="Telescope factname" alt="telescope"></button>`;
}
if (persist) {
rowContent += `<button class="usa-button usa-button--unstyled"><img class="delete-btn" src="${deleteIcon}" title="Stop monitoring fact" alt="delete"></button>`;
} else {
rowContent += `<button class="usa-button usa-button--unstyled"><img class="persist-btn" src="${persistIcon}" title="Monitor fact" alt="monitor"></button>`;
}
rowContent += `</div></td>`;
row.innerHTML = rowContent;
tbody.appendChild(row);
}
// Ask the page script to fetch the value for this fact
// Requesting fact from page script
// debug("Requesting fact from page script", factName)
window.postMessage({ type: "CONTENT_REQ_FACT", factName }, "*");
}
}
// Clear facts
function clearFacts(type) {
const tbody = document.querySelector("#facts-table #track-facts");
if (!tbody) {
return;
}
if (type === "TRACKED") {
trackedFacts = new Set();
saveFacts();
tbody.innerHTML = "";
} else if (type === "TEMP") {
formFacts = new Set();
emptyTempTable();
} else if (type === "ERROR") {
const errorRows = document.querySelectorAll("#facts-table #track-facts tr.error");
errorRows.forEach((row) => {
removeRow(row.querySelector("button img.delete-btn"));
});
}
}
function refreshValues() {
trackedFacts.forEach((factName) => {
window.postMessage({ type: "CONTENT_REQ_FACT", factName }, "*");
});
}
// Remove a row from the tracked facts table
function removeRow(deleteBtn) {
const row = deleteBtn.closest("tr");
const concreteFactName = row.dataset.fact;
// Delete button is only on the tracked facts table
if (row) {
row.remove();
trackedFacts.delete(concreteFactName);
saveFacts();
}
}
function extractCollectionId(factName) {
const uuidRegex =
/#[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/;
const match = factName.match(uuidRegex);
if (match) {
factName = factName.replace(uuidRegex, "*");
return { collectionId: match[0], factName: factName };
}
return { collectionId: null, factName: factName };
}
function copyFact(copyBtn) {
const row = copyBtn.closest("tr");
const concreteFactName = row.dataset.fact;
// Split out the collection id from the fact name to populate the input fields
navigator.clipboard.writeText(concreteFactName);
const { collectionId, factName } = extractCollectionId(concreteFactName);
const factInput = document.getElementById("fact-input");
const collectionIdInput = document.getElementById("collection-id-input");
if (factInput) {
factInput.value = factName;
}
if (collectionIdInput) {
collectionIdInput.value = collectionId || "";
}
}
function addHistory(factGraph, url) {
const currentTime = new Date().toISOString();
history.push({
timestamp: currentTime,
factGraph: factGraph,
url: url,
});
// Optionally, you might want to limit the history size
if (history.length > 50) {
history.shift(); // Remove the oldest entry if we have more than 50
}
chrome.storage.local.set({ history });
createHistory(history);
// debug("Added to history:", { timestamp: currentTime, url: url });
}
function clearHistory() {
history = [];
chrome.storage.local.set({ history }, () => {
debug("history cleared");
});
createHistory(history);
}
function rewindTo(index) {
const factGraph = history[index].factGraph;
history = history.slice(0, index + 1);
chrome.storage.local.set({ history }, () => {
debug("history rewound to", history.at(-1).timestamp);
});
window.postMessage(
{
type: "CONTENT_REQ_FACTGRAPH",
factGraph: history[index].factGraph,
url: history[index].url,
},
"*"
);
}
if (typeof module !== 'undefined') {
module.exports = { updateFactOnPage, addFactRow, clearFacts, removeRow, copyFact, extractCollectionId, addHistory, clearHistory, rewindTo, refreshValues };
}