-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml-formatter.html
More file actions
376 lines (321 loc) · 14 KB
/
html-formatter.html
File metadata and controls
376 lines (321 loc) · 14 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Formatter</title>
<link rel="stylesheet" href="common.css">
<style>
body { display: flex; flex-direction: column; }
.options { display: flex; gap: 16px; align-items: center; flex-wrap: wrap; }
</style>
</head>
<body>
<a href="index.html" class="back-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M19 12H5M12 19l-7-7 7-7"/>
</svg>
All Tools
</a>
<header>
<h1>HTML Formatter</h1>
<p class="subtitle">Pretty print or minify HTML</p>
</header>
<div class="controls">
<button id="formatBtn">Format</button>
<button id="minifyBtn">Minify</button>
<button id="clearBtn" class="secondary">Clear</button>
<div class="options">
<div class="option-group">
<label for="indentSelect">Indent:</label>
<select id="indentSelect">
<option value="2">2 spaces</option>
<option value="4">4 spaces</option>
<option value="tab">Tab</option>
</select>
</div>
</div>
</div>
<div class="container">
<div class="pane">
<div class="pane-header">
<span class="label">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
</svg>
Input
<span id="statusIndicator" class="status-indicator"></span>
</span>
</div>
<textarea id="inputArea" placeholder='Paste your HTML here...
Example:
<div><p>Hello</p><span>World</span></div>' spellcheck="false"></textarea>
<div id="errorMessage" class="error-message"></div>
</div>
<div class="pane">
<div class="pane-header">
<span class="label">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
</svg>
Output
</span>
<button id="copyBtn" class="copy-btn">Copy</button>
</div>
<textarea id="outputArea" readonly placeholder="Formatted HTML will appear here..." spellcheck="false"></textarea>
</div>
</div>
<script>
const inputArea = document.getElementById('inputArea');
const outputArea = document.getElementById('outputArea');
const formatBtn = document.getElementById('formatBtn');
const minifyBtn = document.getElementById('minifyBtn');
const clearBtn = document.getElementById('clearBtn');
const copyBtn = document.getElementById('copyBtn');
const indentSelect = document.getElementById('indentSelect');
const errorMessage = document.getElementById('errorMessage');
const statusIndicator = document.getElementById('statusIndicator');
// Void elements that don't have closing tags
const voidElements = new Set([
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
'link', 'meta', 'param', 'source', 'track', 'wbr'
]);
// Elements that should preserve whitespace
const preserveWhitespaceElements = new Set(['pre', 'code', 'textarea', 'script', 'style']);
// Inline elements that shouldn't add newlines
const inlineElements = new Set([
'a', 'abbr', 'acronym', 'b', 'bdo', 'big', 'br', 'button', 'cite',
'code', 'dfn', 'em', 'i', 'img', 'input', 'kbd', 'label', 'map',
'object', 'output', 'q', 'samp', 'select', 'small', 'span', 'strong',
'sub', 'sup', 'textarea', 'time', 'tt', 'var'
]);
function getIndent(indentValue) {
return indentValue === 'tab' ? '\t' : ' '.repeat(parseInt(indentValue, 10));
}
function formatNode(node, indent, level, preserveWS) {
const indentStr = indent.repeat(level);
let result = '';
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent;
if (preserveWS) {
return text;
}
const trimmed = text.trim();
if (!trimmed) return '';
return trimmed;
}
if (node.nodeType === Node.COMMENT_NODE) {
return `${indentStr}<!--${node.textContent}-->`;
}
if (node.nodeType === Node.DOCUMENT_TYPE_NODE) {
return `<!DOCTYPE ${node.name}>`;
}
if (node.nodeType !== Node.ELEMENT_NODE) {
return '';
}
const tagName = node.tagName.toLowerCase();
const isVoid = voidElements.has(tagName);
const shouldPreserveWS = preserveWhitespaceElements.has(tagName);
const isInline = inlineElements.has(tagName);
// Build opening tag
let openTag = `<${tagName}`;
for (const attr of node.attributes) {
openTag += ` ${attr.name}="${attr.value.replace(/"/g, '"')}"`;
}
if (isVoid) {
return `${indentStr}${openTag}>`;
}
openTag += '>';
// Handle content
const children = Array.from(node.childNodes);
if (children.length === 0) {
return `${indentStr}${openTag}</${tagName}>`;
}
if (shouldPreserveWS) {
// Preserve whitespace for pre, code, etc.
let content = '';
for (const child of children) {
if (child.nodeType === Node.TEXT_NODE) {
content += child.textContent;
} else if (child.nodeType === Node.ELEMENT_NODE) {
content += formatNode(child, indent, 0, true);
}
}
return `${indentStr}${openTag}${content}</${tagName}>`;
}
// Check if content is simple (single text node or only inline elements with text)
const hasBlockChildren = children.some(child =>
child.nodeType === Node.ELEMENT_NODE && !inlineElements.has(child.tagName.toLowerCase())
);
const onlyTextAndInline = children.every(child =>
child.nodeType === Node.TEXT_NODE ||
(child.nodeType === Node.ELEMENT_NODE && inlineElements.has(child.tagName.toLowerCase()))
);
if (onlyTextAndInline && !hasBlockChildren) {
// Keep inline content on same line
let content = '';
for (const child of children) {
content += formatNode(child, indent, 0, false);
}
return `${indentStr}${openTag}${content}</${tagName}>`;
}
// Multi-line formatting for block content
result = `${indentStr}${openTag}\n`;
for (const child of children) {
const childResult = formatNode(child, indent, level + 1, false);
if (childResult) {
result += childResult + '\n';
}
}
result += `${indentStr}</${tagName}>`;
return result;
}
function formatHTML(html, indent) {
// Parse as HTML fragment
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Check for parsing errors in body
const errorNode = doc.querySelector('parsererror');
if (errorNode) {
throw new Error('Invalid HTML: ' + errorNode.textContent);
}
// Determine what to format
let result = '';
// Check if input has doctype or html/head/body
const hasFullDoc = html.trim().toLowerCase().startsWith('<!doctype') ||
html.trim().toLowerCase().startsWith('<html');
if (hasFullDoc) {
// Format full document
if (doc.doctype) {
result += formatNode(doc.doctype, indent, 0, false) + '\n';
}
result += formatNode(doc.documentElement, indent, 0, false);
} else {
// Format just the body content (fragment mode)
const body = doc.body;
const lines = [];
for (const child of body.childNodes) {
const formatted = formatNode(child, indent, 0, false);
if (formatted) {
lines.push(formatted);
}
}
result = lines.join('\n');
}
return result;
}
function minifyHTML(html) {
// Parse as HTML fragment
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
function minifyNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
const tagName = node.parentElement?.tagName.toLowerCase();
if (preserveWhitespaceElements.has(tagName)) {
return node.textContent;
}
return node.textContent.replace(/\s+/g, ' ').trim();
}
if (node.nodeType === Node.COMMENT_NODE) {
return `<!--${node.textContent}-->`;
}
if (node.nodeType === Node.DOCUMENT_TYPE_NODE) {
return `<!DOCTYPE ${node.name}>`;
}
if (node.nodeType !== Node.ELEMENT_NODE) {
return '';
}
const tagName = node.tagName.toLowerCase();
const isVoid = voidElements.has(tagName);
const shouldPreserveWS = preserveWhitespaceElements.has(tagName);
let openTag = `<${tagName}`;
for (const attr of node.attributes) {
openTag += ` ${attr.name}="${attr.value.replace(/"/g, '"')}"`;
}
openTag += '>';
if (isVoid) {
return openTag;
}
let content = '';
for (const child of node.childNodes) {
const minified = minifyNode(child);
if (shouldPreserveWS) {
content += minified;
} else if (minified) {
content += minified;
}
}
return `${openTag}${content}</${tagName}>`;
}
const hasFullDoc = html.trim().toLowerCase().startsWith('<!doctype') ||
html.trim().toLowerCase().startsWith('<html');
if (hasFullDoc) {
let result = '';
if (doc.doctype) {
result += minifyNode(doc.doctype);
}
result += minifyNode(doc.documentElement);
return result;
} else {
let result = '';
for (const child of doc.body.childNodes) {
result += minifyNode(child);
}
return result;
}
}
function format(minify = false) {
const input = inputArea.value.trim();
errorMessage.style.display = 'none';
statusIndicator.className = 'status-indicator';
if (!input) {
outputArea.value = '';
return;
}
try {
if (minify) {
outputArea.value = minifyHTML(input);
} else {
const indent = getIndent(indentSelect.value);
outputArea.value = formatHTML(input, indent);
}
statusIndicator.className = 'status-indicator valid';
} catch (e) {
errorMessage.style.display = 'block';
errorMessage.textContent = e.message;
outputArea.value = '';
statusIndicator.className = 'status-indicator invalid';
}
}
formatBtn.addEventListener('click', () => format(false));
minifyBtn.addEventListener('click', () => format(true));
// Auto-format on input
inputArea.addEventListener('input', () => format(false));
clearBtn.addEventListener('click', () => {
inputArea.value = '';
outputArea.value = '';
errorMessage.style.display = 'none';
statusIndicator.className = 'status-indicator';
inputArea.focus();
});
copyBtn.addEventListener('click', () => {
if (!outputArea.value) return;
navigator.clipboard.writeText(outputArea.value).then(() => {
const originalText = copyBtn.textContent;
copyBtn.textContent = 'Copied!';
copyBtn.classList.add('copied');
setTimeout(() => {
copyBtn.textContent = originalText;
copyBtn.classList.remove('copied');
}, 2000);
});
});
// Re-format when options change
indentSelect.addEventListener('change', () => format(false));
</script>
</body>
</html>