|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 DuckDuckGo |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.duckduckgo.app.browser.omnibar.datastore |
| 18 | + |
| 19 | +import androidx.datastore.core.DataStore |
| 20 | +import androidx.datastore.preferences.core.Preferences |
| 21 | +import androidx.datastore.preferences.core.edit |
| 22 | +import androidx.datastore.preferences.core.stringPreferencesKey |
| 23 | +import com.duckduckgo.app.browser.omnibar.datastore.SharedPreferencesOmnibarDataStore.Keys.KEY_OMNIBAR_POSITION |
| 24 | +import com.duckduckgo.app.di.Omnibar |
| 25 | +import com.duckduckgo.browser.ui.omnibar.OmnibarPosition |
| 26 | +import com.duckduckgo.di.scopes.AppScope |
| 27 | +import com.squareup.anvil.annotations.ContributesBinding |
| 28 | +import dagger.SingleInstanceIn |
| 29 | +import kotlinx.coroutines.flow.Flow |
| 30 | +import kotlinx.coroutines.flow.first |
| 31 | +import kotlinx.coroutines.flow.map |
| 32 | +import kotlinx.coroutines.runBlocking |
| 33 | +import javax.inject.Inject |
| 34 | + |
| 35 | +interface OmnibarDataStore { |
| 36 | + suspend fun setOmnibarPosition(omnibarPosition: OmnibarPosition) |
| 37 | + val omnibarPositionFlow: Flow<OmnibarPosition> |
| 38 | + |
| 39 | + val omnibarPosition: OmnibarPosition |
| 40 | + get() = runBlocking { |
| 41 | + omnibarPositionFlow.first() |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +@ContributesBinding(AppScope::class) |
| 46 | +@SingleInstanceIn(AppScope::class) |
| 47 | +class SharedPreferencesOmnibarDataStore @Inject constructor( |
| 48 | + @Omnibar private val store: DataStore<Preferences>, |
| 49 | +) : OmnibarDataStore { |
| 50 | + |
| 51 | + private object Keys { |
| 52 | + val KEY_OMNIBAR_POSITION = stringPreferencesKey(name = "KEY_OMNIBAR_POSITION") |
| 53 | + } |
| 54 | + |
| 55 | + override suspend fun setOmnibarPosition(omnibarPosition: OmnibarPosition) { |
| 56 | + store.edit { it[KEY_OMNIBAR_POSITION] = omnibarPosition.name } |
| 57 | + } |
| 58 | + |
| 59 | + override val omnibarPositionFlow: Flow<OmnibarPosition> = store.data.map { preferences -> |
| 60 | + val positionName = preferences[KEY_OMNIBAR_POSITION] ?: OmnibarPosition.TOP.name |
| 61 | + OmnibarPosition.valueOf(positionName) |
| 62 | + } |
| 63 | +} |
0 commit comments