wesleytabaka-rpi-led-matrix
Version:
Fork of alexeden/rpi-led-matrix. Node.js/Typescript bindings for hzeller/rpi-rgb-led-matrix
90 lines (89 loc) • 3.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.LayoutUtils = exports.VerticalAlignment = exports.HorizontalAlignment = void 0;
const isSeparator = ({ char }) => char === ' ';
const glphysToWords = (glphys) => {
const index = glphys
.map((g, i) => i === 0 && isSeparator(g) ? null : g.char)
.indexOf(' ');
return index > 0
? [glphys.slice(0, index), ...glphysToWords(glphys.slice(index))]
: [glphys];
};
const calcWordWidth = (gs) => gs.reduce((sum, { w }) => sum + w, 0);
const wordsToLines = (maxWidth, words) => {
const lines = [];
let tmpLine = [];
let tmpLineWidth = 0;
words.filter(({ length }) => length > 0).forEach(word => {
const wordWidth = calcWordWidth(word);
if (tmpLineWidth + wordWidth > maxWidth) {
lines.push(tmpLine);
const firstWord = word.filter(g => !isSeparator(g));
tmpLine = [firstWord];
tmpLineWidth = calcWordWidth(firstWord);
}
else {
tmpLine.push(word);
tmpLineWidth += wordWidth;
}
});
if (tmpLine.length > 0)
lines.push(tmpLine);
return lines;
};
var HorizontalAlignment;
(function (HorizontalAlignment) {
HorizontalAlignment["Left"] = "left";
HorizontalAlignment["Center"] = "center";
HorizontalAlignment["Right"] = "right";
})(HorizontalAlignment = exports.HorizontalAlignment || (exports.HorizontalAlignment = {}));
var VerticalAlignment;
(function (VerticalAlignment) {
VerticalAlignment["Bottom"] = "bottom";
VerticalAlignment["Middle"] = "middle";
VerticalAlignment["Top"] = "top";
})(VerticalAlignment = exports.VerticalAlignment || (exports.VerticalAlignment = {}));
class LayoutUtils {
static textToLines(font, maxW, text) {
const fontHeight = font.height();
const glphys = text.split('').map(char => ({
char,
h: fontHeight,
w: font.stringWidth(char),
}));
return wordsToLines(maxW, glphysToWords(glphys));
}
static linesToMappedGlyphs(lines, lineH, containerW, containerH, alignH = HorizontalAlignment.Center, alignV = VerticalAlignment.Middle) {
const blockH = lineH * lines.length;
const offsetY = (() => {
switch (alignV) {
case VerticalAlignment.Top: return 0;
case VerticalAlignment.Middle: return Math.floor((containerH - blockH) / 2);
case VerticalAlignment.Bottom: return containerH - blockH;
}
})();
return lines.map((words, i) => {
const lineGlyphs = words.reduce((glyphs, word) => [...glyphs, ...word], []);
const lineW = calcWordWidth(lineGlyphs);
let offsetX = (() => {
switch (alignH) {
case HorizontalAlignment.Left: return 0;
case HorizontalAlignment.Center: return Math.floor((containerW - lineW) / 2);
case HorizontalAlignment.Right: return containerW - lineW;
}
})();
return lineGlyphs.map(glyph => {
const mapped = {
...glyph,
x: offsetX,
y: offsetY + i * lineH,
};
offsetX += glyph.w;
return mapped;
});
})
.reduce((glyphs, words) => [...glyphs, ...words], []);
}
}
exports.LayoutUtils = LayoutUtils;