Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable use of linebreaks in text via \n or <br> #12

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ let quote;
let status;

export default function extractElements(text) {
// Enable linebreaks by passing <br> or \n. Note that space is important.
text = text.split('<br>').join('\n');
text = text.split('\n').join('\n ');

const chars = text.split('');
const tags = [];
reset();
Expand Down
9 changes: 5 additions & 4 deletions src/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export default function render(text, options, lineHeight) {
// chars.some((c, index) => {
while (index < chars.length) {
const c = chars[index];
const isLineBreak = /\n/.test(c);
charIndex = index;
isFinalLine = tspanIndex + 1 === maxLines || height + lineHeight > maxHeight;
charsRemain = !/^\s*$/.test(chars.slice(index).join(''));
Expand All @@ -85,7 +86,7 @@ export default function render(text, options, lineHeight) {
const tspan = createTspan(text, tmpStrF, lineHeight);

let complete = false;
if (textFits(text)) {
if (!isLineBreak && textFits(text)) {
// Text with the test character fits, so now just exit if there are no
// more characters to write.
lineStr = tmpStr;
Expand All @@ -101,7 +102,7 @@ export default function render(text, options, lineHeight) {
for (let i = 0; i < openTags.length; i++) {
tmpStr += openTags[i].markup;
}
if (lastBoundIndex > lineCharIndex) {
if (!isLineBreak && lastBoundIndex > lineCharIndex) {
if (isHyphen(chars[lastBoundIndex])) {
// Push the hyphen onto the last word.
// lineStr = chars.slice(lineCharIndex, lastBoundIndex + 1).join('');
Expand All @@ -121,7 +122,7 @@ export default function render(text, options, lineHeight) {
}
if (isFinalLine) {
lineStr = lineStr.replace(/^\s+$/, '');
} else {
} else if (!isLineBreak) {
--index;
}
}
Expand All @@ -130,7 +131,7 @@ export default function render(text, options, lineHeight) {
writeInnerHTML(tspan, lineStr);
// Remove temporarily to prevent the width from getting whacky:
text.removeChild(tspan);
if (isFinalLine || !lineStr) {
if (isFinalLine || (!lineStr && !charsRemain)) {
complete = true;
}
workingLineStr = '';
Expand Down