Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created July 19, 2023 13:24
Show Gist options
  • Save karol-majewski/9a8148d61d19cec46b315e28546b96ec to your computer and use it in GitHub Desktop.
Save karol-majewski/9a8148d61d19cec46b315e28546b96ec to your computer and use it in GitHub Desktop.
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