feat: add xml-formatter

This commit is contained in:
Nybkox
2025-02-27 15:55:06 +01:00
parent 1d02927f6b
commit 189b9a7ad6
4 changed files with 19 additions and 82 deletions

View File

@@ -1,14 +1,14 @@
<script>
import hljs from 'highlight.js/lib/core';
import xmlGrammar from './xmlGrammar';
import formatXml from './formatXml';
import xmlFormat from 'xml-formatter';
import { afterUpdate, onMount } from 'svelte';
import 'highlight.js/styles/vs.css';
export let code = '';
$: formattedCode = formatXml(code);
$: formattedCode = xmlFormat(code);
onMount(() => {
hljs.registerLanguage('xml', xmlGrammar);

View File

@@ -1,24 +0,0 @@
export default function formatXml(xml: string): string {
if (typeof xml !== 'string') return '';
xml = xml.replace(/>\s*</g, '><');
let formatted = '';
let indent = 0;
const tags = xml.split(/(<.*?>)/g).filter(s => s.trim());
for (let tag of tags) {
if (tag.startsWith('</')) {
indent--;
formatted += '\n' + ' '.repeat(indent) + tag;
} else if (tag.startsWith('<') && !tag.endsWith('/>') && !tag.startsWith('<?')) {
formatted += '\n' + ' '.repeat(indent) + tag;
indent++;
} else {
formatted += '\n' + ' '.repeat(indent) + tag;
}
}
return formatted.trim();
}