strapi / blocks-react-renderer

A React renderer for the Strapi's Blocks rich text editor
Other
107 stars 15 forks source link

[feat]: Extract plain text from blocks #21

Open takumiyoshikawa opened 5 months ago

takumiyoshikawa commented 5 months ago

A clear and concise description of what the feature is

This feature adds a method to Strapi's rich-text rendering system, enabling the extraction of plain text from rich-text content.

Why should this feature be included?

This feature is useful in various content markup scenarios. For instance, in creating FAQ sections, it's crucial to have a method that efficiently strips formatting to present clear, concise text.

Please provide an example for how this would work

The feature would work similarly to PortableText's toPlainText. https://github.com/portabletext/toolkit/blob/main/src/toPlainText.ts

takumiyoshikawa commented 5 months ago

I think this minimum Implementation below works.

interface Node {
    text?: string;
    type: string;
    children: Node[];
}

export function getPlainText(block: Node[]) {
    const text: string = block.reduce((acc, node) => {
        if (node.type === 'text') {
            return acc + node.text;
        }
        return acc + getPlainText(node.children);
    }, '');

    return text;
}