cal/packages/lib/turndownService.ts
Abhijeet Singh 3e63c2b717
fix: Italics not being shown in the description after saving (#10848)
* added ignore rule for em tag in turndown

* added ignore rule for em tag in turndown

---------

Co-authored-by: Abhijeet Singh <asing9829@gmail.com>
2023-08-24 11:20:00 +01:00

57 lines
1.3 KiB
TypeScript

import TurndownService from "turndown";
const turndownService = new TurndownService();
function turndown(html: string | TurndownService.Node): string {
let result = turndownService.turndown(html);
result = result.replaceAll("[<p><br></p>]", "");
if (result === "<p><br></p>") {
result = "";
}
return result;
}
turndownService.addRule("shiftEnter", {
filter: function (node) {
return node.nodeName === "BR" && !!isShiftEnter(node);
},
replacement: function () {
return "<br>";
},
});
turndownService.addRule("enter", {
filter: function (node) {
return node.nodeName === "BR" && !isShiftEnter(node);
},
replacement: function () {
return "<p><br></p>";
},
});
turndownService.addRule("ignoreEmphasized", {
filter: "em",
replacement: function (content) {
return content;
},
});
function isShiftEnter(node: HTMLElement) {
let currentNode: HTMLElement | null | ParentNode = node;
while (currentNode != null && currentNode.nodeType !== 1) {
currentNode = currentNode.parentElement || currentNode.parentNode;
}
return (
currentNode &&
currentNode.nodeType === 1 &&
currentNode.parentElement &&
currentNode.parentElement.childNodes.length !== 1 // normal enter is <p><br><p> (p has exactly one childNode)
);
}
export default turndown;