Created
December 20, 2020 22:04
-
-
Save jonathantneal/ee8eb5981dc9037619adfc8040a829fd to your computer and use it in GitHub Desktop.
Flex Gap 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
( | |
( | |
d, | |
c = d.createElement('b').style, | |
a = c.gap = 0, | |
polyfillList = new WeakMap, | |
ungapful = /^(normal|0px)+$/, | |
polyfillNode = element => { | |
if (polyfillList.has(element)) return | |
polyfillList.set(element, true) | |
if (element.shadowRoot) return | |
const ecss = getComputedStyle(element) | |
if (/^(inline-)?flex$/.test(ecss.display) && !ungapful.test(ecss.rowGap + ecss.columnGap)) { | |
const shadowRoot = element.attachShadow({ mode: 'open' }) | |
const shadowEcss = shadowRoot.appendChild(d.createElement('style')) | |
const shadowSlot = shadowRoot.appendChild(d.createElement('slot')) | |
const onFrameSkip = () => { | |
shadowEcss.textContent = ( | |
`::slotted(*){margin:calc(${ecss.rowGap}/2) calc(${ecss.columnGap}/2)}slot{display:inherit;flex-direction:inherit;flex-wrap:inherit;margin:calc(${ecss.rowGap}/-2) calc(${ecss.columnGap}/-2);max-height:-webkit-fill-available}` | |
) | |
requestAnimationFrame(requestAnimationFrame.bind(null, onFrameSkip)) | |
} | |
onFrameSkip() | |
} | |
}, | |
polyfillInit = () => { | |
Array.from(d.all, polyfillNode) | |
mo = new MutationObserver(records => { | |
for (const { addedNodes } of records) { | |
for (const addedNode of addedNodes) { | |
if (addedNode.nodeType === 1) { | |
polyfillNode(addedNode) | |
} | |
} | |
} | |
}) | |
mo.observe(d, { childList: true, subtree: true }) | |
} | |
) => c.gap || polyfillInit() | |
)(document) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment