Last active
April 5, 2016 19:19
-
-
Save ceane/6320f8474929f320e3d0 to your computer and use it in GitHub Desktop.
ES6 implementation of a CSS supports polyfill
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
/** | |
* Read up on the API here https://developer.mozilla.org/en-US/docs/Web/API/CSS/supports | |
*/ | |
if (!window.CSS) { | |
window.CSS = {}; | |
} | |
if(!RegExp.escape) { | |
RegExp.escape = s => String(s).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); | |
} | |
if (!window.CSS.supports) { | |
const _hyphenPattern = /-(.)/g; | |
const camelize = s => s.replace(_hyphenPattern, | |
(_, character) => character.toUpperCase()); | |
const div = document.createElement("div"); | |
function checkSupport(propName, value) { | |
value = value.replace(/^\s/, ""); | |
div.setAttribute("style", `${propName}: ${value};`); | |
return new RegExp(RegExp.escape(value), "i") | |
.test(div.style[camelize(propName)]); | |
} | |
const splitConditionRx = /(\s+or)(?=\W)/; | |
const scoped = /(^\s*\(\s*|\s*\)\s*$)/g; | |
const filter = c => !!c && !(/\b\s*or\s*\b/i.test(c)); | |
const isTrue = b => !!b; | |
const multiCheckSupport = s => checkSupport(...s.replace(scoped, "").split(":")); | |
window.CSS.supports = (...args) => { | |
let hasSupport = false; | |
document.body.appendChild(div); | |
if (args.length === 2) { | |
hasSupport = checkSupport(...args); | |
} else if (args.length === 1) { | |
hasSupport = args[0].split(splitConditionRx) | |
.filter(filter) | |
.map(multiCheckSupport) | |
.some(isTrue); | |
} | |
div.parentElement.removeChild(t); | |
return hasSupport; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment