scoop:scoop.ui:0.1.0
src/interaction/hover.scoop
Selected production source · src/interaction/hover.scoop
1
package scoop.ui3
import scoop.platform.time.MonotonicInstant4
import scoop.graphics.*5
import scoop.platform.time.MonotonicTimeSource6
import scoop.surface.*7
import scoop.time.*8
import scoop.window.*10
public class HoverOptions public constructor(11
public val openDelay: Duration = Duration.milliseconds(300L),12
public val closeDelay: Duration = Duration.milliseconds(150L),13
public val transitDelay: Duration = Duration.milliseconds(350L),14
public val corridorPadding: Double = 6.0,15
public val focus: Boolean = true,16
public val enabled: Boolean = true,17
public val longPress: LongPressOptions = LongPressOptions(enabled = false)18
) {19
init {20
requireUi(21
openDelay >=22
Duration.ZERO &&23
closeDelay >=24
Duration.ZERO &&25
transitDelay >=26
Duration.ZERO,27
"negative hover delay"28
)29
requireUi(30
corridorPadding.isFinite() && corridorPadding >= 0.0,31
"invalid hover corridor padding"32
)33
}34
}36
private enum HoverWait {37
Open, Close, Transit38
}40
/** Trigger and portal input areas share one bounded hover session and one owner deadline. */41
public class Hover internal constructor(42
private val scope: ComponentScope,43
private val trigger: InputArea,44
private var open: Binding<Boolean>,45
private var options: HoverOptions46
): Closeable {47
private val input = scope.input48
private val window = scope.nativeWindow49
private var closed = false50
private var dismissed = false51
private var contactPinned = false52
private var content: Array<InputArea> = []53
private var registrations: Array<Closeable> = []54
private var observation: Closeable? = None55
private var pending: HoverWait? = None56
private var departure: Point? = None57
private var previous: Point? = None58
private var transitEnd: MonotonicInstant? = None59
private val timer = scope.createDeadline { expired() }60
private val triggerEvents = trigger.scope.addEventHandler { _, event -> areaEvent(event) }61
private val triggerFocus = trigger.scope.observeActivity { refresh() }62
private val hold = LongPress(scope, trigger, holdOptions()) { showFromContact() }63
private val windowEvents =64
scope.observeWindow(window) {65
event -> when (event) {66
case Contact(ContactEvent.Began(val contact)) -> {67
val point = contact.pointer.logicalPosition68
if (contactPinned && !contains(Point(point.x, point.y)))69
dismiss()70
}71
else -> {}72
}73
}74
private var previousActivity = window.activity75
private val windowActivity =76
scope.observeWindowActivity {77
value ->78
val previous = previousActivity79
previousActivity = value80
if (81
(previous.focused && !value.focused) ||82
(previous.visible && !value.visible) ||83
(!previous.occluded && value.occluded)84
)85
dismiss()86
else87
if ((!previous.visible && value.visible) || (previous.occluded && !value.occluded))88
refresh()89
}91
init {92
try {93
refresh()94
}95
catch (error: Throwable) {96
throwUi(cleanupUi(Some(error)) { close() });97
throw error98
}99
}101
public val isClosed: Boolean get() {102
val mounted = scope.isMounted;103
return closed || !mounted || trigger.isClosed104
}105
public val isPending: Boolean get() = timer.isScheduled106
public val isOpen: Boolean get() {107
scope.isMounted108
return open.value109
}111
public fun update(open: Binding<Boolean>, options: HoverOptions? = None) {112
checkOpen()113
this.open = open114
this.options = options ?: this.options115
hold.update(holdOptions()) { showFromContact() }116
if (!this.options.enabled || (contactPinned && !this.options.longPress.enabled))117
dismiss()118
else119
refresh()120
}121
public fun setContent(areas: Array<InputArea>) {122
checkOpen()123
for (area in areas) {124
requireUi(!area.isClosed, "hover content area is closed")125
var cursor: InputScope? = Some(area.scope)126
var belongs = false127
while (true) {128
val current = cursor ?: break129
if (current === input) {130
belongs = true;131
break132
}133
cursor = current.parent134
}135
requireUi(belongs, "hover content must be a logical descendant of its owner")136
}137
for (registration in registrations)138
registration.close()139
val next = ArrayList<Closeable>()140
content = areas141
for (area in areas) {142
next.add(area.scope.addEventHandler { _, event -> areaEvent(event) })143
next.add(area.scope.observeActivity { refresh() })144
}145
registrations = next.toArray()146
refresh()147
}148
private fun holdOptions(): LongPressOptions =149
LongPressOptions(150
options.enabled && options.longPress.enabled,151
options.longPress.delay,152
options.longPress.threshold153
)154
private fun contains(point: Point): Boolean {155
if (trigger.hitTest(point))156
return true157
for (area in content)158
if (!area.isClosed && area.hitTest(point))159
return true160
return false161
}162
private fun showFromContact() {163
if (isClosed || !options.enabled || !options.longPress.enabled)164
return165
dismissed = false166
contactPinned = true167
cancelWait()168
open.value = true169
if (isClosed)170
return171
contactPinned = open.value172
if (contactPinned)173
observe()174
}175
private fun areaEvent(event: InputEvent) {176
when (event) {177
case Pointer(InputPointerEvent.Entered(val pointer)) -> {178
val point = Some(pointerPoint(pointer.state))179
previous = point180
refresh(point)181
}182
case Pointer(InputPointerEvent.Left(_)) -> refresh()183
case Pointer(InputPointerEvent.Cancelled(_, _)) -> refresh()184
case FocusChanged(_) -> refresh()185
else -> {}186
}187
}188
private fun within(): Boolean {189
if (trigger.scope.isHovered)190
return true191
for (area in content)192
if (!area.isClosed && area.scope.isHovered)193
return true194
return false195
}196
private fun focused(): Boolean {197
if (!options.focus || !window.isFocused)198
return false199
if (trigger.scope.activity.hasFocus && trigger.scope.isInputAllowed)200
return true201
for (area in content)202
if (!area.isClosed && area.scope.activity.hasFocus && area.scope.isInputAllowed)203
return true204
return false205
}206
private fun refresh(point: Point? = None) {207
if (isClosed || window.state != WindowState.Open)208
return209
if (!window.isVisible || window.isOccluded) {210
cancelWait()211
stopObserving()212
return213
}214
if (!options.enabled || !trigger.scope.isInputAllowed) {215
dismiss();216
return217
}218
if (contactPinned && open.value) {219
cancelWait()220
observe()221
return222
}223
contactPinned = false224
val focus = focused()225
val inside = within()226
if (dismissed) {227
if (inside || focus) {228
cancelWait()229
stopObserving()230
return231
}232
dismissed = false233
}234
if (inside || focus) {235
departure =236
if (inside)237
when (point) {238
case Some(_) -> point;239
case None -> previous240
}241
else242
None243
transitEnd = None244
if (open.value)245
cancelWait()246
else247
schedule(248
HoverWait.Open,249
if (focus)250
Duration.ZERO251
else252
options.openDelay253
)254
observe()255
return256
}257
if (!open.value) {258
cancelWait();259
stopObserving();260
return261
}262
observe()263
val position =264
when (point) {265
case Some(_) -> point;266
case None -> previous267
}268
val start = departure269
val prior = previous270
if (position != None && start != None && prior != None) {271
for (area in content) {272
val bounds = area.visibleBounds ?: continue273
if (hoverTransit(start!!, prior!!, position!!, bounds, options.corridorPadding)) {274
val end = transitEnd ?: (MonotonicTimeSource.now() + options.transitDelay)275
transitEnd = Some(end)276
if (pending != Some(HoverWait.Transit)) {277
pending = Some(HoverWait.Transit)278
timer.schedule(end)279
}280
return281
}282
}283
}284
schedule(HoverWait.Close, options.closeDelay)285
}286
private fun observe() {287
if (isClosed)288
return289
when (observation) {290
case Some(_) -> return;291
case None -> {}292
}293
observation = Some(input.observePointer { event -> observed(event) })294
}295
private fun observed(event: PointerObservation) {296
if (closed)297
return298
when (event) {299
case Pointer(PointerEvent.Left(_)) -> dismiss()300
case Pointer(PointerEvent.Cancelled(_, _)) -> dismiss()301
case FocusLost -> dismiss()302
case Closed -> dismiss()303
case Pointer(val value) -> {304
when (value) {305
case Moved(_) -> contactPinned = false306
case Button(val state, _, ElementState.Pressed, _) -> {307
if (contactPinned && !contains(pointerPoint(state))) {308
dismiss()309
return310
}311
}312
else -> {}313
}314
val point =315
when (value) {316
case Entered(val state) -> pointerPoint(state)317
case Moved(val state) -> pointerPoint(state)318
case Button(val state, _, _, _) -> pointerPoint(state)319
case Wheel(val state, _, _, _) -> pointerPoint(state)320
else -> return321
}322
refresh(Some(point))323
previous = Some(point)324
}325
}326
}327
private fun schedule(kind: HoverWait, delay: Duration) {328
if (pending == Some(kind))329
return330
pending = Some(kind)331
if (delay == Duration.ZERO)332
expired()333
else {334
val requested = MonotonicTimeSource.now() + delay335
val limit = transitEnd336
timer.schedule(337
if (kind == HoverWait.Close && limit != None && limit!! < requested)338
limit!!339
else340
requested341
)342
}343
}344
private fun expired() {345
val next = pending ?: return346
pending = None347
if (isClosed || window.state != WindowState.Open || !window.isVisible || window.isOccluded)348
return349
val opening = next == HoverWait.Open350
if (opening && (!options.enabled || (!within() && !focused()))) {351
stopObserving();352
return353
}354
open.value = opening355
if (isClosed)356
return357
if (open.value)358
observe()359
else360
stopObserving()361
}362
private fun cancelWait() {363
timer.cancel();364
pending = None365
}366
private fun stopObserving() {367
observation?.close();368
observation = None369
}370
public fun dismiss() {371
checkOverlayMutation()372
contactPinned = false373
hold.cancel()374
dismissed = !isClosed && window.state == WindowState.Open && (within() || focused())375
cancelWait()376
stopObserving()377
departure = None378
previous = None379
transitEnd = None380
if (!closed && open.value)381
open.value = false382
}383
private fun checkOpen() {384
checkOverlayMutation()385
if (isClosed)386
throw IllegalStateException(Some("hover behavior is no longer mounted"))387
}388
public override fun close() {389
scope.isMounted390
checkOverlayMutation()391
if (closed)392
return393
closed = true394
contactPinned = false395
var failure = cleanupUi(None) { hold.close() }396
failure = cleanupUi(failure) { windowEvents.close() }397
failure = cleanupUi(failure) { windowActivity.close() }398
failure = cleanupUi(failure) { timer.close() }399
failure = cleanupUi(failure) { stopObserving() }400
failure = cleanupUi(failure) { triggerEvents.close() }401
failure = cleanupUi(failure) { triggerFocus.close() }402
for (registration in registrations)403
failure = cleanupUi(failure) { registration.close() }404
registrations = []405
content = []406
pending = None407
throwUi(failure)408
}409
}411
private fun pointerPoint(value: PointerState): Point =412
Point(value.logicalPosition.x, value.logicalPosition.y)414
public fun ComponentScope.hover(415
trigger: InputArea,416
open: Binding<Boolean>,417
options: HoverOptions = HoverOptions()418
): Hover {419
requireBehaviorArea(trigger)420
return resource { Hover(this, trigger, open, options) }421
}