maps-kt/maps-kt-features/src/commonMain/kotlin/center/sciprog/maps/features/DragHandle.kt

52 lines
1.9 KiB
Kotlin
Raw Normal View History

2022-12-17 23:12:00 +03:00
package center.sciprog.maps.features
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.isPrimaryPressed
2022-12-26 11:19:08 +03:00
/**
* @param result - the endpoint of the drag to perform constrained drag
* @param handleNext - if false do not evaluate subsequent drag handles
*/
public data class DragResult<T : Any>(val result: ViewPoint<T>, val handleNext: Boolean = true)
public fun interface DragHandle<T : Any> {
2022-12-17 23:12:00 +03:00
/**
* @param event - qualifiers of the event used for drag
* @param start - is a point where drag begins, end is a point where drag ends
* @param end - end point of the drag
*
* @return true if default event processors should be used after this one
*/
2022-12-26 11:19:08 +03:00
public fun handle(event: PointerEvent, start: ViewPoint<T>, end: ViewPoint<T>): DragResult<T>
2022-12-17 23:12:00 +03:00
public companion object {
2022-12-26 11:19:08 +03:00
public fun <T : Any> bypass(): DragHandle<T> = DragHandle<T> { _, _, end -> DragResult(end) }
2022-12-17 23:12:00 +03:00
/**
* Process only events with primary button pressed
*/
2022-12-26 11:19:08 +03:00
public fun <T : Any> withPrimaryButton(
block: (event: PointerEvent, start: ViewPoint<T>, end: ViewPoint<T>) -> DragResult<T>,
2022-12-23 22:16:16 +03:00
): DragHandle<T> = DragHandle { event, start, end ->
2022-12-17 23:12:00 +03:00
if (event.buttons.isPrimaryPressed) {
block(event, start, end)
} else {
2022-12-26 11:19:08 +03:00
DragResult(end)
2022-12-17 23:12:00 +03:00
}
}
/**
* Combine several handles into one
*/
2022-12-26 11:19:08 +03:00
public fun <T : Any> combine(vararg handles: DragHandle<T>): DragHandle<T> = DragHandle { event, start, end ->
var current: ViewPoint<T> = end
2022-12-17 23:12:00 +03:00
handles.forEach {
2022-12-26 11:19:08 +03:00
val result = it.handle(event, start, current)
if (!result.handleNext) return@DragHandle result else {
current = result.result
}
2022-12-17 23:12:00 +03:00
}
2022-12-26 11:19:08 +03:00
return@DragHandle DragResult(current)
2022-12-17 23:12:00 +03:00
}
}
}