Line data Source code
1 : part of 'foss_menu.dart';
2 :
3 : /// The floating panel of menu rows: the chrome, the rows, the roving highlight,
4 : /// the keyboard model, and the menu semantics container.
5 : ///
6 : /// It positions itself against [anchor] with [AnchoredLayout], so an opener
7 : /// hands it a rectangle and nothing more: a trigger's bounds, or a zero-size
8 : /// rectangle at a pointer. Values are physical, so the opener resolves the
9 : /// reading direction before building it.
10 : ///
11 : /// It owns row behavior and reports a selection outward through [onSelected],
12 : /// which the opener turns into an action and a dismissal, because the dismissal
13 : /// policy differs per opener. It owns no overlay: the opener supplies the
14 : /// portal, the barrier, and the tap region.
15 : class _FossMenuPanel extends StatefulWidget {
16 4 : const _FossMenuPanel({
17 : required this.items,
18 : required this.anchor,
19 : required this.side,
20 : required this.align,
21 : required this.animation,
22 : required this.onSelected,
23 : required this.onDismiss,
24 : required this.sideOffset,
25 : this.style,
26 : });
27 :
28 : /// The rows, in order.
29 : final List<FossMenuItem> items;
30 :
31 : /// The rectangle to open against, in the overlay's coordinate space.
32 : final Rect anchor;
33 :
34 : /// The physical side of [anchor] to open on. Flips on overflow.
35 : final AnchorSide side;
36 :
37 : /// The physical cross-axis alignment against [anchor].
38 : final AnchorAlign align;
39 :
40 : /// Drives the open and close transition. The panel fades and scales with it.
41 : final Animation<double> animation;
42 :
43 : /// Called with the index of a selectable row the user picked.
44 : final ValueChanged<int> onSelected;
45 :
46 : /// Called when `Escape` closes the panel.
47 : final VoidCallback onDismiss;
48 :
49 : /// The gap from [anchor] along the main axis, in logical pixels.
50 : final double sideOffset;
51 :
52 : /// Per-instance overrides layered on the theme-resolved style.
53 : final FossMenuStyle? style;
54 :
55 4 : @override
56 4 : State<_FossMenuPanel> createState() => _FossMenuPanelState();
57 : }
58 :
59 : class _FossMenuPanelState extends State<_FossMenuPanel> {
60 : final FocusNode _focus = FocusNode(debugLabel: 'FossMenu panel');
61 :
62 : /// The highlighted row, or -1 for none. The panel opens with none, so the
63 : /// first `ArrowDown` lands on the first row.
64 : int _highlight = -1;
65 :
66 : /// One key per item, so the keyboard walk can scroll its row into view.
67 16 : late List<GlobalKey> _rowKeys = _keysFor(widget.items);
68 :
69 4 : static List<GlobalKey> _keysFor(List<FossMenuItem> items) =>
70 16 : List.generate(items.length, (_) => GlobalKey());
71 :
72 4 : @override
73 : void didUpdateWidget(_FossMenuPanel oldWidget) {
74 4 : super.didUpdateWidget(oldWidget);
75 24 : if (widget.items.length != _rowKeys.length) {
76 4 : _rowKeys = _keysFor(widget.items);
77 : }
78 : // A shorter list can leave the highlight past the end.
79 22 : if (_highlight >= widget.items.length) _highlight = -1;
80 : }
81 :
82 4 : @override
83 : void dispose() {
84 8 : _focus.dispose();
85 4 : super.dispose();
86 : }
87 :
88 : /// Whether any row reports the menu-item role, which is what makes the
89 : /// container role necessary. A disabled row still reports it.
90 24 : bool get _hasRows => widget.items.any((item) => item._isRow);
91 :
92 2 : void _highlightRow(int index) {
93 4 : if (_highlight == index) return;
94 6 : setState(() => _highlight = index);
95 : }
96 :
97 : /// Walks the highlight by [delta], skipping rows that cannot take a
98 : /// selection and wrapping at both ends. Does nothing when no row can.
99 2 : void _move(int delta) {
100 6 : final count = widget.items.length;
101 2 : if (count == 0) return;
102 : // From nothing highlighted, a step back has to land on the last row, so
103 : // the walk starts one past the matching end rather than at -1.
104 8 : var next = _highlight < 0 ? (delta > 0 ? -1 : 0) : _highlight;
105 3 : for (var step = 0; step < count; step++) {
106 4 : next = (next + delta) % count;
107 8 : if (widget.items[next]._selectable) {
108 6 : _reveal(next, forward: next > _highlight);
109 2 : _highlightRow(next);
110 : return;
111 : }
112 : }
113 : }
114 :
115 : /// Scrolls row [index] just into view when the panel scrolls internally.
116 : /// The policy only ever scrolls in the direction travelled, so a row that is
117 : /// already visible stays put.
118 2 : void _reveal(int index, {required bool forward}) {
119 6 : if (_rowKeys[index].currentContext case final row?) {
120 2 : Scrollable.ensureVisible(
121 : row,
122 : alignmentPolicy: forward
123 : ? ScrollPositionAlignmentPolicy.keepVisibleAtEnd
124 : : ScrollPositionAlignmentPolicy.keepVisibleAtStart,
125 : );
126 : }
127 : }
128 :
129 3 : void _select(int index) {
130 12 : if (!widget.items[index]._selectable) return;
131 9 : widget.onSelected(index);
132 : }
133 :
134 3 : KeyEventResult _onKey(FocusNode node, KeyEvent event) {
135 3 : if (event is KeyUpEvent) return KeyEventResult.ignored;
136 3 : final key = event.logicalKey;
137 3 : if (key == LogicalKeyboardKey.escape) {
138 9 : widget.onDismiss();
139 : return KeyEventResult.handled;
140 : }
141 2 : if (key == LogicalKeyboardKey.arrowDown) {
142 1 : _move(1);
143 : return KeyEventResult.handled;
144 : }
145 2 : if (key == LogicalKeyboardKey.arrowUp) {
146 4 : _move(-1);
147 : return KeyEventResult.handled;
148 : }
149 2 : if (key == LogicalKeyboardKey.enter || key == LogicalKeyboardKey.space) {
150 4 : if (_highlight >= 0) _select(_highlight);
151 : return KeyEventResult.handled;
152 : }
153 : return KeyEventResult.ignored;
154 : }
155 :
156 4 : @override
157 : Widget build(BuildContext context) {
158 4 : final theme = context.fossTheme;
159 12 : final visuals = _resolve(theme, widget.style);
160 4 : final shape = RoundedSuperellipseBorder(
161 8 : side: BorderSide(color: visuals.borderColor),
162 8 : borderRadius: BorderRadius.circular(visuals.borderRadius),
163 : );
164 :
165 : // IntrinsicWidth so the panel hugs its widest row above the minimum: a
166 : // stretched column would take the incoming maxWidth instead and open
167 : // full-bleed, which loses the anchoring.
168 4 : Widget panel = IntrinsicWidth(
169 4 : child: ConstrainedBox(
170 8 : constraints: BoxConstraints(minWidth: visuals.minWidth),
171 4 : child: DecoratedBox(
172 4 : decoration: ShapeDecoration(
173 4 : color: visuals.backgroundColor,
174 : shape: shape,
175 4 : shadows: visuals.shadows,
176 : ),
177 4 : child: ClipPath(
178 4 : clipper: ShapeBorderClipper(
179 : shape: shape,
180 4 : textDirection: Directionality.of(context),
181 : ),
182 4 : child: Stack(
183 4 : children: [
184 4 : Padding(
185 4 : padding: visuals.padding,
186 8 : child: SingleChildScrollView(child: _rows(visuals)),
187 : ),
188 : // Decorative and above the rows, so it must not take the taps
189 : // meant for them.
190 4 : Positioned.fill(
191 4 : child: IgnorePointer(
192 8 : child: OverlayInnerRing(colors: theme.colors),
193 : ),
194 : ),
195 : ],
196 : ),
197 : ),
198 : ),
199 : ),
200 : );
201 :
202 4 : panel = Focus(
203 4 : focusNode: _focus,
204 4 : onKeyEvent: _onKey,
205 : autofocus: true,
206 : child: panel,
207 : );
208 :
209 : // The container role goes on only when a row wears the menu-item role,
210 : // which needs it. Over an empty list, or one of only separators and
211 : // headings, the role would be a menu with no items, a framework error.
212 4 : if (_hasRows) {
213 4 : panel = Semantics(
214 : role: SemanticsRole.menu,
215 : container: true,
216 : child: panel,
217 : );
218 : }
219 :
220 : // The scale wraps the whole layer and pivots on the anchor's center, so
221 : // the panel grows out of the trigger on whichever side the layout settles
222 : // it, after a flip or a clamp included.
223 12 : final pivot = widget.anchor.center;
224 4 : return MatrixTransition(
225 8 : animation: widget.animation,
226 : alignment: Alignment.topLeft,
227 4 : onTransform: (value) {
228 12 : final scale = _openScale + (1 - _openScale) * value;
229 8 : return Matrix4.diagonal3Values(scale, scale, 1)..setTranslationRaw(
230 12 : pivot.dx * (1 - scale),
231 12 : pivot.dy * (1 - scale),
232 : 0,
233 : );
234 : },
235 4 : child: CustomSingleChildLayout(
236 4 : delegate: AnchoredLayout(
237 8 : anchor: widget.anchor,
238 8 : side: widget.side,
239 8 : align: widget.align,
240 8 : sideOffset: widget.sideOffset,
241 4 : padding: overlaySafeArea(context),
242 : ),
243 12 : child: FadeTransition(opacity: widget.animation, child: panel),
244 : ),
245 : );
246 : }
247 :
248 8 : Widget _rows(_MenuVisuals visuals) => Column(
249 : crossAxisAlignment: CrossAxisAlignment.stretch,
250 : mainAxisSize: MainAxisSize.min,
251 4 : children: [
252 20 : for (var i = 0; i < widget.items.length; i++)
253 16 : _row(visuals, widget.items[i], i),
254 : ],
255 : );
256 :
257 4 : Widget _row(_MenuVisuals visuals, FossMenuItem item, int index) =>
258 4 : switch (item._kind) {
259 7 : _MenuItemKind.separator => _MenuSeparator(visuals: visuals),
260 7 : _MenuItemKind.label => _MenuLabel(item: item, visuals: visuals),
261 8 : _MenuItemKind.item => _MenuRow(
262 8 : key: _rowKeys[index],
263 : item: item,
264 : visuals: visuals,
265 8 : highlighted: index == _highlight,
266 2 : onEnter: () => _highlightRow(index),
267 4 : onTap: () => _select(index),
268 : ),
269 : };
270 : }
271 :
272 : /// An action row: an optional glyph, the label, and an optional shortcut, over
273 : /// a highlight that follows the pointer and the arrow keys.
274 : class _MenuRow extends StatelessWidget {
275 4 : const _MenuRow({
276 : required this.item,
277 : required this.visuals,
278 : required this.highlighted,
279 : required this.onEnter,
280 : required this.onTap,
281 : super.key,
282 : });
283 :
284 : final FossMenuItem item;
285 : final _MenuVisuals visuals;
286 : final bool highlighted;
287 : final VoidCallback onEnter;
288 : final VoidCallback onTap;
289 :
290 4 : @override
291 : Widget build(BuildContext context) {
292 8 : final enabled = item.enabled;
293 8 : final color = visuals.rowColor(
294 4 : highlighted: highlighted,
295 8 : destructive: item.destructive,
296 : );
297 :
298 4 : Widget row = Padding(
299 4 : padding: EdgeInsetsDirectional.only(
300 16 : start: item.inset ? _insetStart : visuals.rowPadding,
301 8 : end: visuals.rowPadding,
302 8 : top: visuals.rowPaddingY,
303 8 : bottom: visuals.rowPaddingY,
304 : ),
305 4 : child: Row(
306 8 : spacing: visuals.gap,
307 4 : children: [
308 8 : if (item.icon case final icon?)
309 0 : IconTheme.merge(
310 0 : data: IconThemeData(
311 0 : color: color.withValues(alpha: color.a * _iconOpacity),
312 0 : size: visuals.iconSize,
313 : ),
314 : child: icon,
315 : ),
316 : // The label takes the slack, which pushes a shortcut to the row end
317 : // and ellipsizes a long label once the panel hits the viewport.
318 4 : Expanded(
319 4 : child: Text(
320 8 : item.label,
321 : maxLines: 1,
322 : overflow: TextOverflow.ellipsis,
323 12 : style: visuals.textStyle.copyWith(color: color),
324 : ),
325 : ),
326 8 : if (item.shortcut case final shortcut?)
327 6 : Text(shortcut, style: visuals.shortcutStyle),
328 : ],
329 : ),
330 : );
331 :
332 4 : row = ConstrainedBox(
333 : constraints: const BoxConstraints(minHeight: _rowMinHeight),
334 4 : child: DecoratedBox(
335 4 : decoration: ShapeDecoration(
336 8 : color: highlighted ? visuals.highlightColor : null,
337 4 : shape: RoundedSuperellipseBorder(
338 12 : borderRadius: BorderRadius.circular(visuals.rowRadius),
339 : ),
340 : ),
341 4 : child: Align(heightFactor: 1, child: row),
342 : ),
343 : );
344 :
345 3 : if (!enabled) row = Opacity(opacity: _disabledOpacity, child: row);
346 :
347 : // One merged node per row, so the label and its shortcut are announced
348 : // together rather than as two nodes.
349 4 : return MergeSemantics(
350 4 : child: Semantics(
351 : role: SemanticsRole.menuItem,
352 : button: true,
353 : enabled: enabled,
354 4 : child: MouseRegion(
355 : cursor: enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,
356 3 : onEnter: enabled ? (_) => onEnter() : null,
357 4 : child: GestureDetector(
358 : behavior: HitTestBehavior.opaque,
359 4 : onTap: enabled ? onTap : null,
360 : child: row,
361 : ),
362 : ),
363 : ),
364 : );
365 : }
366 : }
367 :
368 : /// The divider between two groups of rows.
369 : class _MenuSeparator extends StatelessWidget {
370 3 : const _MenuSeparator({required this.visuals});
371 :
372 : final _MenuVisuals visuals;
373 :
374 3 : @override
375 3 : Widget build(BuildContext context) => ExcludeSemantics(
376 3 : child: Padding(
377 3 : padding: EdgeInsets.symmetric(
378 6 : horizontal: visuals.rowPadding,
379 6 : vertical: visuals.rowPaddingY,
380 : ),
381 3 : child: SizedBox(
382 : height: _separatorThickness,
383 9 : child: ColoredBox(color: visuals.separatorColor),
384 : ),
385 : ),
386 : );
387 : }
388 :
389 : /// The heading above a group of rows. Announced with the menu, but not a row:
390 : /// it takes no input and the keyboard walk skips it.
391 : class _MenuLabel extends StatelessWidget {
392 3 : const _MenuLabel({required this.item, required this.visuals});
393 :
394 : final FossMenuItem item;
395 : final _MenuVisuals visuals;
396 :
397 3 : @override
398 3 : Widget build(BuildContext context) => Padding(
399 3 : padding: EdgeInsetsDirectional.only(
400 12 : start: item.inset ? _labelInsetStart : visuals.rowPadding,
401 6 : end: visuals.rowPadding,
402 6 : top: visuals.labelPaddingY,
403 6 : bottom: visuals.labelPaddingY,
404 : ),
405 15 : child: Text(item.label, style: visuals.labelStyle),
406 : );
407 : }
|