Skip to content

Commit

Permalink
Watch density change on the web (#1630)
Browse files Browse the repository at this point in the history
* feat: watch density change

* Small code cleanup and style changes

---------

Co-authored-by: huanglizhuo <[email protected]>
  • Loading branch information
JakeWharton and huanglizhuo authored Oct 24, 2023
1 parent 0f65d12 commit 68ecfeb
Showing 1 changed file with 29 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import kotlinx.coroutines.flow.update
import kotlinx.dom.clear
import org.w3c.dom.HTMLElement
import org.w3c.dom.MediaQueryList
import org.w3c.dom.events.Event

public fun HTMLElement.asRedwoodView(): RedwoodView<HTMLElement> {
checkNotNull(parentNode) {
Expand All @@ -42,6 +43,8 @@ private class RedwoodHTMLElementView(
private val _children = HTMLElementChildren(element)
override val children: Children<HTMLElement> get() = _children

private var pixelRatioQueryRemover: (() -> Unit)? = null

override val onBackPressedDispatcher: OnBackPressedDispatcher = object : OnBackPressedDispatcher {
override fun addCallback(onBackPressedCallback: OnBackPressedCallback): Cancellable {
// TODO Delegate `onBackPressedCallback` to browser
Expand Down Expand Up @@ -72,13 +75,37 @@ private class RedwoodHTMLElementView(
}
})

// TODO Watch density change
// https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#javascript_2
observePixelRatioChange()

// TODO Watch size change
// https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
}

private fun observePixelRatioChange() {
// From https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#javascript_2.

// Remove the listener based on the old pixel ratio, if it exists.
pixelRatioQueryRemover?.invoke()

// Create a media query based on the current pixel ratio value.
val pixelRatioQuery = window.matchMedia("(resolution: ${window.devicePixelRatio}dppx)")

val listener: (Event) -> Unit = { observePixelRatioChange() }
pixelRatioQuery.addEventListener("change", listener)
pixelRatioQueryRemover = {
pixelRatioQuery.removeEventListener("change", listener)
}

uiConfiguration.update { old ->
UiConfiguration(
darkMode = old.darkMode,
safeAreaInsets = old.safeAreaInsets,
viewportSize = old.viewportSize,
density = window.devicePixelRatio,
)
}
}

override fun reset() {
_children.remove(0, _children.widgets.size)

Expand Down

0 comments on commit 68ecfeb

Please sign in to comment.