-
Notifications
You must be signed in to change notification settings - Fork 98
/
ToolTip.kt
508 lines (484 loc) · 18.6 KB
/
ToolTip.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
package com.microsoft.fluentui.tokenized.notification
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.Transition
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.MutatorMutex
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.paneTitle
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
import androidx.compose.ui.window.PopupProperties
import com.microsoft.fluentui.icons.ToolTipIcons
import com.microsoft.fluentui.icons.tooltipicons.Tip
import com.microsoft.fluentui.theme.FluentTheme
import com.microsoft.fluentui.theme.token.ControlTokens
import com.microsoft.fluentui.theme.token.Icon
import com.microsoft.fluentui.theme.token.controlTokens.TooltipInfo
import com.microsoft.fluentui.theme.token.controlTokens.TooltipTokens
import com.microsoft.fluentui.util.dpToPx
import com.microsoft.fluentui.util.pxToDp
import com.microsoft.fluentui.util.softNavBarOffsetX
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import androidx.compose.runtime.saveable.Saver
/**
* The state that is associated with an instance of a tooltip.
* Each instance of tooltips should have its own [TooltipState].
*/
@Stable
interface TooltipState {
/**
* [Boolean] that will be used to update the visibility
* state of the associated tooltip.
*/
val isVisible: Boolean
/**
* Show the tooltip associated with the current [TooltipState].
* When this method is called all of the other tooltips currently
* being shown will dismiss.
*/
suspend fun show()
/**
* Dismiss the tooltip associated with
* this [TooltipState] if it's currently being shown.
*/
fun dismiss()
/**
* Clean up when the this state leaves Composition.
*/
fun onDispose()
}
@Stable
internal class TooltipStateImpl(private val mutatorMutex: MutatorMutex) : TooltipState {
/**
* [Boolean] that will be used to update the visibility
* state of the associated tooltip.
*/
override var isVisible by mutableStateOf(false)
private set
/**
* continuation used to clean up
*/
private var job: (CancellableContinuation<Unit>)? = null
/**
* Show the tooltip associated with the current [TooltipState].
* It will dismiss after a short duration. When this method is called,
* all of the other tooltips currently being shown will dismiss.
*/
override suspend fun show() {
mutatorMutex.mutate {
try {
suspendCancellableCoroutine { continuation: CancellableContinuation<Unit> ->
isVisible = true
job = continuation
}
} finally {
// cancellation has occurred
// and we close out the current tooltip.
isVisible = false
}
}
}
/**
* Dismiss the tooltip associated with
* this [TooltipState] if it's currently being shown.
*/
override fun dismiss() {
isVisible = false
}
/**
* Cleans up [MutatorMutex] when the tooltip associated
* with this state leaves Composition.
*/
override fun onDispose() {
job?.cancel()
}
}
object TooltipDefaults {
/**
* The global/default [MutatorMutex] used to sync Tooltips.
*/
val GlobalMutatorMutex = MutatorMutex()
}
val TOOLTIP_TIP_TEST_TAG = "tooltip_tip_test_tag"
val TOOLTIP_CONTENT_TEST_TAG = "tooltip_content_test_tag"
/**
* Create and remember the default [TooltipState].
*
* @param mutatorMutex [MutatorMutex] used to ensure that for all of the tooltips associated
* with the mutator mutex, only one will be shown on the screen at any time.
*/
@Composable
fun rememberTooltipState(
mutatorMutex: MutatorMutex = TooltipDefaults.GlobalMutatorMutex
): TooltipState =
remember { TooltipStateImpl(mutatorMutex) }
/**
* ToolTipBox is a composable that shows a tooltip box with a title and a text anchor to its content.
* @param title The title of the tooltip box.
* @param text The text of the tooltip box.
* @param tooltipState The state of the tooltip box.
* @param modifier The modifier to be applied to the tooltip box.
* @param focusable Whether the tooltip box is focusable.
* @param offset The offset of the tooltip box.
* @param tipOffset The X offset to move tip icon relative to the tooltip box.
* @param onDismissRequest The callback to be invoked when the tooltip box is dismissed.
* @param tooltipTokens The tooltip tokens that are used to customize the tooltip box.
* @param content The content of the tooltip box.*
*/
@Composable
fun ToolTipBox(
title: String?,
text: String,
tooltipState: TooltipState,
modifier: Modifier = Modifier,
focusable: Boolean = true,
offset: DpOffset = DpOffset(0.dp, 0.dp),
tipOffset: Dp = 0.dp,
onDismissRequest: (() -> Unit)? = null,
tooltipTokens: TooltipTokens? = null,
content: @Composable () -> Unit,
) {
val themeID =
FluentTheme.themeID //Adding This only for recomposition in case of Token Updates. Unused otherwise.
val token = tooltipTokens
?: FluentTheme.controlTokens.tokens[ControlTokens.ControlType.TooltipControlType] as TooltipTokens
val tooltipInfo = TooltipInfo()
ToolTipBox(
tooltipContent = {
Column(
modifier = Modifier
.semantics(mergeDescendants = true) {}
.padding(token.padding(tooltipInfo = tooltipInfo))
.width(IntrinsicSize.Max),
) {
if (!title.isNullOrBlank()) {
BasicText(
text = title,
style = token.titleTypography(tooltipInfo = tooltipInfo).merge(
TextStyle(color = token.titleColor(tooltipInfo = tooltipInfo))
)
)
Spacer(
modifier = Modifier
.fillMaxWidth()
.height(
token.titleTextSpacing(
tooltipInfo = tooltipInfo
)
)
)
}
BasicText(
text = text, style = token.textTypography(tooltipInfo = tooltipInfo).merge(
TextStyle(color = token.textColor(tooltipInfo = tooltipInfo))
)
)
}
},
tooltipState = tooltipState,
modifier = modifier,
focusable = focusable,
offset = offset,
tipOffset = tipOffset,
onDismissRequest = onDismissRequest,
tooltipTokens = token,
content = content
)
}
/**
* ToolTipBox is a composable that shows a tooltipContent anchored to its content.
* @param tooltipContent The content of the tooltip box.
* @param tooltipState The state of the tooltip box.
* @param modifier The modifier to be applied to the tooltip box.
* @param focusable Whether the tooltip box is focusable.
* @param offset The offset of the tooltip box.
* @param onDismissRequest The callback to be invoked when the tooltip box is dismissed.
* @param tooltipTokens The tooltip tokens that are used to customize the tooltip box.
* @param content The content of the tooltip box.*
*/
@Composable
fun ToolTipBox(
tooltipContent: @Composable () -> Unit,
tooltipState: TooltipState,
modifier: Modifier = Modifier,
focusable: Boolean = true,
offset: DpOffset = DpOffset(0.dp, 0.dp),
tipOffset: Dp = 0.dp,
onDismissRequest: (() -> Unit)? = null,
tooltipTokens: TooltipTokens? = null,
content: @Composable () -> Unit,
) {
val themeID =
FluentTheme.themeID //Adding This only for recomposition in case of Token Updates. Unused otherwise.
Box {
content()
if (tooltipState.isVisible) {
Tooltip(
tooltipContent = tooltipContent,
tooltipState = tooltipState,
modifier = modifier,
focusable = focusable,
offset = offset,
tipOffset = tipOffset,
onDismissRequest = onDismissRequest,
tooltipTokens = tooltipTokens
)
}
}
}
val TipAlignmentSaver = Saver<Alignment, Boolean>(
save = { alignment ->
alignment == Alignment.TopCenter
},
restore = { savedValue ->
if (savedValue) Alignment.TopCenter else Alignment.BottomCenter
}
)
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun Tooltip(
tooltipContent: @Composable () -> Unit,
tooltipState: TooltipState,
modifier: Modifier = Modifier,
focusable: Boolean = true,
offset: DpOffset = DpOffset(0.dp, 0.dp),
tipOffset: Dp = 0.dp,
onDismissRequest: (() -> Unit)? = null,
tooltipTokens: TooltipTokens? = null,
) {
val token = tooltipTokens
?: FluentTheme.controlTokens.tokens[ControlTokens.ControlType.TooltipControlType] as TooltipTokens
val tooltipInfo = TooltipInfo()
var tipAlignment: Alignment by rememberSaveable(stateSaver = TipAlignmentSaver) {
mutableStateOf(Alignment.TopCenter)
}
var tipOffsetX by rememberSaveable { mutableStateOf(0.0f) }
val isRTL = LocalLayoutDirection.current == LayoutDirection.Rtl
val tooltipPositionProvider =
TooltipPositionProvider(
offset,
token.margin(tooltipInfo),
LocalContext.current.softNavBarOffsetX,
) { parentBounds, tooltipContentBounds ->
tipAlignment =
if (parentBounds.top + parentBounds.height / 2 <= tooltipContentBounds.top) {
Alignment.TopCenter
} else {
Alignment.BottomCenter
}
val parentCenter = parentBounds.left + parentBounds.width / 2
val tooltipCenter = tooltipContentBounds.left + tooltipContentBounds.width / 2
tipOffsetX = dpToPx(offset.x) + dpToPx(tipOffset) + if (isRTL) (tooltipCenter - parentCenter).toFloat() else
(parentCenter - tooltipCenter).toFloat()
if(tipOffsetX + tooltipCenter > tooltipContentBounds.right - dpToPx(24.dp)){
tipOffsetX = tooltipContentBounds.right - tooltipCenter - dpToPx(24.dp)
}
else if(tipOffsetX + tooltipCenter < tooltipContentBounds.left + dpToPx(24.dp)) {
tipOffsetX = tooltipContentBounds.left - tooltipCenter + dpToPx(24.dp)
}
}
val coroutineScope = rememberCoroutineScope()
val transition = updateTransition(tooltipState.isVisible, label = "Tooltip transition")
if (transition.currentState || transition.targetState) {
val tooltipPaneDescription = "ToolTip"
Popup(
popupPositionProvider = tooltipPositionProvider,
properties = PopupProperties(
focusable = focusable,
dismissOnClickOutside = true
),
onDismissRequest = {
if (tooltipState.isVisible) {
coroutineScope.launch { tooltipState.dismiss() }
if (onDismissRequest != null) {
onDismissRequest()
}
}
}
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.semantics {
testTagsAsResourceId = true
}) {
if (tipAlignment == Alignment.TopCenter) {
Icon(
imageVector = ToolTipIcons.Tip,
contentDescription = null,
tint = token.tipColor(tooltipInfo),
modifier = Modifier
.offset { IntOffset(x = tipOffsetX.toInt(), y = 1) }
.testTag(TOOLTIP_TIP_TEST_TAG)
)
}
Box(
modifier = modifier
.sizeIn(
minWidth = 40.dp,
maxWidth = token.maxWidth(tooltipInfo),
minHeight = 24.dp
)
.animateTooltip(transition)
.semantics { paneTitle = tooltipPaneDescription }
.background(
token.backgroundBrush(tooltipInfo),
shape = RoundedCornerShape(token.cornerRadius(tooltipInfo))
)
.testTag(TOOLTIP_CONTENT_TEST_TAG)
)
{
tooltipContent()
}
if (tipAlignment == Alignment.BottomCenter) {
Icon(
imageVector = ToolTipIcons.Tip, contentDescription = null,
tint = token.tipColor(tooltipInfo),
modifier = Modifier
.offset { IntOffset(x = tipOffsetX.toInt(), y = -1) }
.rotate(180f)
.testTag(TOOLTIP_TIP_TEST_TAG)
)
}
}
}
}
DisposableEffect(tooltipState) {
onDispose {
tooltipState.onDispose()
}
}
}
private class TooltipPositionProvider(
val tooltipAnchorOffset: DpOffset,
val margin: Dp = 0.dp,
val softNavBarOffsetX: Int,
val onPositionCalculated: (IntRect, IntRect) -> Unit = { _, _ -> }
) : PopupPositionProvider {
override fun calculatePosition(
anchorBounds: IntRect,
windowSize: IntSize,
layoutDirection: LayoutDirection,
popupContentSize: IntSize
): IntOffset {
val marginPx = dpToPx(margin).toInt()
var x = anchorBounds.left + ((anchorBounds.width - popupContentSize.width) / 2) + dpToPx(
tooltipAnchorOffset.x
).toInt()
// If the tooltip goes out of window then we align it to the left or right
if (x < marginPx + softNavBarOffsetX) {
x = marginPx + softNavBarOffsetX //Left Align
} else if (x + popupContentSize.width + marginPx - softNavBarOffsetX > windowSize.width) {
x =
windowSize.width - marginPx - popupContentSize.width + softNavBarOffsetX //Right Align
}
// Tooltip prefers to be below the anchor,
// but if this causes the tooltip to out from window bounds,
// then we place it above the anchor
var y = anchorBounds.bottom + dpToPx(tooltipAnchorOffset.y).toInt()
if (y + popupContentSize.height + marginPx > windowSize.height)
y = anchorBounds.top - popupContentSize.height - dpToPx(tooltipAnchorOffset.y).toInt()
onPositionCalculated(
anchorBounds,
IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height)
)
return IntOffset(x, y)
}
}
private const val TooltipFadeInDuration = 150
private const val TooltipFadeOutDuration = 75
private fun Modifier.animateTooltip(
transition: Transition<Boolean>
): Modifier = composed(
inspectorInfo = debugInspectorInfo {
name = "animateTooltip"
properties["transition"] = transition
}
) {
val scale by transition.animateFloat(
transitionSpec = {
if (false isTransitioningTo true) {
// show tooltip
tween(
durationMillis = TooltipFadeInDuration,
easing = LinearOutSlowInEasing
)
} else {
// dismiss tooltip
tween(
durationMillis = TooltipFadeOutDuration,
easing = LinearOutSlowInEasing
)
}
},
label = "tooltip transition: scaling"
) { if (it) 1f else 0.8f }
val alpha by transition.animateFloat(
transitionSpec = {
if (false isTransitioningTo true) {
// show tooltip
tween(
durationMillis = TooltipFadeInDuration,
easing = LinearEasing
)
} else {
// dismiss tooltip
tween(
durationMillis = TooltipFadeOutDuration,
easing = LinearEasing
)
}
},
label = "tooltip transition: alpha"
) { if (it) 1f else 0f }
return@composed this.graphicsLayer(
scaleX = scale,
scaleY = scale,
alpha = alpha
)
}