feat(xml-diff): add XML diff tool

Compare two pasted XML documents and highlight the differences, mirroring
the JSON diff tool's UI and diff engine. XML is parsed with a native
DOMParser-based normalizer (attributes as @name, text-only leaves as plain
strings) instead of xml-js, and a reconciliation step coerces mismatched
single/repeated element shapes into arrays before diffing so a repeated
element compares cleanly instead of producing a garbled type-mismatch diff.

From PR #1840

Co-Authored-By: @sharevb
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
authored and ShareVB committed 2026-11-22 18:55:30 +01:00
1 parent 5bbc672017
commit ace54204c5
9 files changed
+2601 -1955

No files matched your search

+2118 -1955
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,112 @@
<script lang="ts" setup>
import * as _ from 'es-toolkit/compat';
import { diff } from '../../json-diff/json-diff.models';
import { DiffRootViewer } from '../../json-diff/diff-viewer/diff-viewer.models';
import { reconcileArrayShapes } from '../xml-diff.reconcile';
import { useAppTheme } from '@/ui/theme/themes';
const props = defineProps<{ leftXml: unknown; rightXml: unknown }>();
const onlyShowDifferences = ref(false);
const { leftXml, rightXml } = toRefs(props);
const appTheme = useAppTheme();
const result = computed(() => {
const [reconciledLeftXml, reconciledRightXml] = reconcileArrayShapes(leftXml.value, rightXml.value);
return diff(reconciledLeftXml, reconciledRightXml, { onlyShowDifferences: onlyShowDifferences.value });
});
const xmlAreTheSame = computed(() => _.isEqual(leftXml.value, rightXml.value));
const showResults = computed(() => !_.isUndefined(leftXml.value) && !_.isUndefined(rightXml.value));
</script>
<template>
<div v-if="showResults">
<div flex justify-center>
<n-form-item label="Only show differences" label-placement="left">
<n-switch v-model:value="onlyShowDifferences" />
</n-form-item>
</div>
<c-card data-test-id="diff-result">
<div v-if="xmlAreTheSame" text-center op-70>The provided XMLs are the same</div>
<DiffRootViewer v-else :diff="result" />
</c-card>
</div>
</template>
<style lang="less" scoped>
::v-deep(.diffs-viewer) {
color: v-bind('appTheme.text.mutedColor');
& > ul {
padding-left: 0 !important;
}
ul {
list-style: none;
padding-left: 20px;
margin: 0;
li {
.updated-line {
padding: 3px 0;
}
.result,
.array,
.object,
.value {
&:not(:last-child) {
margin-right: 4px;
}
&.added {
padding: 3px 5px;
border-radius: 4px;
background-color: v-bind('appTheme.success.colorFaded');
color: v-bind('appTheme.success.color');
.key {
color: inherit;
}
}
&.removed {
padding: 3px 5px;
border-radius: 4px;
background-color: v-bind('appTheme.error.colorFaded');
color: v-bind('appTheme.error.color');
.key {
color: inherit;
}
}
}
.value {
cursor: pointer;
border: 1px solid transparent;
transition: border-color 0.2s ease-in-out;
&.added:hover {
border-color: v-bind('appTheme.success.color');
}
&.removed:hover {
border-color: v-bind('appTheme.error.color');
}
}
.added .added,
.removed .removed {
background-color: transparent;
color: inherit;
}
.key {
font-weight: 500;
color: v-bind('appTheme.text.baseColor');
}
}
}
}
</style>
+13
View File
@@ -0,0 +1,13 @@
import { defineTool } from '../tool';
import { translate as t } from '@/plugins/i18n.plugin';
export const tool = defineTool({
name: t('tools.xml-diff.title'),
path: '/xml-diff',
description: t('tools.xml-diff.description'),
keywords: ['xml', 'diff', 'compare', 'difference'],
component: () => import('./xml-diff.vue'),
icon: defineAsyncComponent(() => import('@vicons/material/es/CompareArrowsRound')),
createdAt: new Date('2026-11-22'),
category: 'XML',
});
+51
View File
@@ -0,0 +1,51 @@
import { expect, test } from '@playwright/test';
test.describe('Tool - XML diff', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/xml-diff');
});
test('Has correct title', async ({ page }) => {
await expect(page).toHaveTitle('XML diff - IT Tools');
});
test('Identical XMLs have a custom result message', async ({ page }) => {
await page.getByTestId('leftXml').fill('<foo><bar>baz</bar></foo>');
await page.getByTestId('rightXml').fill('<foo>\n <bar>baz</bar>\n</foo>');
const result = await page.getByTestId('diff-result').innerText();
expect(result).toContain('The provided XMLs are the same');
});
test('Different XMLs have differences listed', async ({ page }) => {
await page.getByTestId('leftXml').fill('<root foo="bar"/>');
await page.getByTestId('rightXml').fill('<root foo="buz" baz="qux"/>');
const result = await page.getByTestId('diff-result').innerText();
expect(result).toContain('{\n@foo: "bar""buz",\n@baz: "qux",\n},');
});
test('Different XMLs have only differences listed when "Only show differences" is checked', async ({ page }) => {
await page.getByTestId('leftXml').fill('<root foo="bar"/>');
await page.getByTestId('rightXml').fill('<root foo="bar" baz="qux"/>');
await page.getByRole('switch').click();
const result = await page.getByTestId('diff-result').innerText();
expect(result).toContain('{\n@baz: "qux",\n},');
expect(result).not.toContain('foo');
});
test('An element going from a single occurrence to several is diffed cleanly, not as a type change', async ({
page,
}) => {
await page.getByTestId('leftXml').fill('<root><item>A</item></root>');
await page.getByTestId('rightXml').fill('<root><item>A</item><item>B</item></root>');
const result = await page.getByTestId('diff-result').innerText();
expect(result).toContain('item: [\n"A",\n"B",\n],');
});
});
@@ -0,0 +1,65 @@
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest';
import { isValidXML, parseXml } from './xml-diff.parser';
describe('xml-diff parser', () => {
describe('parseXml', () => {
it('returns undefined for an empty string', () => {
expect(parseXml('')).toBeUndefined();
expect(parseXml(' ')).toBeUndefined();
});
it('returns undefined for invalid xml', () => {
expect(parseXml('<a><b></a>')).toBeUndefined();
});
it('parses a leaf element to its text content', () => {
expect(parseXml('<foo>bar</foo>')).toEqual('bar');
});
it('parses an empty element to an empty string', () => {
expect(parseXml('<foo/>')).toEqual('');
});
it('parses attributes with an "@" prefix', () => {
expect(parseXml('<foo a="1" b="2"/>')).toEqual({ '@a': '1', '@b': '2' });
});
it('parses a single child element as a plain value', () => {
expect(parseXml('<root><item>A</item></root>')).toEqual({ item: 'A' });
});
it('parses repeated child elements as an array', () => {
expect(parseXml('<root><item>A</item><item>B</item></root>')).toEqual({ item: ['A', 'B'] });
});
it('combines attributes, text and children', () => {
expect(parseXml('<root id="1">hello<child>world</child></root>')).toEqual({
'@id': '1',
'#text': 'hello',
child: 'world',
});
});
it('ignores insignificant whitespace between tags', () => {
const withoutWhitespace = parseXml('<foo><bar>baz</bar></foo>');
const withWhitespace = parseXml('<foo>\n <bar>baz</bar>\n</foo>');
expect(withWhitespace).toEqual(withoutWhitespace);
});
});
describe('isValidXML', () => {
it('accepts an empty string', () => {
expect(isValidXML('')).toBe(true);
});
it('accepts valid xml', () => {
expect(isValidXML('<foo>bar</foo>')).toBe(true);
});
it('rejects invalid xml', () => {
expect(isValidXML('<a><b></a>')).toBe(false);
});
});
});
+74
View File
@@ -0,0 +1,74 @@
export { isValidXML, parseXml };
function parseXml(rawXml: string): unknown {
const trimmed = rawXml.trim();
if (trimmed === '') {
return undefined;
}
const doc = parseXmlDocument(trimmed);
if (doc === undefined || doc.documentElement === null) {
return undefined;
}
return elementToValue(doc.documentElement);
}
function isValidXML(rawXml: string): boolean {
const trimmed = rawXml.trim();
if (trimmed === '') {
return true;
}
return parseXmlDocument(trimmed) !== undefined;
}
function parseXmlDocument(xml: string): Document | undefined {
const doc = new DOMParser().parseFromString(xml, 'application/xml');
if (doc.getElementsByTagName('parsererror').length > 0) {
return undefined;
}
return doc;
}
function elementToValue(element: Element): unknown {
const attributes = Array.from(element.attributes);
const childElements = Array.from(element.children);
const text = getDirectText(element);
if (attributes.length === 0 && childElements.length === 0) {
return text;
}
const value: Record<string, unknown> = {};
for (const attribute of attributes) {
value[`@${attribute.name}`] = attribute.value;
}
const tags = [...new Set(childElements.map((child) => child.tagName))];
for (const tag of tags) {
const sameTagChildren = childElements.filter((child) => child.tagName === tag);
value[tag] =
sameTagChildren.length === 1 ? elementToValue(sameTagChildren[0]) : sameTagChildren.map(elementToValue);
}
if (text !== '') {
value['#text'] = text;
}
return value;
}
function getDirectText(element: Element): string {
return Array.from(element.childNodes)
.filter((node) => node.nodeType === Node.TEXT_NODE || node.nodeType === Node.CDATA_SECTION_NODE)
.map((node) => node.textContent ?? '')
.join('')
.trim();
}
@@ -0,0 +1,63 @@
import { describe, expect, it } from 'vitest';
import { diff } from '../json-diff/json-diff.models';
import { reconcileArrayShapes } from './xml-diff.reconcile';
describe('xml-diff reconcile', () => {
describe('reconcileArrayShapes', () => {
it('leaves matching plain values untouched', () => {
expect(reconcileArrayShapes({ item: 'A' }, { item: 'B' })).toEqual([{ item: 'A' }, { item: 'B' }]);
});
it('pads the shorter side when both are arrays of different lengths', () => {
expect(reconcileArrayShapes({ item: ['A'] }, { item: ['A', 'B'] })).toEqual([
{ item: ['A', undefined] },
{ item: ['A', 'B'] },
]);
});
it('wraps a single value in an array when the other side has an array for the same key', () => {
const [left, right] = reconcileArrayShapes({ item: 'A' }, { item: ['A', 'B'] });
expect(left).toEqual({ item: ['A', undefined] });
expect(right).toEqual({ item: ['A', 'B'] });
});
it('recurses into nested objects', () => {
const [left, right] = reconcileArrayShapes({ root: { item: 'A' } }, { root: { item: ['A', 'B'] } });
expect(left).toEqual({ root: { item: ['A', undefined] } });
expect(right).toEqual({ root: { item: ['A', 'B'] } });
});
});
describe('diff after reconciliation', () => {
it('produces a clean diff when an element goes from single to repeated', () => {
const left = { item: 'A' };
const right = { item: ['A', 'B'] };
const [reconciledLeft, reconciledRight] = reconcileArrayShapes(left, right);
const result = diff(reconciledLeft, reconciledRight);
expect(result).toEqual({
key: '',
type: 'object',
oldValue: { item: ['A', undefined] },
value: { item: ['A', 'B'] },
status: 'children-updated',
children: [
{
key: 'item',
type: 'array',
oldValue: ['A', undefined],
value: ['A', 'B'],
status: 'children-updated',
children: [
{ key: 0, type: 'value', oldValue: 'A', value: 'A', status: 'unchanged' },
{ key: 1, type: 'value', oldValue: undefined, value: 'B', status: 'added' },
],
},
],
});
});
});
});
+60
View File
@@ -0,0 +1,60 @@
export { reconcileArrayShapes };
/**
* XML has no way to know, from a single document, whether a repeated element
* could also legitimately appear once. `xml-diff.parser` therefore represents
* a single occurrence as a plain value and 2+ occurrences as an array, which
* means the same element key can land on different shapes on each side of the
* diff (e.g. `item: {...}` on the left, `item: [{...}, {...}]` on the right).
* Diffing an object against an array directly produces nonsense, so before
* calling the generic diff we walk both trees together and wrap the
* non-array side in a single-element array wherever the two sides disagree.
*/
function reconcileArrayShapes(left: unknown, right: unknown): [unknown, unknown] {
if (Array.isArray(left) || Array.isArray(right)) {
return reconcileArrays(
Array.isArray(left) ? left : left === undefined ? [] : [left],
Array.isArray(right) ? right : right === undefined ? [] : [right],
);
}
if (isPlainObject(left) && isPlainObject(right)) {
return reconcileObjects(left, right);
}
return [left, right];
}
function reconcileArrays(left: unknown[], right: unknown[]): [unknown[], unknown[]] {
const maxLength = Math.max(left.length, right.length);
const reconciledLeft: unknown[] = [];
const reconciledRight: unknown[] = [];
for (let i = 0; i < maxLength; i++) {
const [reconciledLeftItem, reconciledRightItem] = reconcileArrayShapes(left[i], right[i]);
reconciledLeft.push(reconciledLeftItem);
reconciledRight.push(reconciledRightItem);
}
return [reconciledLeft, reconciledRight];
}
function reconcileObjects(
left: Record<string, unknown>,
right: Record<string, unknown>,
): [Record<string, unknown>, Record<string, unknown>] {
const reconciledLeft: Record<string, unknown> = { ...left };
const reconciledRight: Record<string, unknown> = { ...right };
for (const key of new Set([...Object.keys(left), ...Object.keys(right)])) {
const [reconciledLeftValue, reconciledRightValue] = reconcileArrayShapes(left[key], right[key]);
reconciledLeft[key] = reconciledLeftValue;
reconciledRight[key] = reconciledRightValue;
}
return [reconciledLeft, reconciledRight];
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts">
import DiffsViewer from './diff-viewer/xml-diff-viewer.vue';
import { isValidXML, parseXml } from './xml-diff.parser';
const rawLeftXml = ref('');
const rawRightXml = ref('');
const leftXml = computed(() => parseXml(rawLeftXml.value));
const rightXml = computed(() => parseXml(rawRightXml.value));
const xmlValidationRules = [
{
validator: (value: string) => isValidXML(value),
message: 'Invalid XML format',
},
];
</script>
<template>
<c-input-text
v-model:value="rawLeftXml"
:validation-rules="xmlValidationRules"
label="Your first XML"
placeholder="Paste your first XML here..."
rows="20"
test-id="leftXml"
raw-text
multiline
monospace
/>
<c-input-text
v-model:value="rawRightXml"
:validation-rules="xmlValidationRules"
label="Your XML to compare"
placeholder="Paste your XML to compare here..."
rows="20"
multiline
test-id="rightXml"
raw-text
monospace
/>
<DiffsViewer :left-xml="leftXml" :right-xml="rightXml" />
</template>