Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/genui/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
`package:a2ui_core` are no longer accepted.
- **Internal**: Ignore the deprecation of `package:flutter/material.dart` on
Flutter beta until genui can migrate to `package:material_ui` (#1062).
- **Fix**: `AudioPlayer` no longer overflows in narrow or large-text layouts.
Its controls sat on one row with two time labels and a fixed 100 px volume
slider next to the seek bar, so a 320 px wide phone overflowed by 28 px at
normal text size and by 148 px at 2x. When that row doesn't fit, the times
now go on a line under the seek bar and the inline volume slider is left
out, as the device's own volume still works.

## 0.10.5

Expand Down
236 changes: 163 additions & 73 deletions packages/genui/lib/src/catalog/basic_catalog_widgets/audio_player.dart
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,24 @@ final audioPlayer = CatalogItem(
],
);

/// The padding inside the player's card.
const _contentPadding = EdgeInsets.all(12);

/// The space between the time labels and the volume controls.
const double _volumeGap = 12;

/// The size of the volume icon.
const double _volumeIconSize = 20;

/// The width of the inline volume slider.
const double _volumeSliderWidth = 100;

/// The narrowest the seek bar gets before the controls wrap.
const double _minSeekBarWidth = 96;

/// Matches one digit of a time label.
final _digit = RegExp(r'\d');

class _AudioPlayerWidget extends StatefulWidget {
const _AudioPlayerWidget({required this.url, this.description});

Expand Down Expand Up @@ -154,14 +172,121 @@ class _AudioPlayerWidgetState extends State<_AudioPlayerWidget> {
super.dispose();
}

/// Whether all the controls fit on one row [maxWidth] wide.
///
/// The row holds the play button, both times, a seek bar at least
/// [_minSeekBarWidth] wide, and the volume controls. The times are measured
/// with the ambient text scaler, so large text wraps the controls too.
///
/// Both times are measured as the longer of the two, which is the duration
/// once it is known, with every digit as `0`, so the layout doesn't change
/// while the audio plays, even with proportional digits.
bool _fitsOnOneRow(BuildContext context, double maxWidth, TextStyle style) {
final Duration longest = _position > _duration ? _position : _duration;
final String label = formatDuration(longest).replaceAll(_digit, '0');
final painter = TextPainter(
text: TextSpan(text: label, style: style),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
maxLines: 1,
)..layout();
final double timeWidth = painter.width;
painter.dispose();

final double width =
kMinInteractiveDimension +
2 * timeWidth +
_minSeekBarWidth +
_volumeGap +
_volumeIconSize +
_volumeSliderWidth +
_contentPadding.right;
return width <= maxWidth;
}
Comment on lines +180 to +203

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Performance & Robustness Issue

  1. Performance: _fitsOnOneRow is called on every build of the LayoutBuilder. Since _AudioPlayerWidgetState updates its state frequently during playback (e.g., on position changes), this triggers frequent rebuilds and synchronous text layout calls (TextPainter.layout()), which is computationally expensive and can cause UI jank or high CPU usage.
  2. Robustness: Using Directionality.of(context) and MediaQuery.textScalerOf(context) can throw exceptions if the widget is rendered in an environment (like some unit/widget tests) without these inherited widgets.

Solution

Cache the measured text width and only recalculate it when the text scaler, text style, or label length changes. Also, use maybeOf and maybeTextScalerOf with safe fallbacks to prevent potential crashes.

  TextScaler? _lastTextScaler;
  TextStyle? _lastTextStyle;
  int? _lastLabelLength;
  double? _lastTimeWidth;

  /// Whether all the controls fit on one row [maxWidth] wide.
  ///
  /// The row holds the play button, both times, a seek bar at least
  /// [_minSeekBarWidth] wide, and the volume controls. The times are measured
  /// with the ambient text scaler, so large text wraps the controls too.
  ///
  /// Both times are measured as the longer of the two, which is the duration
  /// once it is known, with every digit as `0`, so the layout doesn't change
  /// while the audio plays, even with proportional digits.
  bool _fitsOnOneRow(BuildContext context, double maxWidth, TextStyle style) {
    final Duration longest = _position > _duration ? _position : _duration;
    final String label = formatDuration(longest).replaceAll(_digit, '0');

    final textScaler = MediaQuery.maybeTextScalerOf(context) ?? TextScaler.noScaling;
    if (_lastTextScaler != textScaler ||
        _lastTextStyle != style ||
        _lastLabelLength != label.length ||
        _lastTimeWidth == null) {
      final painter = TextPainter(
        text: TextSpan(text: label, style: style),
        textDirection: Directionality.maybeOf(context) ?? TextDirection.ltr,
        textScaler: textScaler,
        maxLines: 1,
      )..layout();
      _lastTextScaler = textScaler;
      _lastTextStyle = style;
      _lastLabelLength = label.length;
      _lastTimeWidth = painter.width;
      painter.dispose();
    }

    final double width =
        kMinInteractiveDimension +
        2 * _lastTimeWidth! +
        _minSeekBarWidth +
        _volumeGap +
        _volumeIconSize +
        _volumeSliderWidth +
        _contentPadding.right;
    return width <= maxWidth;
  }

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cached in ff95b07: the last TextPainter is kept and laid out again only when the label, style, text direction or text scaler changes, so position updates during playback no longer re-measure the text. It is disposed in dispose().

Directionality.of / MediaQuery.textScalerOf stay as they are: the widget already renders Text, Slider and IconButton, which require both ancestors, so a maybeOf fallback here would not make it work anywhere it fails today.


Widget _buildPlayButton() {
return IconButton(
tooltip: _isPlaying ? 'Pause' : 'Play',
icon: Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
onPressed: widget.url != null && widget.url!.isNotEmpty
? () {
if (_isPlaying) {
_player.pause();
} else {
_player.resume();
}
}
: null,
);
}

Widget _buildSeekBar() {
return MergeSemantics(
child: Semantics(
label: 'Playback position',
child: Slider(
value: _duration.inMilliseconds > 0
? _position.inMilliseconds
.clamp(0, _duration.inMilliseconds)
.toDouble()
: 0,
max: _duration.inMilliseconds > 0
? _duration.inMilliseconds.toDouble()
: 1,
onChanged: (value) {
_player.seek(Duration(milliseconds: value.toInt()));
},
),
),
);
}

List<Widget> _buildVolumeControls(BuildContext context) {
return [
const SizedBox(width: _volumeGap),
Icon(
_volume == 0
? Icons.volume_off
: _volume < 0.5
? Icons.volume_down
: Icons.volume_up,
size: _volumeIconSize,
),
SizedBox(
width: _volumeSliderWidth,
child: SliderTheme(
data: SliderTheme.of(context).copyWith(
overlayShape: SliderComponentShape.noOverlay,
padding: EdgeInsets.zero,
),
child: MergeSemantics(
child: Semantics(
label: 'Volume',
child: Slider(
value: _volume,
onChanged: (value) {
setState(() => _volume = value);
_player.setVolume(value);
},
),
),
),
),
),
SizedBox(width: _contentPadding.right),
];
}

@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
const contentPadding = EdgeInsets.all(12);
final TextStyle timeStyle = DefaultTextStyle.of(
context,
).style.merge(theme.textTheme.bodySmall);

return Card(
child: Padding(
padding: contentPadding,
padding: _contentPadding,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
Expand All @@ -176,81 +301,46 @@ class _AudioPlayerWidgetState extends State<_AudioPlayerWidget> {
overflow: TextOverflow.ellipsis,
),
),
Row(
children: [
IconButton(
tooltip: _isPlaying ? 'Pause' : 'Play',
icon: Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
onPressed: widget.url != null && widget.url!.isNotEmpty
? () {
if (_isPlaying) {
_player.pause();
} else {
_player.resume();
}
}
: null,
),
Text(
LayoutBuilder(
builder: (context, constraints) {
final position = Text(
formatDuration(_position),
style: theme.textTheme.bodySmall,
),
Expanded(
child: MergeSemantics(
child: Semantics(
label: 'Playback position',
child: Slider(
value: _duration.inMilliseconds > 0
? _position.inMilliseconds
.clamp(0, _duration.inMilliseconds)
.toDouble()
: 0,
max: _duration.inMilliseconds > 0
? _duration.inMilliseconds.toDouble()
: 1,
onChanged: (value) {
_player.seek(Duration(milliseconds: value.toInt()));
},
),
),
),
),
Text(
style: timeStyle,
);
final duration = Text(
formatDuration(_duration),
style: theme.textTheme.bodySmall,
),
const SizedBox(width: 12),
Icon(
_volume == 0
? Icons.volume_off
: _volume < 0.5
? Icons.volume_down
: Icons.volume_up,
size: 20,
),
SizedBox(
width: 100,
child: SliderTheme(
data: SliderTheme.of(context).copyWith(
overlayShape: SliderComponentShape.noOverlay,
padding: EdgeInsets.zero,
style: timeStyle,
);
if (_fitsOnOneRow(context, constraints.maxWidth, timeStyle)) {
return Row(
children: [
_buildPlayButton(),
position,
Expanded(child: _buildSeekBar()),
duration,
..._buildVolumeControls(context),
],
);
}
// Too narrow for one row: the times go under the seek bar,
// and the volume is left to the device's own controls.
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
_buildPlayButton(),
Expanded(child: _buildSeekBar()),
],
),
child: MergeSemantics(
child: Semantics(
label: 'Volume',
child: Slider(
value: _volume,
onChanged: (value) {
setState(() => _volume = value);
_player.setVolume(value);
},
),
),
Wrap(
alignment: WrapAlignment.spaceBetween,
children: [position, duration],
),
Comment on lines +359 to 362

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Layout Optimization

Using Wrap here is slightly less efficient than Row with mainAxisAlignment: MainAxisAlignment.spaceBetween. Since the two time labels are very short (e.g., 00:00), they will always fit side-by-side even at 2.0x text scale on a 320px screen. Using Row is a more standard and performant choice.

Suggested change
Wrap(
alignment: WrapAlignment.spaceBetween,
children: [position, duration],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [position, duration],
),

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping Wrap. The two-row layout is the fallback for widths where things already do not fit, and the times there are not always short: past an hour they read 1:00:00, and the player can sit in a narrow parent (a card in a Row, a grid cell) at large text scales. A Row would overflow in those cases; Wrap puts the duration on its own line instead. For the common case it lays out the same as the Row, and the cost of two children is negligible.

),
),
SizedBox(width: contentPadding.right),
],
],
);
},
),
],
),
Expand Down
96 changes: 96 additions & 0 deletions packages/genui/test/catalog/core_widgets/audio_player_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,100 @@ void main() {

expect(find.text('Audio Description'), findsOneWidget);
});

group('AudioPlayer in a narrow view', () {
for (final scale in <double>[1.0, 2.0]) {
testWidgets('fits 320 px at ${scale}x text', (tester) async {
final SemanticsHandle handle = await _show(tester, textScale: scale);

expect(tester.takeException(), isNull);
expect(find.byIcon(Icons.play_arrow), findsOneWidget);
expect(find.bySemanticsLabel('Playback position'), findsOneWidget);
handle.dispose();
});
}

testWidgets('puts the times under the seek bar and drops the volume', (
tester,
) async {
final SemanticsHandle handle = await _show(tester);

final Rect seekBar = tester.getRect(
find.bySemanticsLabel('Playback position'),
);
expect(find.text('00:00'), findsNWidgets(2));
for (final Element time in find.text('00:00').evaluate()) {
final Rect rect = tester.getRect(find.byWidget(time.widget));
expect(rect.top, greaterThanOrEqualTo(seekBar.bottom));
}
expect(find.bySemanticsLabel('Volume'), findsNothing);
handle.dispose();
});
});

testWidgets('AudioPlayer keeps its volume slider in a wide view', (
tester,
) async {
final SemanticsHandle handle = await _show(tester, width: 800);

expect(tester.takeException(), isNull);
expect(find.bySemanticsLabel('Volume'), findsOneWidget);
handle.dispose();
});
}

/// Shows a [BasicCatalogItems.audioPlayer] in a view [width] logical pixels
/// wide, with its text scaled by [textScale].
///
/// The caller disposes the returned handle.
Future<SemanticsHandle> _show(
WidgetTester tester, {
double width = 320,
double textScale = 1.0,
}) async {
tester.view.physicalSize = Size(width, 640);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);

final surfaceController = SurfaceController(
catalogs: [
Catalog([BasicCatalogItems.audioPlayer], catalogId: 'test_catalog'),
],
);
addTearDown(surfaceController.dispose);
const surfaceId = 'testSurface';
surfaceController.handleMessage(
updateComponents(
surfaceId: surfaceId,
components: [
component(
id: 'root',
type: 'AudioPlayer',
properties: {
'url': 'https://example.com/audio.mp3',
'description': 'Audio Description',
},
),
],
),
);
surfaceController.handleMessage(
createSurface(surfaceId: surfaceId, catalogId: 'test_catalog'),
);

final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
MaterialApp(
home: MediaQuery.withClampedTextScaling(
minScaleFactor: textScale,
maxScaleFactor: textScale,
child: Scaffold(
body: Surface(
surfaceContext: surfaceController.contextFor(surfaceId),
),
),
),
),
);
return handle;
}
Loading