Files
housesof/src/atoms/ToggleLayout.svelte

86 lines
3.0 KiB
Svelte

<script>
import { onMount } from 'svelte'
// Variables
let toggleLayout
let layoutSetting
/*
** Run code on browser only
*/
onMount(() => {
// Get layout setting from storage
layoutSetting = (localStorage.getItem('photosLayout')) ? localStorage.getItem('photosLayout') : 'list'
// Variables
const layoutGridClass = 'photos--grid'
const layoutListClass = 'photos--list'
const grid = document.querySelector('.photos')
const toggle = document.querySelector('.toggle')
const pill = toggle.querySelector('.pill')
const activeButton = document.querySelector(`.toggle [data-layout="${layoutSetting}"]`)
// Init of first option
pill.style.width = activeButton.getBoundingClientRect().width + 'px'
pill.style.left = activeButton.getBoundingClientRect().left - toggle.getBoundingClientRect().left + 'px'
// Toggle layout
toggleLayout = event => {
const clicked = event.currentTarget
const type = clicked.dataset.layout
// Change the layout
switch (type) {
case 'grid':
grid.classList.add(layoutGridClass)
grid.classList.remove(layoutListClass)
break
case 'list':
grid.classList.add(layoutListClass)
grid.classList.remove(layoutGridClass)
break
default: break
}
// Animate the active pill
pill.style.width = clicked.getBoundingClientRect().width + 'px'
pill.style.left = clicked.getBoundingClientRect().left - toggle.getBoundingClientRect().left + 'px'
// Add/Remove active classes
document.querySelectorAll('.toggle button').forEach(button => button.classList.remove('active'))
clicked.classList.add('active')
// Remember this setting
localStorage.setItem('photosLayout', type)
}
})
</script>
<div class="toggle">
<button data-layout="list" class:active={layoutSetting === 'list'} on:click={toggleLayout}>
<svg xmlns="http://www.w3.org/2000/svg" width="19" height="17" viewBox="0 0 19 17">
<g class="anim">
<rect width="15" height="3"/>
<rect width="15" height="3" x="4" y="7"/>
<rect width="15" height="3" y="14"/>
</g>
</svg>
<span>List</span>
</button>
<button data-layout="grid" class:active={layoutSetting === 'grid'} on:click={toggleLayout}>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" viewBox="0 0 18 20">
<g class="anim">
<rect width="7" height="7"/>
<rect width="7" height="7" x="11" y="2"/>
<rect width="7" height="7" y="11"/>
<rect width="7" height="7" x="11" y="13"/>
</g>
</svg>
<span>Grid</span>
</button>
<div class="pill" aria-hidden="true" role="presentation"></div>
</div>