html-differ.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { HtmlDiffer } from '@markedjs/html-differ';
  2. const htmlDiffer = new HtmlDiffer({
  3. ignoreSelfClosingSlash: true,
  4. ignoreComments: false
  5. });
  6. export const isEqual = htmlDiffer.isEqual.bind(htmlDiffer);
  7. export async function firstDiff(actual, expected, padding) {
  8. padding = padding || 30;
  9. const diffHtml = await htmlDiffer.diffHtml(actual, expected);
  10. const result = diffHtml.reduce((obj, diff) => {
  11. if (diff.added) {
  12. if (obj.firstIndex === null) {
  13. obj.firstIndex = obj.expected.length;
  14. }
  15. obj.expected += diff.value;
  16. } else if (diff.removed) {
  17. if (obj.firstIndex === null) {
  18. obj.firstIndex = obj.actual.length;
  19. }
  20. obj.actual += diff.value;
  21. } else {
  22. obj.actual += diff.value;
  23. obj.expected += diff.value;
  24. }
  25. return obj;
  26. }, {
  27. firstIndex: null,
  28. actual: '',
  29. expected: ''
  30. });
  31. return {
  32. actual: result.actual.substring(result.firstIndex - padding, result.firstIndex + padding),
  33. expected: result.expected.substring(result.firstIndex - padding, result.firstIndex + padding)
  34. };
  35. }