import * as React from 'react'
import {ReactElement, Fragment, FC} from 'react'
import {limitItems, splitJoin} from './helpers'
/**
* @category Props
*/
export interface SplitLineBreaksProps {
text: string
max?: number
children: (items: JSX.Element[]) => ReactElement
}
/**
* SplitLineBreaks is WIP and subject to change!
* @experimental
* @param props - {@link SplitLineBreaksProps}
* @returns an array of items made from splitting the text on line breaks, and then passed to the children function
* @example
* ```jsx
* const someTextWithLineBreaks = `one\ntwo\nthree`
*
* // …later in JSX…
*
* {(lines) => ( // this is the render prop function
* // the following fragment is to ensure only one child is returned, which wraps however you use the items
* <>
* {lines.map((line, index) => (
*
* {line}
*
* ))}
* >
* )}
*
* ```
*/
export const SplitLineBreaks: FC = ({text = ``, max, children}) => {
const allItems = text.split(`\n`).filter(Boolean)
const limitedItems = max ? allItems.slice(0, max * 1) : allItems
const items = limitedItems.map((item, i) => (
{item}
<>>
))
return children(items)
}
/**
* @category Props
*/
export interface TextUtilityProps {
text: string
max?: number
children: (text: string) => ReactElement
}
/**
* A component that splits text on line breaks, and then passes the resulting string to the children function
* @param props - {@link TextUtilityProps}
* @returns the string with spaces converted to non-breaking spaces, and then passed to the children function
* @example
* ```jsx
*
* {(text) => {text}
}
*
* ```
*/
export const SpacesToNonBreaking: FC = ({text = ``, max, children}) => {
const allItems = splitJoin(text, ` `, `\xa0`)
const items = limitItems(allItems, max)
return children(items)
}
/**
* A component that changes line breaks to spaces, and then passes the resulting string to the children function
* @param props - {@link TextUtilityProps}
* @returns the string with sline breaks to spaces, and then passed to the children function
* @example
* ```jsx
*
* {(text) => {text}
}
*
* ```
*/
export const LineBreaksToSpaces: FC = ({text = ``, max, children}) => {
const allItems = splitJoin(text, `\n`, ` `)
const items = limitItems(allItems, max)
return children(items)
}