Created
April 16, 2018 00:55
-
-
Save brookjordan/da3c8154d6497e03b539578b19d3fd5b to your computer and use it in GitHub Desktop.
Find unique text styles around a site
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Use like: | |
* var a = new StyleCollector({ filterFonts : ['Open Sans', 'Raleway'] }); | |
* a.search(); // => no of new fonts found | |
* console.log(a.textStyles); // => Array of unique found text styles | |
*/ | |
class StyleCollector { | |
constructor({ filterFonts } = {}) { | |
this._foundStyles = []; | |
if (typeof filterFonts === 'undefined') { | |
this._filterFonts = []; | |
} else if (typeof filterFonts === 'string') { | |
this._filterFonts = [filterFonts]; | |
} else { | |
this._filterFonts = filterFonts; | |
} | |
} | |
search() { | |
let currentLength = this._foundStyles.length; | |
let newStyles = (Array.from( | |
document.querySelectorAll('*') | |
)) | |
.map(elt => getComputedStyle(elt)) | |
.map(style => JSON.stringify({ | |
fontStyle: style.fontStyle, | |
fontVariant: style.fontVariant, | |
textTransform: style.textTransform, | |
fontWeight: +style.fontWeight, | |
fontSize: parseFloat(style.fontSize) || style.fontSize, | |
lineHeight: parseFloat(style.lineHeight) || style.lineHeight, | |
letterSpacing: parseFloat(style.letterSpacing) || style.letterSpacing, | |
fontFamily: style.fontFamily.split(',')[0], | |
})); | |
if (this._filterFonts.length) { | |
newStyles = newStyles.filter(this._fontFilter.bind(this)); | |
} | |
this._foundStyles = [ | |
...this._foundStyles, | |
...newStyles, | |
] | |
.filter((s, i, a) => a.indexOf(s) === i); | |
return this._foundStyles.length - currentLength; | |
} | |
get textStyles() { | |
return this._foundStyles.map(a => JSON.parse(a)); | |
} | |
_fontFilter(style) { | |
let i = this._filterFonts.length; | |
if (i === 0) { | |
return true; | |
} | |
do { | |
i -= 1; | |
if (JSON.parse(style).fontFamily.indexOf(this._filterFonts[i]) > -1) { | |
return true; | |
} | |
} while (i); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment