Skip to content

Instantly share code, notes, and snippets.

@liampmccabe
Created August 5, 2024 12:33
Show Gist options
  • Select an option

  • Save liampmccabe/628e90e81af150037faea8c5fec877cc to your computer and use it in GitHub Desktop.

Select an option

Save liampmccabe/628e90e81af150037faea8c5fec877cc to your computer and use it in GitHub Desktop.
const remixLocation = useLocation()
const [source, setSource] = useState<any>(null)
const [items, setItems] = useState<any[]>(layers ?? [])
const [activeLayer, setActiveLayer] = useState<any>(null)
/**
* Listen to popstate event and set active layer
*/
useEffect(() => {
function back() {
const id = location.pathname.split('/')[2]
const index = items.findIndex(item => item.id === id)
if (index > -1) {
setActiveLayer(items[index])
}
}
window.addEventListener('popstate', back)
if (location.pathname !== '/search') {
setSource(location.pathname)
}
return () => {
window.removeEventListener('popstate', back)
}
}, [])
/**
* Listen to location change and set active layer
*/
useEffect(() => {
const id = remixLocation.pathname.split('/')[2]
if (!id) {
setActiveLayer(null)
}
}, [remixLocation])
/**
* Open layer page
*
* @param layer
*/
function onLayerChange(layer: Layer) {
setActiveLayer(layer)
}
/**
* Close layer page
*/
function onClose() {
setActiveLayer(null)
if (source) {
history.pushState({}, '', source)
}
}
/**
* Navigate to next layer
*/
function onNextLayer() {
const id = location.pathname.split('/')[2]
const index = items.findIndex(item => item.id === id)
if (index < items.length - 1) {
setActiveLayer(items[index + 1])
history.pushState({}, '', `/layers/${items[index + 1].id}`)
}
}
/**
* Navigate to previous layer
*/
function onPreviousLayer() {
const id = location.pathname.split('/')[2]
const index = items.findIndex(item => item.id === id)
if (index > 0) {
setActiveLayer(items[index - 1])
history.pushState({}, '', `/layers/${items[index - 1].id}`)
}
}
const activeLayerIndex = items.findIndex(item => item.id === activeLayer?.id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment