WYSIWYG fix list nesting (#13251)

* Improvements to nested lists

* OL tests and PR feedback
This commit is contained in:
Chris LaFreniere
2020-11-05 18:21:33 -08:00
committed by GitHub
parent fe546e3791
commit e4390db779
2 changed files with 40 additions and 0 deletions

View File

@@ -105,6 +105,32 @@ export class HTMLMarkdownConverter {
return `[${node.innerText}](${node.href})`;
}
});
this.turndownService.addRule('listItem', {
filter: 'li',
replacement: function (content, node, options) {
content = content
.replace(/^\n+/, '') // remove leading newlines
.replace(/\n+$/, '\n') // replace trailing newlines with just a single one
.replace(/\n/gm, '\n '); // indent
let prefix = options.bulletListMarker + ' ';
let parent = node.parentNode;
let nestedCount = 0;
if (parent.nodeName === 'OL') {
let start = parent.getAttribute('start');
let index = Array.prototype.indexOf.call(parent.children, node);
prefix = (start ? Number(start) + index : index + 1) + '. ';
} else if (parent.nodeName === 'UL') {
while (parent?.nodeName === 'UL') {
nestedCount++;
parent = parent?.parentNode;
}
prefix = (' '.repeat(nestedCount - 1)) + options.bulletListMarker + ' ';
}
return (
prefix + content + (node.nextSibling && !/\n$/.test(content) ? '\n' : '')
);
}
});
}
}

View File

@@ -138,4 +138,18 @@ suite('HTML Markdown Converter', function (): void {
htmlString = '<a href="http://www.microsoft.com/images/msft.png">msft</a>';
assert.equal(htmlMarkdownConverter.convert(htmlString), '[msft](http://www.microsoft.com/images/msft.png)', 'Basic http link test failed');
});
test('Should transform <li> tags', () => {
htmlString = '<ul><li>Test</li></ul>';
assert.equal(htmlMarkdownConverter.convert(htmlString), `- Test`, 'Basic unordered list test failed');
htmlString = '<ul><li>Test</li><li>Test2</li></ul>';
assert.equal(htmlMarkdownConverter.convert(htmlString), `- Test\n- Test2`, 'Basic unordered 2 item list test failed');
htmlString = '<ul><li>Test<ul><li>Test2</li></ul><li>Test3</li></ul>';
assert.equal(htmlMarkdownConverter.convert(htmlString), `- Test\n - Test2\n- Test3`, 'Nested item list test failed');
htmlString = '<ol><li>Test</li></ol>';
assert.equal(htmlMarkdownConverter.convert(htmlString), `1. Test`, 'Basic ordered item test failed');
htmlString = '<ol><li>Test</li><li>Test2</li></ol>';
assert.equal(htmlMarkdownConverter.convert(htmlString), `1. Test\n2. Test2`, 'Basic ordered item test failed');
htmlString = '<ol><li>Test<ol><li>Test2</li></ol><li>Test3</li></ol>';
assert.equal(htmlMarkdownConverter.convert(htmlString), `1. Test\n 1. Test2\n2. Test3`, 'Basic ordered item test failed');
});
});