Skip to content

Instantly share code, notes, and snippets.

@GlauberF
Created April 25, 2023 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GlauberF/7d4d30e86681a185e607e24728463fb3 to your computer and use it in GitHub Desktop.
Save GlauberF/7d4d30e86681a185e607e24728463fb3 to your computer and use it in GitHub Desktop.
function quill(html) {
let parser = new DOMParser();
let dom = parser.parseFromString(html, "text/html");
let quillOps = [];
let elementToQuill = (el, attributes) => {
if (el.nodeType === Node.TEXT_NODE) {
el.textContent.split(" ").forEach((word) => {
if (word) { // para evitar a inserção de strings vazias
let lastInsert = quillOps[quillOps.length - 1]?.insert ?? "";
if (word === lastInsert) { // verifica se a palavra atual é igual ao último objeto insert inserido
quillOps[quillOps.length - 1].attributes = attributes;
} else {
quillOps.push({ insert: word, attributes });
}
}
});
return;
}
let newAttributes = Object.assign({}, attributes);
switch (el.tagName) {
case "STRONG":
newAttributes.bold = true;
break;
case "EM":
newAttributes.italic = true;
break;
case "U":
newAttributes.underline = true;
break;
case "S":
newAttributes.strike = true;
break;
case "A":
newAttributes.link = el.getAttribute("href");
newAttributes.target = "_blank";
break;
case "SPAN":
if (el.style.fontSize) {
newAttributes.size = el.style.fontSize;
}
if (el.style.color) {
newAttributes.color = el.style.color;
}
if (el.style.backgroundColor) {
newAttributes.background = el.style.backgroundColor;
}
break;
}
for (let child of el.childNodes) {
elementToQuill(child, newAttributes);
}
};
for (let child of dom.body.childNodes) {
elementToQuill(child, {});
}
return quillOps;
}
quill("<p><strong>negrito</strong></p><p><em>italico</em></p><p><u>sublinhado</u></p><p><s>tachado</s></p><p><a href=\"http://google.com.br\" rel=\"noopener noreferrer\" target=\"_blank\">link</a></p><p><span style=\"font-size: 15px;\">fonte</span></p><p><span style=\"color: rgb(255, 153, 0);\">texto-cor</span></p><p><span style=\"color: rgb(0, 0, 0); background-color: rgb(0, 255, 0);\">text-background</span></p>")
// [{"insert":"abacate","attributes":{}},{"insert":"negrito","attributes":{"bold":true}},{"insert":"italico","attributes":{"italic":true}},{"insert":"sublinhado","attributes":{"underline":true}},{"insert":"tachado","attributes":{"strike":true}},{"insert":"link","attributes":{"link":"http://google.com.br","target":"_blank"}},{"insert":"fonte","attributes":{"size":"15px"}},{"insert":"texto-cor","attributes":{"color":"rgb(255, 153, 0)"}},{"insert":"text-background","attributes":{"color":"rgb(0, 0, 0)","background":"rgb(0, 255, 0)"}}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment