diff --git a/CHANGELOG.md b/CHANGELOG.md index ff3f66e9794..0792f7d001b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## 0.23.1 +* `Coroutines`: + * `Compose`: + * Add `StyleSheetsAggregator` + ## 0.23.0 **THIS UPDATE MAY CONTAINS SOME BREAKING CHANGES (INCLUDING BREAKING CHANGES IN BYTECODE LAYER) RELATED TO UPDATE OF diff --git a/coroutines/compose/src/jsMain/kotlin/dev/inmo/micro_utils/coroutines/compose/StyleSheetsAggregator.kt b/coroutines/compose/src/jsMain/kotlin/dev/inmo/micro_utils/coroutines/compose/StyleSheetsAggregator.kt new file mode 100644 index 00000000000..9cc62b81acd --- /dev/null +++ b/coroutines/compose/src/jsMain/kotlin/dev/inmo/micro_utils/coroutines/compose/StyleSheetsAggregator.kt @@ -0,0 +1,66 @@ +package dev.inmo.micro_utils.coroutines.compose + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import dev.inmo.micro_utils.coroutines.SpecialMutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.debounce +import org.jetbrains.compose.web.css.CSSRulesHolder +import org.jetbrains.compose.web.css.Style +import org.jetbrains.compose.web.css.StyleSheet + +/** + * Aggregator of Compose CSS StyleSheet. Allowing to add [StyleSheet] in it and draw it in one place without requiring + * to add `Style(stylesheet)` on every compose function call + */ +object StyleSheetsAggregator { + private val _stylesFlow = SpecialMutableStateFlow>(emptySet()) + val stylesFlow: StateFlow> = _stylesFlow.asStateFlow() + + @Composable + fun draw() { + _stylesFlow.debounce(13L).collectAsState(emptySet()).value.forEach { + Style(it) + } + } + + /** + * Adding [styleSheet] into the [Set] of included stylesheets. If you called [enableStyleSheetsAggregator], + * new styles will be enabled in the document + */ + fun addStyleSheet(styleSheet: CSSRulesHolder) { + _stylesFlow.value += styleSheet + } + + /** + * Removed [styleSheet] into the [Set] of included stylesheets + */ + fun removeStyleSheet(styleSheet: CSSRulesHolder) { + _stylesFlow.value -= styleSheet + } +} + +/** + * Drawing [StyleSheetsAggregator] in place. You may pass [Set] of [CSSRulesHolder]/[StyleSheet]s as preset of styles + */ +@Composable +fun enableStyleSheetsAggregator( + stylesPreset: Set = emptySet(), +) { + remember { + stylesPreset.forEach { + StyleSheetsAggregator.addStyleSheet(it) + } + } + StyleSheetsAggregator.draw() +} + +/** + * Will include [this] [CSSRulesHolder]/[StyleSheet] in the [StyleSheetsAggregator] using its + * [StyleSheetsAggregator.addStyleSheet] + */ +fun CSSRulesHolder.includeInStyleSheetsAggregator() { + StyleSheetsAggregator.addStyleSheet(this) +}