jump-sdk / jetpack_compose_country_code_picker_emoji

Jetpack Compose Country Code Picker with Emoji Flags
https://jitpack.io/#jump-sdk/jetpack_compose_country_code_picker_emoji
Apache License 2.0
45 stars 13 forks source link

@Preview support requires mocking telephonyManager? #56

Closed adrianegraphene closed 5 months ago

adrianegraphene commented 5 months ago

I want to be able to Preview TogiCountryCodePicker in my project so I can make quick edits to the UI. When I try, I get the same bug that shows up on TogiCountryCodePickerPreview in this file.

ccp/src/main/java/com/togitech/ccp/component/TogiCountryCodePicker.kt

java.lang.AssertionError: Unsupported Service: phone   at com.android.layoutlib.bridge.android.BridgeContext.getSystemService(BridgeContext.java:719)
com.togitech.ccp.data.utils.CountryCodeUtilsKt.getTelephonyManager(CountryCodeUtils.kt:41)
com.togitech.ccp.data.utils.CountryCodeUtilsKt.getUserIsoCode(CountryCodeUtils.kt:26)
com.togitech.ccp.component.TogiCountryCodePickerKt.configureInitialCountry(TogiCountryCodePicker.kt:273)
com.togitech.ccp.component.TogiCountryCodePickerKt.access$configureInitialCountry(TogiCountryCodePicker.kt:1)

I can briefly work around it wrapping the TogiCountryCodePicker with

if (!LocalInspectionMode.current) {

and setting the @Preview to this

@Preview(device = Devices.PIXEL_4, showBackground = true, showSystemUi = true)
@Composable
private fun TogiCountryCodePickerPreview() {
    TogiCountryCodePicker(
        onValueChange = { _, _ -> },
        showCountryCode = true,
        showCountryFlag = true,
        showPlaceholder = true,
        includeOnly = null,
    )
}

but then I just see a UI. If anyone knows how to mock the telephony service or even put a static variable in the country code field when in Preview mode... I'd love to be able to use the @Preview here. Thanks for a great codebase otherwise!

I feel like a simple static string could be set here

@Suppress("SwallowedException", "TooGenericExceptionCaught", "Deprecation")
internal fun getUserIsoCode(context: Context): Iso31661alpha2 = try {
    val telephonyManager = context.telephonyManager
    telephonyManager?.networkCountryIso ?: telephonyManager?.simCountryIso
} catch (ex: Exception) {
    null
}.takeIf { !it.isNullOrBlank() } ?: context.resources.configuration.locale.country

but I'm just not seeing it right now. Thought I'd leave this here for others to see / contribute / comment.

hbmartin commented 5 months ago

Hi @adrianegraphene 👋 You should be able to sidestep this issue in previews by setting either initialCountryIsoCode or initialCountryPhoneCode, can you try that and see if it meets your requirements?