• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2024 The Android Open Source Project
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.android.photopicker.util
18 
19 import androidx.compose.runtime.Composable
20 import androidx.compose.runtime.remember
21 import androidx.compose.ui.platform.LocalConfiguration
22 import java.text.DateFormat
23 import java.text.NumberFormat
24 import java.text.SimpleDateFormat
25 import java.util.Locale
26 
27 /**
28  * A helper class for localization tasks
29  *
30  * @property locale The locale to use for localization. Defaults to the device's default locale.
31  */
32 data class LocalizationHelper(private val locale: Locale = Locale.getDefault()) {
33 
34     private val numberFormat = NumberFormat.getInstance(locale)
35 
36     /**
37      * Returns a localized string representation of the given count.
38      *
39      * @param count The count to format.
40      * @return The localized string representation of the count.
41      */
getLocalizedCountnull42     fun getLocalizedCount(count: Int): String {
43         return numberFormat.format(count)
44     }
45 
46     /**
47      * Returns a localized date and time formatter.
48      *
49      * @param dateStyle The style of the date format (e.g., DateFormat.MEDIUM).
50      * @param timeStyle The style of the time format (e.g., DateFormat.SHORT).
51      * @return A DateFormat instance with the specified styles and locale.
52      */
getLocalizedDateTimeFormatternull53     fun getLocalizedDateTimeFormatter(dateStyle: Int, timeStyle: Int): DateFormat {
54         return SimpleDateFormat.getDateTimeInstance(dateStyle, timeStyle, locale)
55     }
56 }
57 
58 /**
59  * Provides a [LocalizationHelper] instance that is remembered and updated when the locale changes.
60  */
61 @Composable
rememberLocalizationHelpernull62 fun rememberLocalizationHelper(): LocalizationHelper {
63     val currentLocale = LocalConfiguration.current.locales.get(0) ?: Locale.getDefault()
64     return remember(currentLocale) { LocalizationHelper(locale = currentLocale) }
65 }
66