Add utility method for extracting font families from a font spec
This commit is contained in:
committed by
Andreas Hocevar
parent
06728ab0fa
commit
dea8a340a6
@@ -43,3 +43,30 @@ ol.css.CLASS_UNSUPPORTED = 'ol-unsupported';
|
|||||||
* @type {string}
|
* @type {string}
|
||||||
*/
|
*/
|
||||||
ol.css.CLASS_CONTROL = 'ol-control';
|
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.<string>} 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];
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user