-
-
Save vegeta897/16a9d2c527e7deadcc887bffd7958786 to your computer and use it in GitHub Desktop.
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
calculateMetrics: function(options) { | |
// TODO: Normalize line lengths so there are no single-word remainders | |
var text = options.text; | |
var lines = []; | |
var words = text.split(' '); | |
var space = fontMap[' ']; | |
var lineWidth = 0, lineChars = [], maxLineWidth = 0; | |
for(var w = 0; w < words.length; w++) { | |
var word = words[w]; | |
if(word == '') continue; // Skip empty words | |
var wordWidth = 0; | |
var wordChars = []; | |
if(lineChars.length > 0) { // Add space before word unless starting a line | |
wordChars.push({ x: lineWidth, char: space, w: space.w }); | |
wordWidth += space.w; | |
} | |
if(word.length > 1 && fontMap[word]) { // Icon codes | |
wordChars.push({ | |
x: lineWidth + wordWidth, char: fontMap[word], w: fontMap[word].w, oy: -2 | |
}); | |
wordWidth += fontMap[word].w; | |
} else { | |
for(var a = 0; a < word.length; a++) { | |
var ltr = fontMap[word[a]] || space; | |
wordChars.push({ | |
x: lineWidth + wordWidth, char: ltr, w: ltr.w, oy: ltr.oy | |
}); | |
wordWidth += ltr.w; | |
} | |
} | |
if(options.maxWidth && lineWidth + wordWidth > options.maxWidth) { | |
if(wordWidth > options.maxWidth) { // Word is longer than maxWidth, won't fit any line | |
if(lineWidth > 0) { | |
lines.push({ w: lineWidth, chars: lineChars }); | |
maxLineWidth = Math.max(lineWidth, maxLineWidth); | |
lineWidth = 0; lineChars = []; | |
} | |
wordChars = []; | |
wordWidth = 0; | |
for(var b = 0; b < word.length; b++) { | |
var ltrB = fontMap[word[b]] || space; | |
if(lineWidth + wordWidth + ltrB.w < options.maxWidth) { | |
wordChars.push({ | |
x: lineWidth + wordWidth, char: ltrB, w: ltrB.w, oy: ltrB.oy | |
}); | |
wordWidth += ltrB.w; | |
} else { | |
var trimWidth = (lineWidth + wordWidth + ltrB.w) - options.maxWidth; | |
wordChars.push({ | |
x: lineWidth + wordWidth, char: ltrB, w: ltrB.w - trimWidth, oy: ltrB.oy | |
}); | |
wordWidth += ltrB.w - trimWidth; | |
break; | |
} | |
} | |
lineWidth += wordWidth; | |
lineChars = lineChars.concat(wordChars); | |
} else { // Word can be pushed to next line | |
w--; | |
} | |
lines.push({ w: lineWidth, chars: lineChars }); | |
maxLineWidth = Math.max(lineWidth, maxLineWidth); | |
lineWidth = 0; lineChars = []; | |
} else { // Word fits on line | |
lineWidth += wordWidth; | |
lineChars = lineChars.concat(wordChars); | |
if(w == words.length - 1) { | |
lines.push({ w: lineWidth, chars: lineChars }); | |
maxLineWidth = Math.max(lineWidth, maxLineWidth); | |
} | |
} | |
} | |
return { lines: lines, text: text, w: maxLineWidth }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment