Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -367,15 +367,16 @@ fun <T> SwitchEnumState(values: Array<T>, state: MutableState<T>, modifier: Modi
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopBarBasic() {
val accentColor = topBarAccentColor()
CenterAlignedTopAppBar(
navigationIcon = {
Text("Text", color = Color.Blue)
Text("Text", color = accentColor)
},
title = { Text("Chats", fontWeight = FontWeight.Bold) },
actions = {
val modifier = Modifier.padding(horizontal = 10.dp)
Icon(Icons.Outlined.Phone, null, modifier, Color.Blue)
Icon(Icons.Outlined.Edit, null, modifier, Color.Blue)
Icon(Icons.Outlined.Phone, null, modifier, accentColor)
Icon(Icons.Outlined.Edit, null, modifier, accentColor)
}
)
}
Expand All @@ -384,6 +385,7 @@ fun TopBarBasic() {
@Composable
fun TopBarWithGradient() {
val bgColor = MaterialTheme.colorScheme.background
val accentColor = topBarAccentColor()
val green = Color.Green.copy(0.5f).compositeOver(bgColor)
val blue = Color.Blue.copy(0.5f).compositeOver(bgColor)
Box(
Expand All @@ -392,8 +394,8 @@ fun TopBarWithGradient() {
CenterAlignedTopAppBar(
navigationIcon = {
Row {
Icon(Icons.Default.ArrowBack, null, tint = Color.Blue)
Text("Back", color = Color.Blue)
Icon(Icons.Default.ArrowBack, null, tint = accentColor)
Text("Back", color = accentColor)
}
},
title = {
Expand All @@ -404,12 +406,16 @@ fun TopBarWithGradient() {
},
actions = {
val modifier = Modifier.padding(horizontal = 10.dp)
Icon(Icons.Outlined.Phone, null, modifier, Color.Blue)
Icon(Icons.Outlined.Edit, null, modifier, Color.Blue)
Icon(Icons.Outlined.Phone, null, modifier, accentColor)
Icon(Icons.Outlined.Edit, null, modifier, accentColor)
},
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
containerColor = Color.Transparent
)
)
}
}

@Composable
private fun topBarAccentColor(): Color =
if (isSystemInDarkTheme()) Color(0xFF8AB4F8) else Color.Blue
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package androidx.compose.mpp.demo

import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
Expand Down Expand Up @@ -154,11 +155,21 @@ private fun ExampleTopBar(
back: () -> Unit,
) {
TopAppBar(
backgroundColor = topAppBarBackgroundColor(),
contentColor = topAppBarContentColor(),
title = { Text(title) },
navigationIcon = { ArrowBackIcon(back) }
)
}

@Composable
private fun topAppBarBackgroundColor(): Color =
if (isSystemInDarkTheme()) Color(0xFF3F1D6E) else MaterialTheme.colors.primary

@Composable
private fun topAppBarContentColor(): Color =
if (isSystemInDarkTheme()) Color.White else MaterialTheme.colors.onPrimary

@Composable
private fun SelectionScaffold(
title: String,
Expand Down Expand Up @@ -191,6 +202,8 @@ private fun SelectionTopBar(
* out of box in android development or with Material3 Scaffold
*/
TopAppBar(
backgroundColor = topAppBarBackgroundColor(),
contentColor = topAppBarContentColor(),
contentPadding = WindowInsets.systemBars
.only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal)
.union(WindowInsets(left = 20.dp))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
package androidx.compose.ui.events

import kotlin.js.js
import kotlinx.browser.document
import kotlinx.browser.window
import org.w3c.dom.AddEventListenerOptions
import org.w3c.dom.events.Event
import org.w3c.dom.events.EventTarget
Expand Down Expand Up @@ -56,5 +54,4 @@ internal class EventTargetListener(private val eventTarget: EventTarget) {
fun dispose() {
abortController.abort()
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -110,15 +110,13 @@ import kotlinx.coroutines.flow.receiveAsFlow
import org.jetbrains.skiko.SkiaLayer
import org.jetbrains.skiko.SkikoRenderDelegate
import org.jetbrains.skiko.hostOs
import org.w3c.dom.AddEventListenerOptions
import org.w3c.dom.DocumentReadyState
import org.w3c.dom.Element
import org.w3c.dom.HTMLCanvasElement
import org.w3c.dom.HTMLDivElement
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLTextAreaElement
import org.w3c.dom.LOADING
import org.w3c.dom.MediaQueryListEvent
import org.w3c.dom.Node
import org.w3c.dom.TouchEvent
import org.w3c.dom.events.Event
Expand All @@ -128,6 +126,7 @@ import org.w3c.dom.events.KeyboardEvent
import org.w3c.dom.events.MouseEvent
import org.w3c.dom.events.WheelEvent
import org.w3c.dom.pointerevents.PointerEvent
import androidx.compose.ui.window.MediaQueryListener

private val actualDensity
get() = window.devicePixelRatio
Expand All @@ -153,15 +152,15 @@ internal class DefaultWindowState(private val viewportContainer: Element) : Comp

override val globalEvents = EventTargetListener(window)

private var mediaQueryListener: MediaQueryListener? = null

override fun init() {

globalEvents.addDisposableEvent("resize") {
channel.trySend(getParentContainerBox())
}

initMediaEventListener {
channel.trySend(getParentContainerBox())
}
recreateMediaQueryListener()

channel.trySend(getParentContainerBox())
}
Expand All @@ -170,16 +169,22 @@ internal class DefaultWindowState(private val viewportContainer: Element) : Comp
return IntSize(viewportContainer.clientWidth, viewportContainer.clientHeight)
}

private fun initMediaEventListener(handler: (Double) -> Unit) {
private fun recreateMediaQueryListener() {
mediaQueryListener?.dispose()
val contentScale = actualDensity
window.matchMedia("(resolution: ${contentScale}dppx)")
.addEventListener("change", { evt ->
evt as MediaQueryListEvent
if (!evt.matches) {
handler(contentScale)
mediaQueryListener = object : MediaQueryListener("(resolution: ${contentScale}dppx)") {
override fun onChange(matches: Boolean) {
if (!matches) {
channel.trySend(getParentContainerBox())
}
initMediaEventListener(handler)
}, AddEventListenerOptions(capture = true, once = true))
recreateMediaQueryListener()
}
}
}

override fun dispose() {
mediaQueryListener?.dispose()
super.dispose()
}

override fun sizeFlow() = channel.receiveAsFlow()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package androidx.compose.ui.window

import kotlin.js.js
import kotlinx.browser.window
import org.w3c.dom.MediaQueryList
import org.w3c.dom.MediaQueryListEvent
import org.w3c.dom.events.Event

internal abstract class MediaQueryListener(private val query: String) {
private val media: MediaQueryList by lazy {
window.matchMedia(query)
}

abstract fun onChange(matches: Boolean)

private val listener: (Event) -> Unit = { event ->
event as MediaQueryListEvent
onChange(event.matches)
}

fun dispose() {
try {
media.removeEventListener("change", listener)
} catch (t : Throwable) {
media.removeListener(listener)
}
}
Comment thread
Copilot marked this conversation as resolved.

init {
if (isMatchMediaSupported()) {
try {
media.addEventListener("change", listener)
} catch (t: Throwable) {
media.addListener(listener)
}
}
}

fun matches(): Boolean? {
return when {
!isMatchMediaSupported() -> null
else -> media.matches
}
}
}

// supported by all browsers since 2015
// https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
// Changed from `@JsFun` annotation because in 2.2.20 it's marked as not available on LV = 2.0
// TODO: Cannot add opt-in with LV = 2.0 due to https://youtrack.jetbrains.com/issue/KT-79716
private fun isMatchMediaSupported(): Boolean = js("window.matchMedia != undefined")
Original file line number Diff line number Diff line change
Expand Up @@ -18,68 +18,35 @@ package androidx.compose.ui.window

import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import kotlin.js.js
import kotlinx.browser.window
import org.jetbrains.skiko.SystemTheme
import org.w3c.dom.MediaQueryList
import org.w3c.dom.MediaQueryListEvent
import org.w3c.dom.Window
import org.w3c.dom.events.Event

internal interface SystemThemeObserver {
val currentSystemTheme: State<SystemTheme>

fun dispose()
}

internal class SystemThemeObserverImpl(window : Window) : SystemThemeObserver {

private class SystemThemeObserverImpl : SystemThemeObserver {
override val currentSystemTheme: State<SystemTheme>
get() = _currentSystemTheme

private val media: MediaQueryList by lazy {
window.matchMedia("(prefers-color-scheme: dark)")
private val mediaQueryListener: MediaQueryListener = object : MediaQueryListener("(prefers-color-scheme: dark)") {
override fun onChange(matches: Boolean) {
_currentSystemTheme.value = if (matches) SystemTheme.DARK else SystemTheme.LIGHT
}
}

private val _currentSystemTheme = mutableStateOf(
when {
!isMatchMediaSupported() -> SystemTheme.UNKNOWN
media.matches -> SystemTheme.DARK
else -> SystemTheme.LIGHT
when(mediaQueryListener.matches()) {
true -> SystemTheme.DARK
false -> SystemTheme.LIGHT
else -> SystemTheme.UNKNOWN

@eymar Oleksandr Karpovich (eymar) Jul 15, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a bit confusing to see a third branch when first 2 branches already cover true and false.
Then I looked at the matches() method and noticed that it returns Boolean?.

What do you think about creating a value class for the returned value?

For example:

internal value class MediaQuery private constuctor(private val matchResult: Int) {
    companion object {
          val NOT_SUPPORTED = MediaQuery(-1)
          val NO_MATCH = MediaQuery(0)
          val MATCH = MediaQuery(1)
    }
}

then your when becomes:

when(mediaQueryListener.matches()) {
            MATCH -> SystemTheme.DARK
            NO_MATCH -> SystemTheme.LIGHT
            else -> SystemTheme.UNKNOWN
}

@eymar Oleksandr Karpovich (eymar) Jul 15, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or maybe it's not the responsibility of fun matches to notify about the unsupported state.
MediaQueryListener might have a static method for checking if queries are supported.

Then fun matches will return a Boolean without ?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isMatchMediaSupported can be even evaluated once (by lazy) and reused in elsewhere.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I absolutely don't mind having dedicated status if it's not overkill - Boolean? though is more or less an idiom for yes/no/we-don't-know but sure, performance-wise we won't lose anything and may be it will be clearer

}
)

private val listener: (Event) -> Unit = { event ->
_currentSystemTheme.value = if ((event as MediaQueryListEvent).matches)
SystemTheme.DARK else SystemTheme.LIGHT
}

override fun dispose() {
if (isMatchMediaSupported()) {
try {
media.removeEventListener("change", listener)
} catch (t : Throwable) {
media.removeListener(listener)
}
}
}

init {
if (isMatchMediaSupported()) {
try {
media.addEventListener("change", listener)
} catch (t: Throwable) {
media.addListener(listener)
}
}
mediaQueryListener.dispose()
}
}

internal fun getSystemThemeObserver(): SystemThemeObserver =
SystemThemeObserverImpl(window)

// supported by all browsers since 2015
// https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
// Changed from `@JsFun` annotation because in 2.2.20 it's marked as not available on LV = 2.0
// TODO: Cannot add opt-in with LV = 2.0 due to https://youtrack.jetbrains.com/issue/KT-79716
private fun isMatchMediaSupported(): Boolean = js("window.matchMedia != undefined")
internal fun getSystemThemeObserver(): SystemThemeObserver = SystemThemeObserverImpl()
Loading