Skip to content
Merged
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
19 changes: 18 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,23 @@ const fontWeights = {
};
const sp = ' ';
const italicRE = /(italic|oblique)$/i;
const snakeCaseRE = /_/g;
const wordStartRE = /(^| )[a-z]/g;

/**
* @param {string} font Font name, e.g. `'noto_sans_bold'` or `'Noto Sans Bold'`.
* @return {string} Font name with words separated by spaces, e.g. `'Noto Sans Bold'`.
*/
function toWords(font) {
if (font.indexOf('_') === -1) {
return font;
}
// Snake case names, e.g. from VersaTiles styles, are all lower case.
// Capitalized words match the family names that font services use.
return font
.replace(snakeCaseRE, sp)
.replace(wordStartRE, (wordStart) => wordStart.toUpperCase());
}

const fontCache = {};

Expand All @@ -46,7 +63,7 @@ export default function (fonts, size, lineHeight) {
const fontFamilies = [];
let haveWeight, haveStyle;
for (let i = 0, ii = fonts.length; i < ii; ++i) {
const font = fonts[i];
const font = toWords(fonts[i]);
const parts = font.split(' ');
let maybeWeight = parts[parts.length - 1].toLowerCase();
if (
Expand Down
12 changes: 12 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,18 @@ describe('mapbox-to-css-font', function () {
should(parseFont('Inter Semi Bold', 16)).eql('normal 600 16px Inter');
});

it('handle snake case font names', function () {
should(parseFont('noto_sans_regular', 16)).eql(
'normal 400 16px "Noto Sans"',
);
should(parseFont('noto_sans_bold', 16)).eql(
'normal 700 16px "Noto Sans"',
);
should(parseFont('noto_sans_semibold_italic', 16)).eql(
'italic 600 16px "Noto Sans"',
);
});

it('handle line-height', function () {
should(parseFont('monospace', 16)).eql('normal 400 16px monospace');
should(parseFont('monospace', 16, 3.5)).eql(
Expand Down
Loading