mirror of
https://github.com/sharevb/it-tools.git
synced 2026-12-04 18:35:09 +03:00
feat(new tool): HTML to XHTML
This commit is contained in:
1 parent
ebad961241
commit
7ba56bf81b
6 files changed
+290
No files matched your search
@@ -0,0 +1,110 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { toStrictXhtml } from './html-to-xhtml.service';
|
||||
|
||||
describe('toStrictXhtml', () => {
|
||||
it('self-closes all void elements', () => {
|
||||
const html = `
|
||||
<img src="a.png">
|
||||
<br>
|
||||
<hr>
|
||||
<input disabled>
|
||||
<meta charset="utf-8">
|
||||
<source src="x.mp4">
|
||||
<track kind="captions">
|
||||
<area href="#">
|
||||
<base href="/">
|
||||
<col>
|
||||
<embed src="x">
|
||||
<param name="p" value="v">
|
||||
<wbr>
|
||||
`;
|
||||
|
||||
const out = toStrictXhtml(html);
|
||||
|
||||
const expected = [
|
||||
'<img src="a.png" />',
|
||||
'<br />',
|
||||
'<hr />',
|
||||
'<input disabled="disabled" />',
|
||||
'<meta charset="utf-8" />',
|
||||
'<source src="x.mp4" />',
|
||||
'<track kind="captions" />',
|
||||
'<area href="#" />',
|
||||
'<base href="/" />',
|
||||
'<col />',
|
||||
'<embed src="x" />',
|
||||
'<param name="p" value="v" />',
|
||||
'<wbr />',
|
||||
];
|
||||
|
||||
for (const line of expected) {
|
||||
expect(out).toContain(line);
|
||||
}
|
||||
});
|
||||
|
||||
it('injects namespace on root element when requested', () => {
|
||||
const html = '<html><body><p>Hello</p></body></html>';
|
||||
|
||||
const out = toStrictXhtml(html, {
|
||||
addNamespace: true,
|
||||
});
|
||||
|
||||
expect(out).toContain('<html xmlns="http://www.w3.org/1999/xhtml">');
|
||||
});
|
||||
|
||||
it('applies indentation when indent option is provided', () => {
|
||||
const html = '<div><p>Hello</p></div>';
|
||||
|
||||
const out = toStrictXhtml(html, { indent: 2 });
|
||||
|
||||
expect(out).toBe(
|
||||
`<div>
|
||||
<p>
|
||||
Hello
|
||||
</p>
|
||||
</div>`,
|
||||
);
|
||||
});
|
||||
|
||||
it('escapes XML entities in text and attributes', () => {
|
||||
const html = '<p title="5 > 3 & 2 < 4">5 > 3 & 2 < 4</p>';
|
||||
|
||||
const out = toStrictXhtml(html);
|
||||
|
||||
expect(out).toContain('title="5 > 3 & 2 < 4"');
|
||||
expect(out).toContain('5 > 3 & 2 < 4');
|
||||
});
|
||||
|
||||
it('lowercases tag and attribute names', () => {
|
||||
const html = '<DIV CLASS="X"><IMG SRC="A.PNG"></DIV>';
|
||||
|
||||
const out = toStrictXhtml(html);
|
||||
|
||||
expect(out).toContain('<div class="X">');
|
||||
expect(out).toContain('<img src="A.PNG" />');
|
||||
});
|
||||
|
||||
it('serializes comments correctly', () => {
|
||||
const html = '<div><!-- Test Comment --></div>';
|
||||
|
||||
const out = toStrictXhtml(html);
|
||||
expect(out).toContain('<!-- Test Comment -->');
|
||||
});
|
||||
|
||||
it('handles nested structures deterministically', () => {
|
||||
const html = '<ul><li>One</li><li>Two</li></ul>';
|
||||
|
||||
const out = toStrictXhtml(html, { indent: 2 });
|
||||
|
||||
expect(out).toBe(
|
||||
`<ul>
|
||||
<li>
|
||||
One
|
||||
</li>
|
||||
<li>
|
||||
Two
|
||||
</li>
|
||||
</ul>`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { DomUtils, parseDocument } from 'htmlparser2';
|
||||
|
||||
export interface XhtmlOptions {
|
||||
addNamespace?: boolean // add http://www.w3.org/1999/xhtml
|
||||
indent?: number // number of spaces per indent level
|
||||
}
|
||||
|
||||
export function toStrictXhtml(html: string, options: XhtmlOptions = {}): string {
|
||||
// FULL canonical void element list
|
||||
const voidElements = new Set([
|
||||
'area', 'base', 'br', 'col', 'embed', 'hr', 'img',
|
||||
'input', 'link', 'meta', 'param', 'source', 'track', 'wbr',
|
||||
]);
|
||||
|
||||
const escapeXml = (value: string) =>
|
||||
value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
|
||||
const indentSize = options.indent ?? 0;
|
||||
const indentStr = (level: number) =>
|
||||
indentSize > 0 ? ' '.repeat(level * indentSize) : '';
|
||||
|
||||
const serialize = (node: any, level = 0): string => {
|
||||
if (DomUtils.isText(node)) {
|
||||
const text = escapeXml(node.data);
|
||||
return indentSize > 0 ? indentStr(level) + text : text;
|
||||
}
|
||||
|
||||
if (DomUtils.isComment(node)) {
|
||||
const comment = `<!--${escapeXml(node.data)}-->`;
|
||||
return indentSize > 0 ? indentStr(level) + comment : comment;
|
||||
}
|
||||
|
||||
if (DomUtils.isTag(node)) {
|
||||
const tag = node.name.toLowerCase();
|
||||
|
||||
// Attributes
|
||||
const attrsObj = { ...(node.attribs || {}) };
|
||||
|
||||
// Inject namespace on root element if requested
|
||||
if (options.addNamespace && node.parent?.type === 'root') {
|
||||
attrsObj.xmlns = 'http://www.w3.org/1999/xhtml';
|
||||
}
|
||||
|
||||
const attrs = Object.entries(attrsObj)
|
||||
.map(([k, v]) => `${k.toLowerCase()}="${escapeXml(String(v || k.toLowerCase()))}"`)
|
||||
.join(' ');
|
||||
|
||||
const open = attrs ? `<${tag} ${attrs}` : `<${tag}`;
|
||||
|
||||
// VOID ELEMENT → self-close
|
||||
if (voidElements.has(tag)) {
|
||||
const line = `${open} />`;
|
||||
return indentSize > 0 ? indentStr(level) + line : line;
|
||||
}
|
||||
|
||||
// NORMAL ELEMENT
|
||||
const children = (node.children || [])
|
||||
.map(child => serialize(child, level + 1))
|
||||
.join(indentSize > 0 ? '\n' : '');
|
||||
|
||||
if (indentSize > 0) {
|
||||
if (children.trim().length === 0) {
|
||||
return `${indentStr(level)}${open}></${tag}>`;
|
||||
}
|
||||
return `${indentStr(level)}${open}>\n${children}\n${indentStr(level)}</${tag}>`;
|
||||
}
|
||||
|
||||
return `${open}>${children}</${tag}>`;
|
||||
}
|
||||
|
||||
return '';
|
||||
};
|
||||
|
||||
const doc = parseDocument(html);
|
||||
|
||||
return doc.children
|
||||
.map(node => serialize(node, 0))
|
||||
.join(indentSize > 0 ? '\n' : '');
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<script setup lang="ts">
|
||||
import { toStrictXhtml } from './html-to-xhtml.service';
|
||||
import TextareaCopyable from '@/components/TextareaCopyable.vue';
|
||||
|
||||
const inputHtml = ref('');
|
||||
const addNamespace = ref(false);
|
||||
const indentation = ref(2);
|
||||
const outputHtml = computed(() => {
|
||||
try {
|
||||
return toStrictXhtml(
|
||||
inputHtml.value,
|
||||
{
|
||||
addNamespace: addNamespace.value,
|
||||
indent: indentation.value,
|
||||
},
|
||||
);
|
||||
}
|
||||
catch (e: any) {
|
||||
return `<!-- ERROR: ${e.toString()} -->`;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<c-input-text
|
||||
v-model:value="inputHtml"
|
||||
multiline raw-text
|
||||
placeholder="Your HTML content..."
|
||||
rows="8"
|
||||
autofocus
|
||||
label="Your HTML to convert to XHTML:"
|
||||
paste-html
|
||||
mb-1
|
||||
/>
|
||||
|
||||
<n-space justify="center" mb-2>
|
||||
<n-form-item label="Add XHTML xmlns:" label-placement="left">
|
||||
<n-switch v-model:value="addNamespace" />
|
||||
</n-form-item>
|
||||
<n-form-item label="Indentation:" label-placement="left">
|
||||
<n-input-number v-model:value="indentation" :min="0" />
|
||||
</n-form-item>
|
||||
</n-space>
|
||||
|
||||
<c-card v-if="outputHtml" title="Output XHTML:">
|
||||
<TextareaCopyable
|
||||
:value="outputHtml"
|
||||
multiline
|
||||
language="html"
|
||||
:word-wrap="true"
|
||||
/>
|
||||
</c-card>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,13 @@
|
||||
import { BrandHtml5 } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: 'HTML to XHTML',
|
||||
path: '/html-to-xhtml',
|
||||
description: 'Convert HTML to strict XHTML (XML parsable, self closing tags...)',
|
||||
keywords: ['html', 'xhtml'],
|
||||
component: () => import('./html-to-xhtml.vue'),
|
||||
icon: BrandHtml5,
|
||||
createdAt: new Date('2026-01-03'),
|
||||
category: 'Web',
|
||||
});
|
||||
Reference in new issue
Block a user