Scoop API

scoop:scoop.ui.component:0.1.0

src/menus/popup.scoop

Selected production source · src/menus/popup.scoop

1package scoop.ui.component
3import scoop.graphics.*
4import scoop.surface.*
5import scoop.time.Duration
6import scoop.ui.*
7import scoop.ui.style.*
8import scoop.ui.style.Theme
9import scoop.window.*
10import scoop.window.accessibility.*
11import scoop.ui.component.column as menuColumn
13/** Handles are presentation references, never a second selection or focus model. */
14internal class MenuFocus: NavigationSource {
15 private val storage = ChoiceHandles()
16 private var items: Array<MenuItemSpec> = []
17 var handles: Array<FocusHandle> = []
18 fun resolve(content: MenuContent) {
19 val next = ArrayList<MenuItemSpec>()
20 for (entry in content.entries)
21 when (menuItem(entry)) {
22 case Some(val item) -> next.add(item)
23 case None -> {}
24 }
25 items = next.toArray()
26 handles =
27 storage.resolve(
28 Array<ViewKey>(items.size) { index -> items[index].key },
29 Array<FocusOptions>(items.size) { index -> items[index].focus }
30 )
31 }
32 public override val count: Long get() = items.size
33 public override fun keyAt(index: Long): ViewKey = items[index].key
34 public override fun indexOfKey(key: ViewKey): Long? {
35 for (index in 0L ..< items.size)
36 if (items[index].key == key)
37 return Some(index)
38 return None
39 }
40 public override fun enabledAt(index: Long): Boolean = items[index].enabled
41 public override fun searchTextAt(index: Long): String = items[index].label
42 fun handle(key: ViewKey): FocusHandle = handles[indexOfKey(key)!!]
43 fun current(): ViewKey? {
44 for (index in 0L ..< handles.size)
45 if (handles[index].hasFocus)
46 return Some(items[index].key)
47 return None
48 }
49 fun edge(last: Boolean): FocusHandle? {
50 var index =
51 if (last)
52 items.size - 1L
53 else
54 0L
55 while (index >= 0L && index < items.size) {
56 if (items[index].enabled)
57 return Some(handles[index])
58 index += if (last)
59 -1L
60 else
61 1L
62 }
63 return None
64 }
67/** One root close request is shared by every submenu. */
68internal class MenuChain(
69 val close: () -> Unit,
70 val tab: (Boolean) -> Unit,
71 val horizontal: ((Boolean) -> Unit)? = None
74internal class MenuPopupProps(
75 val open: Binding<Boolean>,
76 val content: MenuContent,
77 val options: MenuOptions,
78 val placement: OverlayPlacement,
79 val handle: OverlayHandle,
80 val focus: MenuFocus,
81 val chain: MenuChain,
82 val root: Boolean = false,
83 val takeFocus: Boolean = true,
84 val last: Boolean = false,
85 val initial: OverlayFocusOptions = OverlayFocusOptions(),
86 val dismiss: OverlayDismiss = OverlayDismiss(true, OutsidePress.CloseAndContinue, true),
87 val anchorVisibility: AnchorVisibility = AnchorVisibility.Close,
88 val link: HoverPopupLink? = None,
89 val onCloseRequest: (OverlayCloseReason) -> Boolean = { _ -> true },
90 val onClosed: (OverlayCloseReason) -> Unit = {},
91 val semantics: ComponentSemantics? = None
94internal class MenuPopup(
95 private val props: Props<MenuPopupProps>,
96 scope: ComponentScope
97): Component(scope) {
98 private val themes = ThemeAccess(scope)
99 public override fun onMount() {
100 themes.mount(props.value.options.theme)
101 }
102 private fun dismissSemantically(): SemanticActionResult {
103 val input = props.value
104 if (!input.open.value)
105 return SemanticActionResult.Unavailable
106 input.handle.requestClose()
107 return if (!props.value.open.value)
108 SemanticActionResult.Completed
109 else
110 SemanticActionResult.Rejected
111 }
112 public override fun render(): View {
113 val input = props.value
114 val options = input.options
115 val theme = themes.read(options.theme)
116 val density = theme.tokens.typography.body.fontSize / 14.0
117 input.focus.resolve(input.content)
118 val panel =
119 panelFrame(
120 element(
121 MenuViewportProps(options, theme),
122 { current, mount -> MenuViewport(current, scope = mount) },
123 [
124 component(
125 MenuLevelProps(input, theme),
126 { current, mount -> MenuLevel(current, scope = mount) }
127 )
128 ]
129 ),
130 Insets.all(4.0 * density),
131 styleOverride {
132 background(Some(Paint(theme.tokens.palette.popover.background)))
133 border(
134 Some(
135 Border.all(
136 1.0,
137 componentPanelBorder(theme, theme.tokens.palette.popover)
138 )
139 )
140 )
141 corners(Corners.all(8.0 * density))
142 boxShadows(theme.tokens.effects.floating)
143 }.then(options.style),
144 Some(options.width * density)
145 )
146 val motion =
147 theme.tokens.motion.resolve(
148 options.transition.resolve(Some(AnimationSpec.Tween(Duration.milliseconds(100L))))
149 )
150 val content =
151 when (input.link) {
152 case Some(val link) -> element(
153 HoverPopupContentProps(link, false, None),
154 { current, mount -> HoverPopupContent(current, scope = mount) },
155 [panel]
156 )
157 case None -> panel
158 }
159 val inputs = props
160 val semantics =
161 input.semantics ?:
162 if (input.root)
163 options.semantics
164 else
165 ComponentSemantics()
166 return portal(
167 input.open,
168 element(
169 PopupMotionProps(options.enabled, 8.0 * density),
170 { current, mount -> PopupMotion(current, scope = mount) },
171 [
172 semanticContent(
173 content,
174 SemanticRole.Menu,
175 semantics.properties(
176 enabled = options.enabled,
177 modal = input.root && options.mode == OverlayMode.Modal
178 ),
179 actions = SemanticActions(dismiss = Some { dismissSemantically() }),
180 relations = semantics.relations,
181 mergeLabels = false,
182 reference = semantics.reference
183 )
184 ]
185 )
186 ) {
187 placement = input.placement
188 handle = Some(input.handle)
189 mode =
190 if (input.root)
191 options.mode
192 else
193 OverlayMode.NonModal
194 focus =
195 Some(
196 OverlayFocusOptions(
197 when (input.initial.initialFocus) {
198 case Some(_) -> input.initial.initialFocus;
199 case None -> input.focus.edge(input.last)
200 },
201 input.initial.restoreFocus,
202 input.takeFocus && input.initial.autoFocus,
203 input.initial.restoreTarget
204 )
205 )
206 dismiss = input.dismiss
207 anchorVisibility = input.anchorVisibility
208 transition = PresenceOptions(motion, motion)
209 onCloseRequest = { reason -> inputs.value.onCloseRequest(reason) }
210 onClosed = { reason -> inputs.value.onClosed(reason) }
211 }
212 }
215internal class MenuLevelProps(val popup: MenuPopupProps, val theme: Theme)
217/** The same keyed row sequence is used at every depth and by all three entry points. */
218internal class MenuLevel(
219 private val props: Props<MenuLevelProps>,
220 scope: ComponentScope
221): Component(scope) {
222 private val expanded = state<ViewKey?>(None)
223 public override fun render(): View {
224 val input = props.value
225 val popup = input.popup
226 val expanded = this.expanded
227 val rows =
228 Array<View>(popup.content.entries.size) {
229 index ->
230 val entry = popup.content.entries[index]
231 val key = menuKey(entry)
232 component(
233 MenuRowProps(
234 entry,
235 popup.options,
236 input.theme,
237 when (menuItem(entry)) {
238 case Some(_) -> Some(popup.focus.handle(key))
239 case None -> None
240 },
241 binding(
242 { expanded.value == Some(key) },
243 {
244 open -> if (open)
245 expanded.value = Some(key)
246 else
247 if (expanded.value == Some(key))
248 expanded.value = None
249 }
250 ),
251 popup.chain
252 ),
253 { current, mount -> MenuRow(current, scope = mount) },
254 key
255 )
256 }
257 return element(
258 MenuNavigationProps(
259 popup.focus,
260 popup.options,
261 popup.chain,
262 popup.root,
263 Some(popup.handle),
264 { expanded.value = None }
265 ),
266 { current, mount -> MenuNavigation(current, scope = mount) },
267 [
268 menuColumn {
269 addAll(rows)
270 alignment = CrossAlignment.Stretch
271 }
272 ]
273 )
274 }
277internal class MenuNavigationProps(
278 val focus: MenuFocus,
279 val options: MenuOptions,
280 val chain: MenuChain,
281 val root: Boolean = true,
282 val handle: OverlayHandle? = None,
283 val navigated: () -> Unit = {}
286internal class MenuNavigation(
287 private val props: Props<MenuNavigationProps>,
288 scope: ComponentScope
289): Element<Unit>(scope) {
290 private var navigation: KeyNavigation? = None
291 private var search: Typeahead? = None
292 private fun options(): NavigationOptions {
293 val input = props.value
294 return NavigationOptions(
295 Array<NavigationItem>(input.focus.handles.size) {
296 index -> NavigationItem(input.focus.handles[index])
297 },
298 loop = input.options.loop,
299 onNavigate = { _ -> props.value.navigated() }
300 )
301 }
302 public override fun onMount() {
303 navigation = Some(scope.keyNavigation(options()))
304 val input = props.value
305 search =
306 Some(
307 scope.typeahead(
308 input.focus,
309 { props.value.focus.current() },
310 { key -> focusMatch(key) },
311 input.options.typeahead
312 )
313 )
314 scope.input.addDefaultAction {
315 context, event ->
316 val key =
317 when (event) {
318 case Keyboard(val value) -> value;
319 else -> return@addDefaultAction
320 }
321 if (!menuKeyAllowed(key, true))
322 return@addDefaultAction
323 val input = props.value
324 if (key.logicalKey == LogicalKey.Named(NamedKey.Tab)) {
325 context.consume()
326 input.chain.tab(key.modifiers.shift)
327 } else
328 if (!key.modifiers.shift) {
329 val backwards = menuBackward(key, scope.layoutDirection)
330 when (backwards) {
331 case Some(val reverse) -> if (!input.root && reverse) {
332 context.consume();
333 input.handle!!.requestClose()
334 } else
335 if (input.root)
336 when (input.chain.horizontal) {
337 case Some(val move) -> {
338 context.consume();
339 move(reverse)
340 }
341 case None -> {}
342 }
343 case None -> {}
344 }
345 }
346 }
347 }
348 private fun focusMatch(key: ViewKey) {
349 props.value.navigated()
350 props.value.focus.handle(key).requestFocus(FocusOrigin.Keyboard)
351 }
352 public override fun update(): UiInvalidation {
353 navigation!!.options = options()
354 val input = props.value
355 search!!.update(
356 input.focus,
357 { props.value.focus.current() },
358 { key -> focusMatch(key) },
359 Some(input.options.typeahead)
360 )
361 return UiInvalidation.Layout
362 }
363 public override fun measure(context: MeasureContext, constraints: Constraints): LayoutResult<
364 Unit
365 > {
366 val result = context.measureChild(0L, constraints)
367 context.placeChild(0L, Point(0.0, 0.0))
368 return LayoutResult(result, Unit)
369 }
370 public override fun scene(context: SceneContext, measured: Unit) {
371 context.children()
372 }
375internal fun menuKeyAllowed(key: KeyEvent, shift: Boolean = false): Boolean =
376 key.state ==
377 ElementState.Pressed &&
378 !key.synthetic &&
379 !key.modifiers.control &&
380 !key.modifiers.alt &&
381 !key.modifiers.superKey &&
382 !key.modifiers.function &&
383 (shift || !key.modifiers.shift)
385internal fun menuBackward(key: KeyEvent, direction: LayoutDirection): Boolean? =
386 when (key.logicalKey) {
387 case Named(NamedKey.ArrowLeft) -> Some(direction != LayoutDirection.Rtl)
388 case Named(NamedKey.ArrowRight) -> Some(direction == LayoutDirection.Rtl)
389 else -> None
390 }
392private class MenuViewportProps(val options: MenuOptions, val theme: Theme)
394/** Natural-height eager menu scrolling; focus reveal uses the existing ScrollViewport. */
395private class MenuViewport(
396 private val props: Props<MenuViewportProps>,
397 scope: ComponentScope
398): Element<ScrollLayout>(scope) {
399 private val scroll = ScrollState()
400 private var control: ScrollControl? = None
401 public override fun onMount() {
402 control =
403 Some(
404 ScrollControl(scope) {
405 ScrollControlProps(
406 scroll,
407 ScrollAxes.Vertical,
408 28.0,
409 ScrollChain.Contain,
410 ScrollbarVisibility.Auto,
411 scrollbarOptions(),
412 props.value.options.enabled,
413 FocusOptions(tabStop = false),
414 PaintCachePolicy.None,
415 props.value.theme
416 )
417 }
418 )
419 }
420 public override fun update(): UiInvalidation {
421 control!!.update()
422 return UiInvalidation.Layout
423 }
424 public override fun measure(context: MeasureContext, constraints: Constraints): LayoutResult<
425 ScrollLayout
426 > {
427 val child =
428 context.measureChild(0L, Constraints(constraints.minWidth, constraints.maxWidth))
429 val size = constraints.constrain(child.size)
430 val layout = control!!.layout(size, child.size)
431 context.placeChild(0L, Point(0.0, 0.0))
432 return LayoutResult(LayoutMetrics(size), layout)
433 }
434 public override fun scene(context: SceneContext, layout: ScrollLayout) {
435 control!!.scene(context, layout)
436 }