this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

at e28f6d2f370b4e882ed6f23d08ca0f8d94dbac5f 82 lines 2.1 kB view raw
1import {createContext, useContext, useMemo, useState} from 'react' 2import {nanoid} from 'nanoid/non-secure' 3 4import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' 5import {type ImageSource} from '#/view/com/lightbox/ImageViewing/@types' 6 7export type Lightbox = { 8 id: string 9 images: ImageSource[] 10 index: number 11} 12 13const LightboxContext = createContext<{ 14 activeLightbox: Lightbox | null 15}>({ 16 activeLightbox: null, 17}) 18LightboxContext.displayName = 'LightboxContext' 19 20const LightboxControlContext = createContext<{ 21 openLightbox: (lightbox: Omit<Lightbox, 'id'>) => void 22 closeLightbox: () => boolean 23}>({ 24 openLightbox: () => {}, 25 closeLightbox: () => false, 26}) 27LightboxControlContext.displayName = 'LightboxControlContext' 28 29export function Provider({children}: React.PropsWithChildren<{}>) { 30 const [activeLightbox, setActiveLightbox] = useState<Lightbox | null>(null) 31 32 const openLightbox = useNonReactiveCallback( 33 (lightbox: Omit<Lightbox, 'id'>) => { 34 setActiveLightbox(prevLightbox => { 35 if (prevLightbox) { 36 // Ignore duplicate open requests. If it's already open, 37 // the user has to explicitly close the previous one first. 38 return prevLightbox 39 } else { 40 return {...lightbox, id: nanoid()} 41 } 42 }) 43 }, 44 ) 45 46 const closeLightbox = useNonReactiveCallback(() => { 47 let wasActive = !!activeLightbox 48 setActiveLightbox(null) 49 return wasActive 50 }) 51 52 const state = useMemo( 53 () => ({ 54 activeLightbox, 55 }), 56 [activeLightbox], 57 ) 58 59 const methods = useMemo( 60 () => ({ 61 openLightbox, 62 closeLightbox, 63 }), 64 [openLightbox, closeLightbox], 65 ) 66 67 return ( 68 <LightboxContext.Provider value={state}> 69 <LightboxControlContext.Provider value={methods}> 70 {children} 71 </LightboxControlContext.Provider> 72 </LightboxContext.Provider> 73 ) 74} 75 76export function useLightbox() { 77 return useContext(LightboxContext) 78} 79 80export function useLightboxControls() { 81 return useContext(LightboxControlContext) 82}