From dea8a340a66ba069f3baca9054dc23e017c97677 Mon Sep 17 00:00:00 2001 From: Tim Schaub Date: Sat, 14 Oct 2017 13:17:28 -0600 Subject: [PATCH] Add utility method for extracting font families from a font spec --- src/ol/css.js | 27 +++++++++++++++++++++++ test/spec/ol/css.test.js | 47 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 test/spec/ol/css.test.js diff --git a/src/ol/css.js b/src/ol/css.js index 915893ea34..c6582bec30 100644 --- a/src/ol/css.js +++ b/src/ol/css.js @@ -43,3 +43,30 @@ ol.css.CLASS_UNSUPPORTED = 'ol-unsupported'; * @type {string} */ ol.css.CLASS_CONTROL = 'ol-control'; + + +/** + * Get the list of font families from a font spec. Note that this doesn't work + * for font families that have commas in them. + * @param {string} The CSS font property. + * @return {Array.} The font families (or null if the input spec is invalid). + */ +ol.css.getFontFamilies = (function() { + var style; + var cache = {}; + return function(font) { + if (!style) { + style = document.createElement('div').style; + } + if (!(font in cache)) { + style.font = font; + var family = style.fontFamily; + style.font = ''; + if (!family) { + return null; + } + cache[font] = family.split(/,\s?/); + } + return cache[font]; + }; +})(); diff --git a/test/spec/ol/css.test.js b/test/spec/ol/css.test.js new file mode 100644 index 0000000000..cf5e40f18b --- /dev/null +++ b/test/spec/ol/css.test.js @@ -0,0 +1,47 @@ +goog.require('ol.css'); + +describe('ol.css', function() { + + describe('getFontFamilies()', function() { + var cases = [{ + font: '2em "Open Sans"', + families: ['"Open Sans"'] + }, { + font: '2em \'Open Sans\'', + families: ['"Open Sans"'] + }, { + font: '2em "Open Sans", sans-serif', + families: ['"Open Sans"', 'sans-serif'] + }, { + font: 'italic small-caps bolder 16px/3 cursive', + families: ['cursive'] + }, { + font: 'garbage 2px input', + families: null + }, { + font: '100% fantasy', + families: ['fantasy'] + }]; + + cases.forEach(function(c, i) { + it('works for ' + c.font, function() { + var families = ol.css.getFontFamilies(c.font); + if (c.families === null) { + expect(families).to.be(null); + return; + } + families.forEach(function(family, j) { + // Safari uses single quotes for font families, so we have to do extra work + if (family.charAt(0) === '\'') { + // we wouldn't want to do this in the lib since it doesn't properly escape quotes + // but we know that our test cases don't include quotes in font names + families[j] = '"' + family.slice(1, -1) + '"'; + } + }); + expect(families).to.eql(c.families); + }); + }); + + }); + +});