-
Notifications
You must be signed in to change notification settings - Fork 0
/
code-beautifier.js
91 lines (82 loc) · 3.6 KB
/
code-beautifier.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
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
// Code Beautifier for HTML, CSS and JavaScript
// developed by Tawhidur Rahman Dear, https://www.tawhidurrahmandear.com
// Live Preview available at https://www.devilhunter.net/p/code-beautifier.html
const getElement = (id) => document.getElementById(id);
const notify = (message, duration = 2000) => {
const notification = getElement('notification');
notification.textContent = message;
setTimeout(() => (notification.textContent = ''), duration);
};
const beautifyHTML = (html) => {
let formatted = '';
let indentLevel = 0;
const indentSize = ' ';
html.split(/>\s*</).forEach((element) => {
if (element.match(/^\/\w/)) {
indentLevel--;
formatted += `${indentSize.repeat(indentLevel)}<${element}>\n`;
} else if (element.match(/^<?\w[^>]*[^/]$/)) {
formatted += `${indentSize.repeat(indentLevel)}<${element}>\n`;
indentLevel++;
} else {
formatted += `${indentSize.repeat(indentLevel)}<${element}>\n`;
}
});
return formatted.trim();
};
const beautifyCSS = (css) =>
css
.replace(/\s+/g, ' ')
.replace(/;\s*/g, ';\n ')
.replace(/\{\s*/g, ' {\n ')
.replace(/\}\s*/g, '\n}\n')
.replace(/,\s*/g, ',\n ')
.trim();
const beautifyJS = (js) => {
let formatted = '';
let indentLevel = 0;
const indentSize = ' ';
js.split(/([{};])/).forEach((token) => {
token = token.trim();
if (token === '{') {
formatted += `${indentSize.repeat(indentLevel)}${token}\n`;
indentLevel++;
} else if (token === '}') {
indentLevel--;
formatted += `${indentSize.repeat(indentLevel)}${token}\n`;
} else if (token === ';') {
formatted += `${token}\n`;
} else if (token) {
formatted += `${indentSize.repeat(indentLevel)}${token}`;
}
});
return formatted.trim();
};
const beautifyCode = (type) => {
const inputCode = getElement('inputCode').value.trim();
if (!inputCode) {
notify('Please paste your code in the input box.', 3000);
return;
}
let outputCode = '';
if (type === 'html') outputCode = beautifyHTML(inputCode);
else if (type === 'css') outputCode = beautifyCSS(inputCode);
else if (type === 'js') outputCode = beautifyJS(inputCode);
getElement('outputCode').value = outputCode;
notify('Code beautified successfully!');
};
const clearAll = () => {
getElement('inputCode').value = '';
getElement('outputCode').value = '';
notify('We cleared all fields.');
};
const copyCode = () => {
const outputCode = getElement('outputCode').value;
if (!outputCode) {
notify('There is nothing to copy!', 3000);
return;
}
navigator.clipboard.writeText(outputCode)
.then(() => notify('Copied successfully ...'))
.catch(() => notify('Failed to copy!', 3000));
};