Created
June 29, 2021 13:31
-
-
Save Pitel/d5016cc6af0d0cc20e21151db5189760 to your computer and use it in GitHub Desktop.
MediaQueryStore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dev.fritz2.binding.RootStore | |
import dev.fritz2.styling.theme.Theme | |
import kotlinx.browser.window | |
import kotlinx.coroutines.ExperimentalCoroutinesApi | |
import kotlinx.coroutines.MainScope | |
import kotlinx.coroutines.flow.distinctUntilChanged | |
import kotlinx.coroutines.flow.launchIn | |
import kotlinx.coroutines.flow.map | |
import kotlinx.coroutines.flow.onEach | |
import kotlinx.coroutines.plus | |
import org.w3c.dom.MediaQueryListEvent | |
import org.w3c.dom.events.EventListener | |
@OptIn(ExperimentalCoroutinesApi::class) | |
object MediaQueryStore : RootStore<MediaQueryStore.Breakpoint>(Breakpoint.SM) { | |
enum class Breakpoint { | |
SM, | |
MD, | |
LG, | |
XL | |
} | |
val md = data.map { | |
it.ordinal >= Breakpoint.MD.ordinal | |
}.distinctUntilChanged() | |
val lg = data.map { | |
it.ordinal >= Breakpoint.LG.ordinal | |
}.distinctUntilChanged() | |
val xl = data.map { | |
it.ordinal >= Breakpoint.XL.ordinal | |
}.distinctUntilChanged() | |
private const val MEDIA_PREFIX = "@media" | |
private val mdListener = EventListener { | |
update( | |
if ((it as MediaQueryListEvent).matches) { | |
Breakpoint.MD | |
} else { | |
Breakpoint.SM | |
} | |
) | |
} | |
private val lgListener = EventListener { | |
update( | |
if ((it as MediaQueryListEvent).matches) { | |
Breakpoint.LG | |
} else { | |
Breakpoint.MD | |
} | |
) | |
} | |
private val xlListener = EventListener { | |
update( | |
if ((it as MediaQueryListEvent).matches) { | |
Breakpoint.XL | |
} else { | |
Breakpoint.LG | |
} | |
) | |
} | |
private var mdMedia = window.matchMedia("") | |
private var lgMedia = window.matchMedia("") | |
private var xlMedia = window.matchMedia("") | |
init { | |
Theme.data.onEach { theme -> | |
mdMedia.removeListener(mdListener) | |
mdMedia = window.matchMedia(theme.mediaQueryMd.removePrefix(MEDIA_PREFIX)).apply { | |
addListener(mdListener) | |
} | |
lgMedia.removeListener(lgListener) | |
lgMedia = window.matchMedia(theme.mediaQueryLg.removePrefix(MEDIA_PREFIX)).apply { | |
addListener(lgListener) | |
} | |
xlMedia.removeListener(xlListener) | |
xlMedia = window.matchMedia(theme.mediaQueryXl.removePrefix(MEDIA_PREFIX)).apply { | |
addListener(xlListener) | |
} | |
update( | |
when { | |
xlMedia.matches -> Breakpoint.XL | |
lgMedia.matches -> Breakpoint.LG | |
mdMedia.matches -> Breakpoint.MD | |
else -> Breakpoint.SM | |
} | |
) | |
}.launchIn(MainScope() + job) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment