Created
July 19, 2023 13:24
-
-
Save karol-majewski/9a8148d61d19cec46b315e28546b96ec to your computer and use it in GitHub Desktop.
Remove orphans from text (source: https://twitter.com/joeflateau/status/1681426536711487490)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
const NON_BREAKING_SPACE_CHARACTER = '\u00A0'; | |
interface Props { | |
children: string; | |
/** | |
* If the text is shorter than this, it will not be processed. | |
*/ | |
requiredLength?: number; | |
/** | |
* The minimum number of words to keep on the last line. | |
*/ | |
minimumWordsInLastLine?: number; | |
} | |
/** | |
* @see https://twitter.com/joeflateau/status/1681426536711487490 | |
*/ | |
export const Deorphanize: React.FC<Props> = ({ children, minimumWordsInLastLine = 2, requiredLength = 5 }) => { | |
const words = children.split(/\s+/); | |
if (words.length <= requiredLength) { | |
return <>{children}</>; | |
} | |
const leading = words.slice(0, words.length - minimumWordsInLastLine).join(' '); | |
const lastLine = words.slice(-minimumWordsInLastLine).join(NON_BREAKING_SPACE_CHARACTER); | |
return ( | |
<> | |
{leading} {lastLine} | |
</> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment