Scoop API

scoop:scoop.ui:0.1.0

src/interaction/hover.scoop

Selected production source · src/interaction/hover.scoop

1package scoop.ui
3import scoop.platform.time.MonotonicInstant
4import scoop.graphics.*
5import scoop.platform.time.MonotonicTimeSource
6import scoop.surface.*
7import scoop.time.*
8import scoop.window.*
10public 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 }
36private enum HoverWait {
37 Open, Close, Transit
40/** Trigger and portal input areas share one bounded hover session and one owner deadline. */
41public class Hover internal constructor(
42 private val scope: ComponentScope,
43 private val trigger: InputArea,
44 private var open: Binding<Boolean>,
45 private var options: HoverOptions
46): Closeable {
47 private val input = scope.input
48 private val window = scope.nativeWindow
49 private var closed = false
50 private var dismissed = false
51 private var contactPinned = false
52 private var content: Array<InputArea> = []
53 private var registrations: Array<Closeable> = []
54 private var observation: Closeable? = None
55 private var pending: HoverWait? = None
56 private var departure: Point? = None
57 private var previous: Point? = None
58 private var transitEnd: MonotonicInstant? = None
59 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.logicalPosition
68 if (contactPinned && !contains(Point(point.x, point.y)))
69 dismiss()
70 }
71 else -> {}
72 }
73 }
74 private var previousActivity = window.activity
75 private val windowActivity =
76 scope.observeWindowActivity {
77 value ->
78 val previous = previousActivity
79 previousActivity = value
80 if (
81 (previous.focused && !value.focused) ||
82 (previous.visible && !value.visible) ||
83 (!previous.occluded && value.occluded)
84 )
85 dismiss()
86 else
87 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 error
98 }
99 }
101 public val isClosed: Boolean get() {
102 val mounted = scope.isMounted;
103 return closed || !mounted || trigger.isClosed
104 }
105 public val isPending: Boolean get() = timer.isScheduled
106 public val isOpen: Boolean get() {
107 scope.isMounted
108 return open.value
109 }
111 public fun update(open: Binding<Boolean>, options: HoverOptions? = None) {
112 checkOpen()
113 this.open = open
114 this.options = options ?: this.options
115 hold.update(holdOptions()) { showFromContact() }
116 if (!this.options.enabled || (contactPinned && !this.options.longPress.enabled))
117 dismiss()
118 else
119 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 = false
127 while (true) {
128 val current = cursor ?: break
129 if (current === input) {
130 belongs = true;
131 break
132 }
133 cursor = current.parent
134 }
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 = areas
141 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.threshold
153 )
154 private fun contains(point: Point): Boolean {
155 if (trigger.hitTest(point))
156 return true
157 for (area in content)
158 if (!area.isClosed && area.hitTest(point))
159 return true
160 return false
161 }
162 private fun showFromContact() {
163 if (isClosed || !options.enabled || !options.longPress.enabled)
164 return
165 dismissed = false
166 contactPinned = true
167 cancelWait()
168 open.value = true
169 if (isClosed)
170 return
171 contactPinned = open.value
172 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 = point
180 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 true
191 for (area in content)
192 if (!area.isClosed && area.scope.isHovered)
193 return true
194 return false
195 }
196 private fun focused(): Boolean {
197 if (!options.focus || !window.isFocused)
198 return false
199 if (trigger.scope.activity.hasFocus && trigger.scope.isInputAllowed)
200 return true
201 for (area in content)
202 if (!area.isClosed && area.scope.activity.hasFocus && area.scope.isInputAllowed)
203 return true
204 return false
205 }
206 private fun refresh(point: Point? = None) {
207 if (isClosed || window.state != WindowState.Open)
208 return
209 if (!window.isVisible || window.isOccluded) {
210 cancelWait()
211 stopObserving()
212 return
213 }
214 if (!options.enabled || !trigger.scope.isInputAllowed) {
215 dismiss();
216 return
217 }
218 if (contactPinned && open.value) {
219 cancelWait()
220 observe()
221 return
222 }
223 contactPinned = false
224 val focus = focused()
225 val inside = within()
226 if (dismissed) {
227 if (inside || focus) {
228 cancelWait()
229 stopObserving()
230 return
231 }
232 dismissed = false
233 }
234 if (inside || focus) {
235 departure =
236 if (inside)
237 when (point) {
238 case Some(_) -> point;
239 case None -> previous
240 }
241 else
242 None
243 transitEnd = None
244 if (open.value)
245 cancelWait()
246 else
247 schedule(
248 HoverWait.Open,
249 if (focus)
250 Duration.ZERO
251 else
252 options.openDelay
253 )
254 observe()
255 return
256 }
257 if (!open.value) {
258 cancelWait();
259 stopObserving();
260 return
261 }
262 observe()
263 val position =
264 when (point) {
265 case Some(_) -> point;
266 case None -> previous
267 }
268 val start = departure
269 val prior = previous
270 if (position != None && start != None && prior != None) {
271 for (area in content) {
272 val bounds = area.visibleBounds ?: continue
273 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 return
281 }
282 }
283 }
284 schedule(HoverWait.Close, options.closeDelay)
285 }
286 private fun observe() {
287 if (isClosed)
288 return
289 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 return
298 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 = false
306 case Button(val state, _, ElementState.Pressed, _) -> {
307 if (contactPinned && !contains(pointerPoint(state))) {
308 dismiss()
309 return
310 }
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 -> return
321 }
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 return
330 pending = Some(kind)
331 if (delay == Duration.ZERO)
332 expired()
333 else {
334 val requested = MonotonicTimeSource.now() + delay
335 val limit = transitEnd
336 timer.schedule(
337 if (kind == HoverWait.Close && limit != None && limit!! < requested)
338 limit!!
339 else
340 requested
341 )
342 }
343 }
344 private fun expired() {
345 val next = pending ?: return
346 pending = None
347 if (isClosed || window.state != WindowState.Open || !window.isVisible || window.isOccluded)
348 return
349 val opening = next == HoverWait.Open
350 if (opening && (!options.enabled || (!within() && !focused()))) {
351 stopObserving();
352 return
353 }
354 open.value = opening
355 if (isClosed)
356 return
357 if (open.value)
358 observe()
359 else
360 stopObserving()
361 }
362 private fun cancelWait() {
363 timer.cancel();
364 pending = None
365 }
366 private fun stopObserving() {
367 observation?.close();
368 observation = None
369 }
370 public fun dismiss() {
371 checkOverlayMutation()
372 contactPinned = false
373 hold.cancel()
374 dismissed = !isClosed && window.state == WindowState.Open && (within() || focused())
375 cancelWait()
376 stopObserving()
377 departure = None
378 previous = None
379 transitEnd = None
380 if (!closed && open.value)
381 open.value = false
382 }
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.isMounted
390 checkOverlayMutation()
391 if (closed)
392 return
393 closed = true
394 contactPinned = false
395 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 = None
407 throwUi(failure)
408 }
411private fun pointerPoint(value: PointerState): Point =
412 Point(value.logicalPosition.x, value.logicalPosition.y)
414public 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) }