Skip to content

Instantly share code, notes, and snippets.

@bmcminn
Last active January 20, 2020 17:03
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 bmcminn/8f189f7283b839579934a4794ee81123 to your computer and use it in GitHub Desktop.
Save bmcminn/8f189f7283b839579934a4794ee81123 to your computer and use it in GitHub Desktop.
<script>
import Container from './Container.svelte'
</script>
<h1>App Name</h1>
<Container>
<div class:col-xs-3 class:col-md-2 class:col-lg-1>...</div>
<div class:col-xs-3 class:col-md-2 class:col-lg-1 class:hidden class:visible-md>...</div>
<div class:col-xs-3 class:col-md-2 class:col-lg-1>...</div>
</Container>
<script>
import { onMount, onDestroy } from 'svelte'
let debounceInMillis = 100
let debounceImmediately = true
export const gridXS = 'grid-xs'
export const gridSM = 'grid-sm'
export const gridMD = 'grid-md'
export const gridLG = 'grid-lg'
export const gridXL = 'grid-xl'
export let sizeXS = 480
export let sizeSM = 768
export let sizeMD = 1024
export let sizeLG = 1440
export let sizeXL = 1980
let isXS = false
let isSM = false
let isMD = false
let isLG = false
let isXL = false
let container
onMount(() => {
resizeObserver.observe(container)
measureBox(container)
})
onDestroy(() => {
resizeObserver.unobserve(container)
})
/**
* Debounces a given callback by time in milliseconds
* @sauce: https://davidwalsh.name/javascript-debounce-function
* @sauce: http://underscorejs.org/#debounce
* @param {function} cb Callback to be fired once the debounce has lapsed
* @param {number} wait Debounce delay in milliseconds
* @param {boolean} immediate Whether to trigger the callback before or after the delay
* @return {null}
*/
const debounce = (cb, wait, immediate) => {
var timeout
return function() {
var context = this, args = arguments
var later = function() {
timeout = null
if (!immediate) cb.apply(context, args)
}
var callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) cb.apply(context, args)
}
}
const resizeObserver = new ResizeObserver(debounce((entries) => {
measureBox(container)
// for (let entry of entries) {
// if (entry.contentBoxSize) {
// ...
// } else {
// ...
// }
// }
}), debounceInMillis, debounceImmediately)
const measureBox = (el) => {
let width = el.clientWidth
isXS = 0 < width && width <= sizeXS
isSM = sizeXS < width && width <= sizeSM
isMD = sizeSM < width && width <= sizeMD
isLG = sizeMD < width && width <= sizeLG
isXL = sizeLG < width && width <= sizeXL
}
</script>
<style>
:global(.hidden) { display: none }
:global(.grid-xs) > .hidden-xs { display: none }
:global(.grid-xs) > .visible-xs { display: block }
</style>
<div bind:this={container}
class:grid-xs={isXS}
class:grid-sm={isSM}
class:grid-md={isMD}
class:grid-lg={isLG}
class:grid-xl={isXL}
>
<slot></slot>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment