Files
pipelines/app/lib/ui/theme/design_focus_ring.dart
T

196 lines
6.0 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'app_design_tokens.dart';
/// Draws the design's [FocusRingStyle] around whatever has keyboard focus,
/// over the whole app (dialogs and menus included), as a browser draws its
/// focus outline: every focusable gets the ring without per-widget code.
///
/// Like a browser's `:focus-visible`, it shows only while the keyboard
/// drives: a key press turns it on and any pointer press (a click, a tap)
/// turns it off, so clicking into the transcript draws no frame round it.
/// It shows only under a design with a ring; otherwise it paints nothing. The overlay is always in the tree, so a design switch keeps the
/// app's subtree. It follows a focused control as it scrolls by checking its
/// rect after each frame the app draws anyway; it never schedules frames.
class DesignFocusRing extends StatefulWidget {
const DesignFocusRing({super.key, required this.child});
final Widget child;
@override
State<DesignFocusRing> createState() => _DesignFocusRingState();
}
class _DesignFocusRingState extends State<DesignFocusRing> {
final _rect = ValueNotifier<Rect?>(null);
final _overlay = GlobalKey();
FocusRingStyle? _style;
bool _tracking = false;
/// Whether the keyboard, not a pointer, was used last.
bool _keyboard = false;
@override
void initState() {
super.initState();
FocusManager.instance.addListener(_update);
HardwareKeyboard.instance.addHandler(_onKey);
GestureBinding.instance.pointerRouter.addGlobalRoute(_onPointer);
}
@override
void dispose() {
FocusManager.instance.removeListener(_update);
HardwareKeyboard.instance.removeHandler(_onKey);
GestureBinding.instance.pointerRouter.removeGlobalRoute(_onPointer);
_rect.dispose();
super.dispose();
}
/// Notes a key press; never handles the key.
bool _onKey(KeyEvent event) {
if (event is KeyDownEvent && !_keyboard) {
_keyboard = true;
_update();
}
return false;
}
void _onPointer(PointerEvent event) {
if (event is PointerDownEvent && _keyboard) {
_keyboard = false;
_update();
}
}
/// Where the focused control is, in the overlay's coordinates; null when
/// no ring shows.
Rect? _measure() {
if (_style == null || !_keyboard) return null;
final node = FocusManager.instance.primaryFocus;
final context = node?.context;
if (node == null || context == null || !context.mounted) return null;
// A scope (a route, the app) holds focus between controls: no ring.
if (node is FocusScopeNode) return null;
// A text field's ring goes round its whole decorated field, not the
// text inside it.
RenderObject? box = context.findRenderObject();
var steps = 0;
context.visitAncestorElements((element) {
if (element.widget is InputDecorator) {
box = element.findRenderObject();
return false;
}
return ++steps < 40;
});
final overlay = _overlay.currentContext?.findRenderObject();
final target = box;
if (target is! RenderBox || !target.hasSize || !target.attached) {
return null;
}
if (overlay is! RenderBox || !overlay.hasSize) return null;
final rect = MatrixUtils.transformRect(
target.getTransformTo(overlay),
Offset.zero & target.size,
);
if (rect.isEmpty || !(Offset.zero & overlay.size).overlaps(rect)) {
return null;
}
return rect;
}
void _update() {
if (!mounted) return;
_rect.value = _measure();
// While a ring shows, check its rect after each frame (a scroll, a
// layout change); a post-frame callback alone schedules no frame.
if (_rect.value != null && !_tracking) {
_tracking = true;
SchedulerBinding.instance.addPostFrameCallback(_afterFrame);
}
}
void _afterFrame(Duration _) {
_tracking = false;
_update();
}
@override
Widget build(BuildContext context) {
final style = AppDesignTokens.of(context).focusRing;
if (style != _style) {
_style = style;
WidgetsBinding.instance.addPostFrameCallback((_) => _update());
}
return Stack(
fit: StackFit.passthrough,
children: [
widget.child,
Positioned.fill(
child: IgnorePointer(
child: RepaintBoundary(
child: CustomPaint(
key: _overlay,
painter: style == null
? null
: FocusRingPainter(
rect: _rect,
style: style,
radius: AppDesignTokens.of(context).radius ?? 0,
),
),
),
),
),
],
);
}
}
/// Paints [style]'s ring around [rect]: a halo of the page colour, then the
/// ring, [FocusRingStyle.offset] outside the control, with rounded corners.
class FocusRingPainter extends CustomPainter {
FocusRingPainter({
required this.rect,
required this.style,
required this.radius,
}) : super(repaint: rect);
final ValueListenable<Rect?> rect;
final FocusRingStyle style;
/// The control's corner radius; the ring's corners keep it concentric.
final double radius;
@override
void paint(Canvas canvas, Size size) {
final target = rect.value;
if (target == null) return;
final ring = target.inflate(style.offset + style.width / 2);
final corner = Radius.circular(radius + style.offset);
canvas
..drawRRect(
RRect.fromRectAndRadius(target.inflate(style.offset / 2), corner),
Paint()
..style = PaintingStyle.stroke
..strokeWidth = style.offset
..color = style.halo,
)
..drawRRect(
RRect.fromRectAndRadius(ring, corner),
Paint()
..style = PaintingStyle.stroke
..strokeWidth = style.width
..color = style.color,
);
}
@override
bool shouldRepaint(FocusRingPainter old) =>
old.rect != rect || old.style != style || old.radius != radius;
}