Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created December 20, 2020 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/ee8eb5981dc9037619adfc8040a829fd to your computer and use it in GitHub Desktop.
Save jonathantneal/ee8eb5981dc9037619adfc8040a829fd to your computer and use it in GitHub Desktop.
Flex Gap Polyfill
(
(
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