/*
 * SPDX-FileCopyrightText: 2020 The HedgeDoc developers (see AUTHORS file)
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { convertNodeToReactElement } from './convertNodeToReactElement.js'
import { Node } from 'domhandler'
import { ReactElement } from 'react'
import { NodeToReactElementTransformer } from './NodeToReactElementTransformer.js'

/**
 * Processes the nodes generated by htmlparser2 and convert them all into React elements
 *
 * @param {Object[]} nodes List of nodes to process
 * @param {Function} transform Transform function to optionally apply to nodes
 * @returns {React.Element[]} The list of processed React elements
 */
export function processNodes(
  nodes: Node[],
  transform?: NodeToReactElementTransformer,
): (ReactElement | string | null)[] {
  return nodes.map((node, index) => {
    if (transform) {
      const transformed = transform(node, index)
      if (transformed === null || !!transformed) {
        return transformed
      }
    }
    return convertNodeToReactElement(node, index, transform)
  })
}
