-
Notifications
You must be signed in to change notification settings - Fork 629
/
BaseSheetActivity.kt
376 lines (328 loc) · 12.8 KB
/
BaseSheetActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package com.stripe.android.paymentsheet.ui
import android.content.pm.ActivityInfo
import android.content.res.ColorStateList
import android.graphics.Insets
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.WindowMetrics
import android.widget.ScrollView
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.view.isVisible
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.stripe.android.link.ui.verification.LinkVerificationDialog
import com.stripe.android.paymentsheet.BottomSheetController
import com.stripe.android.paymentsheet.R
import com.stripe.android.paymentsheet.viewmodels.BaseSheetViewModel
import com.stripe.android.ui.core.PaymentsTheme
import com.stripe.android.ui.core.PaymentsThemeDefaults
import com.stripe.android.ui.core.createTextSpanFromTextStyle
import com.stripe.android.ui.core.elements.H4Text
import com.stripe.android.ui.core.elements.Html
import com.stripe.android.ui.core.getBackgroundColor
import com.stripe.android.ui.core.isSystemDarkTheme
import com.stripe.android.ui.core.paymentsColors
import com.stripe.android.view.KeyboardController
import kotlin.math.roundToInt
internal abstract class BaseSheetActivity<ResultType> : AppCompatActivity() {
abstract val viewModel: BaseSheetViewModel<*>
@VisibleForTesting
internal val bottomSheetBehavior by lazy { BottomSheetBehavior.from(bottomSheet) }
protected val bottomSheetController: BottomSheetController by lazy {
BottomSheetController(bottomSheetBehavior = bottomSheetBehavior)
}
abstract val rootView: ViewGroup
abstract val bottomSheet: ViewGroup
abstract val appbar: AppBarLayout
abstract val linkAuthView: ComposeView
abstract val scrollView: ScrollView
abstract val toolbar: MaterialToolbar
abstract val messageView: TextView
abstract val header: ComposeView
abstract val fragmentContainerParent: ViewGroup
abstract val testModeIndicator: TextView
abstract val notesView: ComposeView
abstract val primaryButton: PrimaryButton
abstract val bottomSpacer: View
abstract fun setActivityResult(result: ResultType)
private val keyboardController: KeyboardController by lazy {
KeyboardController(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.registerFromActivity(this)
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
// In Oreo, Activities where `android:windowIsTranslucent=true` can't request
// orientation. See https://stackoverflow.com/a/50832408/11103900
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
supportFragmentManager.addOnBackStackChangedListener {
updateToolbarButton(supportFragmentManager.backStackEntryCount == 0)
}
scrollView.viewTreeObserver.addOnScrollChangedListener {
appbar.elevation = if (scrollView.scrollY > 0) {
resources.getDimension(R.dimen.stripe_paymentsheet_toolbar_elevation)
} else {
0f
}
}
bottomSheetController.setup()
bottomSheetController.shouldFinish.observe(this) { shouldFinish ->
if (shouldFinish) {
finish()
}
}
viewModel.processing.observe(this) { isProcessing ->
updateRootViewClickHandling(isProcessing)
toolbar.isEnabled = !isProcessing
}
// Set Toolbar to act as the ActionBar so it displays the menu items.
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
toolbar.setNavigationOnClickListener {
if (toolbar.isEnabled) {
if (supportFragmentManager.backStackEntryCount == 0) {
viewModel.onUserCancel()
} else {
onUserBack()
}
}
}
updateToolbarButton(supportFragmentManager.backStackEntryCount == 0)
setupHeader()
setupPrimaryButton()
setupNotes()
viewModel.showLinkVerificationDialog.observe(this) { show ->
linkAuthView.setContent {
if (show) {
viewModel.linkVerificationCallback?.let { callback ->
LinkVerificationDialog(
linkLauncher = viewModel.linkLauncher,
verificationCallback = callback
)
}
}
}
}
viewModel.contentVisible.observe(this) {
scrollView.isVisible = it
}
// Make `bottomSheet` clickable to prevent clicks on the bottom sheet from triggering
// `rootView`'s click listener
bottomSheet.isClickable = true
viewModel.liveMode.observe(this) { isLiveMode ->
testModeIndicator.visibility = if (isLiveMode) View.GONE else View.VISIBLE
}
val isDark = baseContext.isSystemDarkTheme()
viewModel.config?.let {
bottomSheet.setBackgroundColor(
Color(it.appearance.getColors(isDark).surface).toArgb()
)
toolbar.setBackgroundColor(
Color(it.appearance.getColors(isDark).surface).toArgb()
)
}
setSheetWidthForTablets()
}
override fun finish() {
super.finish()
overridePendingTransition(0, 0)
}
override fun onBackPressed() {
if (supportFragmentManager.backStackEntryCount > 0) {
clearErrorMessages()
super.onBackPressed()
} else {
viewModel.onUserCancel()
}
}
override fun onDestroy() {
super.onDestroy()
viewModel.unregisterFromActivity()
}
protected fun closeSheet(
result: ResultType
) {
// TODO(mlb): Consider if this needs to be an abstract function
setActivityResult(result)
bottomSheetController.hide()
}
open fun clearErrorMessages() {
updateErrorMessage(messageView)
}
protected fun updateErrorMessage(
messageView: TextView,
userMessage: BaseSheetViewModel.UserErrorMessage? = null
) {
userMessage?.message.let { message ->
viewModel.config?.appearance?.let {
messageView.text = createTextSpanFromTextStyle(
text = message,
context = this,
fontSizeDp = (
it.typography.sizeScaleFactor
* PaymentsThemeDefaults.typography.smallFontSize.value
).dp,
color = Color(it.getColors(this.isSystemDarkTheme()).error),
fontFamily = it.typography.fontResId
)
}
}
messageView.isVisible = userMessage != null
}
private fun setupHeader() {
header.apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
val text = viewModel.headerText.observeAsState()
text.value?.let {
PaymentsTheme {
H4Text(
text = it,
modifier = Modifier.padding(bottom = 2.dp)
)
}
}
}
}
}
/**
* Perform the initial setup for the primary button.
*/
private fun setupPrimaryButton() {
viewModel.primaryButtonUIState.observe(this) { state ->
state?.let {
primaryButton.setOnClickListener {
state.onClick?.invoke()
}
primaryButton.setLabel(state.label)
primaryButton.isVisible = state.visible
bottomSpacer.isVisible = state.visible
} ?: run {
resetPrimaryButtonState()
}
}
viewModel.primaryButtonState.observe(this) { state ->
primaryButton.updateState(state)
}
viewModel.ctaEnabled.observe(this) { isEnabled ->
primaryButton.isEnabled = isEnabled
}
primaryButton.setAppearanceConfiguration(
PaymentsTheme.primaryButtonStyle,
tintList = viewModel.config?.primaryButtonColor ?: ColorStateList.valueOf(
PaymentsTheme.primaryButtonStyle.getBackgroundColor(baseContext)
)
)
bottomSpacer.isVisible = true
}
/**
* Reset the primary button to its default state.
*/
abstract fun resetPrimaryButtonState()
private fun setupNotes() {
viewModel.notesText.observe(this) { text ->
val showNotes = text != null
text?.let {
notesView.setContent {
PaymentsTheme {
Html(
html = text,
imageGetter = mapOf(),
color = MaterialTheme.paymentsColors.subtitle,
style = MaterialTheme.typography.body1.copy(
textAlign = TextAlign.Center
)
)
}
}
}
notesView.isVisible = showNotes
}
}
private fun updateToolbarButton(isStackEmpty: Boolean) {
val toolbarResources = if (isStackEmpty) {
ToolbarResources(
R.drawable.stripe_paymentsheet_toolbar_close,
R.string.stripe_paymentsheet_close
)
} else {
ToolbarResources(
R.drawable.stripe_paymentsheet_toolbar_back,
R.string.stripe_paymentsheet_back
)
}
val navigationIconDrawable = AppCompatResources.getDrawable(this, toolbarResources.icon)
viewModel.config?.appearance?.let {
navigationIconDrawable?.setTintList(
ColorStateList.valueOf(
it.getColors(baseContext.isSystemDarkTheme()).appBarIcon
)
)
}
toolbar.navigationIcon = navigationIconDrawable
toolbar.navigationContentDescription = resources.getString(toolbarResources.description)
}
private fun updateRootViewClickHandling(isProcessing: Boolean) {
if (!isProcessing) {
// Handle taps outside of bottom sheet
rootView.setOnClickListener {
viewModel.onUserCancel()
}
} else {
rootView.setOnClickListener(null)
rootView.isClickable = false
}
}
private fun onUserBack() {
keyboardController.hide()
onBackPressed()
}
private fun setSheetWidthForTablets() {
if (!resources.getBoolean(R.bool.isTablet)) {
return
}
val screenWidth = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val windowMetrics: WindowMetrics = windowManager.currentWindowMetrics
val insets: Insets = windowMetrics.windowInsets
.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
windowMetrics.bounds.width() - insets.left - insets.right
} else {
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
displayMetrics.widthPixels
}
val params: ViewGroup.LayoutParams = bottomSheet.layoutParams
params.width = (screenWidth * TABLET_WIDTH_RATIO).roundToInt()
bottomSheet.layoutParams = params
}
internal companion object {
const val EXTRA_FRAGMENT_CONFIG = "com.stripe.android.paymentsheet.extra_fragment_config"
const val EXTRA_STARTER_ARGS = "com.stripe.android.paymentsheet.extra_starter_args"
const val TABLET_WIDTH_RATIO = .6
}
internal data class ToolbarResources(
@DrawableRes val icon: Int,
@StringRes val description: Int
)
}