-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat-on-paste.js
56 lines (50 loc) · 1.6 KB
/
format-on-paste.js
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
document.addEventListener("paste", handleKeyboardEvent);
document.addEventListener("keydown", handleKeyboardEvent);
function handleKeyboardEvent(event) {
const cmdV = event.type === "paste";
const cmdF = event.code === "KeyF" && event.metaKey;
const cmdShiftV = event.code === "KeyV" && event.metaKey && event.shiftKey;
if (cmdV || cmdF || cmdShiftV) {
event.preventDefault();
navigator.clipboard.readText().then((clipText) => {
if (continueFormatting(clipText)) {
transformClipboard(document, navigator, clipText, cmdV);
}
});
}
}
function continueFormatting(clipText) {
try {
if (isValidJson(clipText)) {
console.log("Clipboard already contains a valid JSON object.");
return false;
}
return true;
} catch (e) {
console.error("Clipboard does not contain a valid JSON object.");
return false;
}
}
function isValidJson(jsonString) {
try {
const parsedObject = JSON.parse(jsonString);
return typeof parsedObject === "object" && !Array.isArray(parsedObject);
} catch (e) {
return false;
}
}
function transformClipboard(document, navigator, clipText, isPasteEvent) {
try {
const jsonFormat = JSON.stringify(eval("(" + clipText + ")"), null, 2);
navigator.clipboard.writeText(jsonFormat).then(function () {
if (jsonFormat) {
const finalText = isPasteEvent
? "\n\n⬆️Delete Above\n Converted JSON ⬇️\n\n" + jsonFormat
: jsonFormat;
document.activeElement.value = finalText;
}
});
} catch (e) {
console.error("Clipboard does not contain a valid JSON object.");
}
}