ntms
Version:
A dead simple way to add i18n to your Next.js app using the Notion API and Deepl
78 lines (73 loc) • 1.75 kB
text/typescript
import { RichText } from "../types";
const htmlparser2 = require("htmlparser2");
const makeRichText = (): RichText => {
return {
type: "text",
plain_text: "",
annotations: {
bold: false,
italic: false,
strikethrough: false,
underline: false,
code: false,
color: "default",
},
href: null,
};
};
const toRichText = (html: string): RichText[] => {
let rich_text;
let parts = [];
const parser = new htmlparser2.Parser({
onopentag(name, attributes) {
if (name === "span") {
rich_text = makeRichText();
}
if (name == "mustach") {
rich_text.plain_text += "{{";
}
if (name == "plural") {
rich_text.plain_text += "((";
}
if (name === "b") {
rich_text.annotations.bold = true;
}
if (name === "pre") {
rich_text.annotations.code = true;
}
if (name === "strike") {
rich_text.annotations.strikethrough = true;
}
if (name === "u") {
rich_text.annotations.underline = true;
}
if (name === "mark") {
Object.keys(attributes).forEach(
(x) =>
x === "data-color" && (rich_text.annotations.color = attributes[x])
);
}
if (name === "a") {
rich_text.href = attributes.href;
}
},
ontext(text) {
rich_text.plain_text += text;
},
onclosetag(name) {
if (name == "mustach") {
rich_text.plain_text += "}}";
}
if (name == "plural") {
rich_text.plain_text += "))";
}
if (name === "span") {
parts.push(rich_text);
}
},
});
parser.write(html);
parser.end();
return parts;
};
export default toRichText;