hedgedoc/html-to-react/src/convertHtmlToReact.ts
Tilman Vatteroth 84527f065c feat: import html-to-react from https://github.com/hedgedoc/html-to-react
Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
2023-08-26 15:07:49 +02:00

38 lines
1.2 KiB
TypeScript

/*
* SPDX-FileCopyrightText: 2020 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { parseDocument } from 'htmlparser2'
import { processNodes } from './processNodes.js'
import { ReactElement } from 'react'
import { Document } from 'domhandler'
import { NodeToReactElementTransformer } from './NodeToReactElementTransformer.js'
export interface ParserOptions {
decodeEntities?: boolean
transform?: NodeToReactElementTransformer
preprocessNodes?: (nodes: Document) => Document
}
/**
* Parses an HTML string and returns a list of React components generated from it
*
* @param {String} html The HTML to convert into React component
* @param {Object} options Options to pass
* @returns {Array} List of top level React elements
*/
export function convertHtmlToReact(
html: string,
options?: ParserOptions
): (ReactElement | string | null)[] {
const parsedDocument = parseDocument(html, {
decodeEntities: options?.decodeEntities ?? true
})
const processedDocument =
options?.preprocessNodes?.(parsedDocument) ?? parsedDocument
return processNodes(processedDocument.childNodes, options?.transform)
}