Created
October 21, 2020 08:13
-
-
Save gubser/257e1022f84b8f13e89b0b8e43aaca10 to your computer and use it in GitHub Desktop.
Create auto-wrapping text in SVG
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 React from 'react'; | |
import { isArray } from 'lodash'; | |
export function wrapText(s: string|undefined, maxLength: number): string[] { | |
if(s === undefined) { | |
return []; | |
} else if(s.length < maxLength) { | |
return [s]; | |
} else { | |
const lastSpaceIndex = s.lastIndexOf(' ', maxLength); | |
if(lastSpaceIndex === -1) { | |
return [ | |
s.substring(0, maxLength), | |
...wrapText(s.substring(maxLength), maxLength) | |
]; | |
} else { | |
return [ | |
s.substring(0, lastSpaceIndex), | |
...wrapText(s.substring(lastSpaceIndex+1), maxLength) | |
]; | |
} | |
} | |
} | |
export interface WrappedTextProps extends React.SVGProps<SVGTextElement> { | |
children: string|string[]; | |
maxLength?: number; | |
} | |
export function WrappedText({ children, maxLength, ...rest }: WrappedTextProps) { | |
if(isArray(children)) { | |
if(children.length === 0) { | |
return <></>; | |
} else { | |
return ( | |
<text {...rest}> | |
{children.map((s, i) => <tspan key={i} x="0" dy="1.2em">{s}</tspan>)} | |
</text> | |
); | |
} | |
} else { | |
return ( | |
<text {...rest}> | |
{wrapText(children, maxLength || 80).map((s, i) => <tspan key={i} x="0" dy="1.2em">{s}</tspan>)} | |
</text> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment