export interface TiptapNode {
type: string;
content?: TiptapNode[];
text?: string;
attrs?: {
[key: string]: any;
};
}
export default class Content {
static convertTipTapRawToText(content: string): string {
const text: string = this.convertTiptapToHTMLFromString(content);
return this.htmlToText(text);
}
static htmlToText(html: string) {
return html
.replace(/
/gi, '\n') // Gérer les
d'abord
.replace(/<\/?(p|h[1-6]|div)(\s+[^>]*)?>/gi, '\n') // Balises bloc
.replace(/<\/?[^>]+(>|$)/g, '') // Supprimer toutes les balises restantes
.replace(/(\n\s*){2,}/g, '\n\n') // Préserver les paragraphes
.replace(/^\s+|\s+$|(?<=\s)\s+/g, '') // Nettoyer les espaces
.trim();
}
static convertTiptapToHTMLFromString(jsonString: string): string {
// Convert the JSON string to an object
let jsonObject: TiptapNode;
try {
jsonObject = JSON.parse(jsonString);
} catch (error) {
console.error('Invalid JSON string:', error);
return '';
}
// Use the existing conversion function
return this.convertTiptapToHTML(jsonObject);
}
static convertTiptapToHTML(node: TiptapNode): string {
let html = '';
switch (node.type) {
case 'doc':
if (node.content) {
node.content.forEach(childNode => {
html += this.convertTiptapToHTML(childNode);
});
}
break;
case 'paragraph':
html += '
'; if (node.content) { node.content.forEach(childNode => { html += this.convertTiptapToHTML(childNode); }); } html += '
'; break; case 'text': let textContent = node.text || ''; // Apply attributes like bold, italic, etc. if (node.attrs) { if (node.attrs.bold) { textContent = `${textContent}`; } if (node.attrs.italic) { textContent = `${textContent}`; } if (node.attrs.underline) { textContent = `${textContent}`; } if (node.attrs.strike) { textContent = `'; if (node.content) { node.content.forEach(childNode => { html += this.convertTiptapToHTML(childNode); }); } html += ''; break; case 'codeBlock': html += '
';
if (node.content) {
node.content.forEach(childNode => {
html += this.convertTiptapToHTML(childNode);
});
}
html += '';
break;
default:
console.warn(`Unhandled node type: ${node.type}`);
if (node.content) {
node.content.forEach(childNode => {
html += this.convertTiptapToHTML(childNode);
});
}
break;
}
return html;
}
}