UNPKG

sanity-next-social-image-generator

Version:
34 lines (33 loc) 2.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildTextSVGBuffer = void 0; var buildTextSVGBuffer = function (config) { var svgText = constructMultilineSVGText(config.width, config.height, config.fontSize, config.text); var svg = "\n <svg width=\"".concat(config.width, "\" height=\"").concat(config.height, "\">\n <defs>\n <style type=\"text/css\">\n .title {\n fill: ").concat(config.color || 'white', ";\n font-size: ").concat(config.fontSize, "px;\n font-family: \"").concat(config.fontName, "\";\n }\n </style>\n </defs>\n ").concat(svgText, "\n </svg>\n "); return Buffer.from(svg); }; exports.buildTextSVGBuffer = buildTextSVGBuffer; var constructMultilineSVGText = function (containerWidth, containerHeight, fontSize, text) { var numCharactersPerLine = (containerWidth / fontSize) * 1.5; var rows = [[]]; var currentRow = 0; var currentCharacterCount = 0; // Group words into rows based on allowed # of characters per line for (var _i = 0, _a = text.split(' '); _i < _a.length; _i++) { var word = _a[_i]; var canAddWordToRow = currentCharacterCount + word.length <= numCharactersPerLine; if (canAddWordToRow) { rows[currentRow].push(word); currentCharacterCount += word.length; } else { currentRow++; currentCharacterCount = 0; rows[currentRow] = [word]; } } var heightPercentPerRow = Math.floor((fontSize / containerHeight) * 100) / 2; var containerYOffset = 50 - heightPercentPerRow * rows.length; // Create SVG <text> element that has <tspan> children for each row return "<text x=\"50%\" y=\"".concat(containerYOffset, "%\" text-anchor=\"middle\" class=\"title\">\n ").concat(rows.reduce(function (acc, row) { return (acc += "<tspan x=\"".concat(containerWidth / 2, "\" dy=\"1em\">").concat(row.join(' '), "</tspan>")); }, ''), "\n </text>"); };