import 'dart:math' as math; import 'package:flutter/material.dart'; import '../../../ui/adaptive/app_popups.dart'; enum DiffForm { rendered, raw } const diffFormLabels = { DiffForm.rendered: 'Rendered', DiffForm.raw: 'Raw patch', }; /// Conservatively choose between two stock controls using the current native /// label role and text scaler. This does not size or restyle either control. bool diffFormSegmentsFit(BuildContext context, double maxWidth) { final style = Theme.of(context).textTheme.labelLarge ?? DefaultTextStyle.of(context).style; var widest = 0.0; for (final label in diffFormLabels.values) { final painter = TextPainter( text: TextSpan(text: label, style: style), textDirection: Directionality.of(context), textScaler: MediaQuery.textScalerOf(context), maxLines: 1, )..layout(); widest = math.max(widest, painter.width); painter.dispose(); } return (widest + 48) * 2 <= maxWidth; } Widget diffFormControl( BuildContext context, { required DiffForm form, required ValueChanged onChanged, }) { return SegmentedButton( style: ButtonStyle(minimumSize: const WidgetStatePropertyAll(Size(0, 48))), segments: [ for (final entry in diffFormLabels.entries) ButtonSegment(value: entry.key, label: Text(entry.value)), ], selected: {form}, showSelectedIcon: false, onSelectionChanged: (selection) { if (selection.isNotEmpty) onChanged(selection.first); }, ); } /// An anchored desktop menu or narrow sheet when segment labels cannot fit. Widget diffFormMenu( BuildContext context, { required DiffForm form, required ValueChanged onChanged, }) { return IconButton( tooltip: 'Diff form', constraints: const BoxConstraints(minWidth: 48, minHeight: 48), padding: EdgeInsets.zero, icon: const Icon(Icons.more_vert, size: 28), onPressed: () => showAppChoiceMenu( context, builder: (sheetContext) => SafeArea( child: Column( mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), child: Align( alignment: AlignmentDirectional.centerStart, child: Text( 'Diff form', style: Theme.of(sheetContext).textTheme.titleMedium, ), ), ), for (final entry in diffFormLabels.entries) AppChoiceMenuItem( selected: entry.key == form, // At accessibility text sizes the check mark otherwise leaves // too little room for the longest label in the phone sheet. contentPadding: EdgeInsets.zero, onTap: () { Navigator.of(sheetContext).pop(); onChanged(entry.key); }, child: Text(entry.value), ), ], ), ), ), ); }