-
Notifications
You must be signed in to change notification settings - Fork 9
/
toggle.kt
481 lines (453 loc) · 13.8 KB
/
toggle.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
/*
* Designed and developed by 2022 SungbinLand, Team Duckie
*
* Licensed under the MIT.
* Please see full license: https://github.com/duckie-team/quack-quack-android/blob/master/LICENSE
*/
package team.duckie.quackquack.ui.component
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.snap
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathMeasure
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import kotlin.math.floor
import team.duckie.quackquack.ui.animation.QuackAnimationSpec
import team.duckie.quackquack.ui.border.QuackBorder
import team.duckie.quackquack.ui.color.QuackColor
import team.duckie.quackquack.ui.icon.QuackIcon
private const val TransitionLabel = "CheckTransition"
private const val BoxOutDuration = 100
private val RoundCheckboxSize = 28.dp
private val SquareCheckboxSize = 18.dp
private val IconSize = 24.dp
private val SmallIconSize = 18.dp
private val StrokeWidth = 1.5.dp
private val ToggleTitleSpace = 5.dp
private val QuackIconTextToggleSpacing = 4.dp
private const val CheckCrossX = 0.4f
private const val CheckCrossY = 0.7f
private const val LeftX = 0.25f
private const val LeftY = 0.55f
private const val RightX = 0.75f
private const val RightY = 0.35f
private const val StopLocation = 0.5f
private const val RoundCheckBoxAlpha = 0.2f
private val CheckColor = QuackColor.White
private val QuackRoundCheckShape = CircleShape
private val QuackRectangleCheckShape = RoundedCornerShape(
size = 4.dp,
)
/**
* 덕키의 원형 CheckBox 입니다.
*
* @param title 체크박스의 타이틀
* @param checked 체크되었는지 여부
* @param onToggle 체크시 호출되는 콜백
*/
@Composable
public fun QuackRoundCheckBox(
title: String? = null,
checked: Boolean,
onToggle: (Boolean) -> Unit,
) {
Row(
horizontalArrangement = Arrangement.spacedBy(ToggleTitleSpace),
verticalAlignment = Alignment.CenterVertically,
) {
QuackSurface(
modifier = Modifier.size(
size = RoundCheckboxSize,
),
shape = QuackRoundCheckShape,
backgroundColor = getCheckBoxBackgroundColor(
isChecked = checked,
uncheckedColor = QuackColor.Black.changeAlpha(
alpha = RoundCheckBoxAlpha,
),
),
border = QuackBorder(
color = getCheckBoxBackgroundColor(
isChecked = checked,
uncheckedColor = QuackColor.White,
),
),
onClick = {
onToggle(!checked)
},
rippleEnabled = false,
) {
Check(
value = ToggleableState(
value = checked,
),
)
}
if (title != null) {
QuackBody2(text = title)
}
}
}
/**
* 덕키의 모서리가 둥근 사각형 CheckBox 입니다.
*
* @param title 체크박스의 타이틀
* @param checked 체크되었는지 여부
* @param onToggle 체크시 호출되는 콜백
*/
@Composable
public fun QuackSquareCheckBox(
title: String? = null,
checked: Boolean,
onToggle: (Boolean) -> Unit,
) {
Row(
horizontalArrangement = Arrangement.spacedBy(ToggleTitleSpace),
verticalAlignment = Alignment.CenterVertically,
) {
QuackSurface(
modifier = Modifier.size(
size = SquareCheckboxSize,
),
shape = QuackRectangleCheckShape,
backgroundColor = getCheckBoxBackgroundColor(
isChecked = checked,
uncheckedColor = QuackColor.Gray3,
),
onClick = {
onToggle(!checked)
},
rippleEnabled = false,
) {
Check(
value = ToggleableState(
value = checked,
),
)
}
if (title != null) {
QuackBody2(text = title)
}
}
}
/**
* 덕키의 IconTextToggle 입니다.
*
* [checked] 에 따라 보여지는 아이콘이 달라집니다.
* [checkedIcon] 이 null 이면 [uncheckedIcon] 으로만 적용됩니다.
*
* @param checkedIcon 체크되었을 때 보여지는 [QuackIcon],
* @param uncheckedIcon 체크가 해제되었을 때 보여지는 [QuackIcon]
* @param checked 체크되었는지 여부
* @param text 아이콘 오른쪽에 표시될 Text
* @param onToggle 체크시 호출되는 콜백
*/
@Composable
public fun QuackIconTextToggle(
checkedIcon: QuackIcon?,
uncheckedIcon: QuackIcon,
checked: Boolean,
text: String,
onToggle: (Boolean) -> Unit,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(
space = QuackIconTextToggleSpacing,
),
) {
QuackBasicIconToggle(
checkedIcon = checkedIcon,
uncheckedIcon = uncheckedIcon,
checked = checked,
onToggle = {
onToggle(!checked)
},
size = SmallIconSize,
)
QuackBody2(
text = text,
singleLine = true,
)
}
}
/**
* 덕키의 ToggleButton 입니다.
*
* [checked] 에 따라 보여지는 아이콘이 달라집니다.
*
* @param checkedIcon 체크되었을 때 보여지는 [QuackIcon], null 일 경우 [uncheckedIcon] 으로만 적용
* @param uncheckedIcon 체크가 해제되었을 때 보여지는 [QuackIcon]
* @param checked 체크되었는지 여부
* @param onToggle 체크시 호출되는 콜백
*/
@Composable
public fun QuackIconToggle(
checkedIcon: QuackIcon?,
uncheckedIcon: QuackIcon,
checked: Boolean,
onToggle: (Boolean) -> Unit,
): Unit = QuackBasicIconToggle(
checkedIcon = checkedIcon,
uncheckedIcon = uncheckedIcon,
checked = checked,
onToggle = onToggle,
)
/**
* 덕키의 Basic ToggleButton 입니다.
*
* [checked] 에 따라 보여지는 아이콘이 달라집니다.
*
* @param checkedIcon 체크되었을 때 보여지는 [QuackIcon] , null 일 경우 [uncheckedIcon] 으로만 적용
* @param uncheckedIcon 체크가 해제되었을 때 보여지는 [QuackIcon]
* @param checked 체크되었는지 여부
* @param onToggle 체크시 호출되는 콜백
*/
@Composable
private fun QuackBasicIconToggle(
checkedIcon: QuackIcon?,
uncheckedIcon: QuackIcon,
checked: Boolean,
onToggle: (Boolean) -> Unit,
size: Dp = IconSize,
) = QuackImage(
overrideSize = DpSize(
width = size,
height = size,
),
tint = when (checkedIcon != null && checked) {
true -> QuackColor.DuckieOrange
false -> QuackColor.Gray1
},
src = when (checkedIcon != null && checked) {
true -> checkedIcon
else -> uncheckedIcon
},
rippleEnabled = false,
onClick = {
onToggle(!checked)
},
)
/**
* 체크 여부에 따라 CheckBox 의 배경색을 지정합니다.
*
* @param isChecked 체크 여부
* @param uncheckedColor 체크되지 않았을 경우 배경색
* @return CheckBox 의 배경색
*/
@Stable
private fun getCheckBoxBackgroundColor(
isChecked: Boolean,
uncheckedColor: QuackColor,
) = when (isChecked) {
true -> QuackColor.DuckieOrange
else -> uncheckedColor
}
/**
* [Canvas] 에 Check 모양을 그립니다.
*
* animationSpec 으로 항상 [QuackAnimationSpec] 을 사용합니다.
*
* @param value 현재 토글 상태를 의미하는 [ToggleableState]
* @param checkColor Check 색상
* @param size Check 의 크기
*/
@Composable
internal fun Check(
value: ToggleableState,
checkColor: QuackColor = CheckColor,
size: Dp = SquareCheckboxSize,
) {
val transition = updateTransition(
targetState = value,
label = TransitionLabel,
)
val checkDrawFraction by transition.animateFloat(
transitionSpec = { QuackAnimationSpec() },
label = TransitionLabel,
) { toggleableState ->
when (toggleableState) {
ToggleableState.On -> 1f
ToggleableState.Off -> 0f
ToggleableState.Indeterminate -> 1f
}
}
val checkCenterGravitationShiftFraction by transition.animateFloat(
transitionSpec = {
when {
initialState == ToggleableState.Off -> snap()
targetState == ToggleableState.Off -> snap(
delayMillis = BoxOutDuration,
)
else -> QuackAnimationSpec()
}
},
label = TransitionLabel,
) { toggleableState ->
when (toggleableState) {
ToggleableState.On -> 0f
ToggleableState.Off -> 0f
ToggleableState.Indeterminate -> 1f
}
}
val checkCache = remember {
CheckDrawingCache()
}
Canvas(
modifier = Modifier
.wrapContentSize(
align = Alignment.Center,
)
.requiredSize(
size = size,
),
) {
val strokeWidthPx = floor(
x = StrokeWidth.toPx(),
)
drawCheck(
checkColor = checkColor.composeColor,
checkFraction = checkDrawFraction,
crossCenterGravitation = checkCenterGravitationShiftFraction,
strokeWidthPx = strokeWidthPx,
drawingCache = checkCache,
)
}
}
@Immutable
private class CheckDrawingCache(
val checkPath: Path = Path(),
val pathMeasure: PathMeasure = PathMeasure(),
val pathToDraw: Path = Path(),
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CheckDrawingCache
if (checkPath != other.checkPath) return false
if (pathMeasure != other.pathMeasure) return false
if (pathToDraw != other.pathToDraw) return false
return true
}
override fun hashCode(): Int {
var result = checkPath.hashCode()
result = 31 * result + pathMeasure.hashCode()
result = 31 * result + pathToDraw.hashCode()
return result
}
}
/**
* [start], [stop] 사이의 임의의 지점 f(p) 를 반환하는 함수이다.
*
* [fraction] 은 임의의 점 p 까지의 거리를 의미한다.
*
* @param start 시작 지점
* @param stop 도착 지점
* @param fraction 임의의 점 p 까지의 거리
*
* @return [start], [stop] 사이의 임의의 지점 f(p)
*/
@Suppress("SameParameterValue")
private fun linearInterpolation(
start: Float,
stop: Float,
fraction: Float,
) = (1 - fraction) * start + fraction * stop
/**
* 체크 표시를 그리기 위한 메서드
* [crossCenterGravitation] 의 값이 0f -> 1f -> 0f 이므로,
* 중심지점일수록 그려지는 속도가 빠르다.
*
* @param checkColor 체크 표시의 색상
* @param checkFraction 체크 표시가 끝나는 지점까지의 거리
* @param crossCenterGravitation 중심지점의 중력
* @param strokeWidthPx 선의 굵기
* @param drawingCache 그려질 선의 경로를 저장하는 캐시
*/
@Stable
private fun DrawScope.drawCheck(
checkColor: Color,
checkFraction: Float,
crossCenterGravitation: Float,
strokeWidthPx: Float,
drawingCache: CheckDrawingCache,
) {
val stroke = Stroke(
width = strokeWidthPx,
cap = StrokeCap.Round,
)
val width = size.width
val gravitatedCrossX = linearInterpolation(
start = CheckCrossX,
stop = StopLocation,
fraction = crossCenterGravitation,
)
val gravitatedCrossY = linearInterpolation(
start = CheckCrossY,
stop = StopLocation,
fraction = crossCenterGravitation,
)
val gravitatedLeftY = linearInterpolation(
start = LeftY,
stop = StopLocation,
fraction = crossCenterGravitation,
)
val gravitatedRightY = linearInterpolation(
start = RightY,
stop = StopLocation,
fraction = crossCenterGravitation,
)
with(drawingCache) {
checkPath.reset()
checkPath.moveTo(
x = width * LeftX,
y = width * gravitatedLeftY,
)
checkPath.lineTo(
x = width * gravitatedCrossX,
y = width * gravitatedCrossY,
)
checkPath.lineTo(
x = width * RightX,
y = width * gravitatedRightY,
)
pathMeasure.setPath(
path = checkPath,
forceClosed = false,
)
pathToDraw.reset()
pathMeasure.getSegment(
startDistance = 0f,
stopDistance = pathMeasure.length * checkFraction,
destination = pathToDraw,
startWithMoveTo = true,
)
}
drawPath(
path = drawingCache.pathToDraw,
color = checkColor,
style = stroke,
)
}