fix(player): 聚焦时保留评论列表并稳定焦点

This commit is contained in:
Zhou Weidong committed 2026-10-21 12:53:46 +08:00
1 parent de99c09454
commit ad69ef7f54
2 files changed
+141 -115

No files matched your search

@@ -34,6 +34,7 @@ const double _composerTopGap = 8;
const double _replyBannerHeight = 46; const double _replyBannerHeight = 46;
const double _expandedInputRadius = 12; const double _expandedInputRadius = 12;
const double _postButtonHeight = 32; const double _postButtonHeight = 32;
const double _expandedComposerReserve = 113;
/// 服务端评论底部弹窗:匿名列表、游标翻页、回复与登录发布。 /// 服务端评论底部弹窗:匿名列表、游标翻页、回复与登录发布。
class DramaCommentsSheet extends StatefulWidget { class DramaCommentsSheet extends StatefulWidget {
@@ -45,22 +46,22 @@ class DramaCommentsSheet extends StatefulWidget {
State<DramaCommentsSheet> createState() => _DramaCommentsSheetState(); State<DramaCommentsSheet> createState() => _DramaCommentsSheetState();
} }
class _DramaCommentsSheetState extends State<DramaCommentsSheet> class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
with WidgetsBindingObserver {
final _input = TextEditingController(); final _input = TextEditingController();
final _inputFocus = FocusNode(); final _inputFocus = FocusNode();
final _keyboardInset = KeyboardInsetNotifier.instance; final _keyboardInset = KeyboardInsetNotifier.instance;
final _sheetMeasureKey = GlobalKey();
late final CommentRepository _comments; late final CommentRepository _comments;
late final CommentController _controller; late final CommentController _controller;
DramaComment? _replyTo; DramaComment? _replyTo;
int? _serverCount; int? _serverCount;
int _countRequest = 0; int _countRequest = 0;
bool _keyboardWasVisible = false; double? _sheetHeightWithoutKeyboard;
bool _sheetMeasureScheduled = false;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
WidgetsBinding.instance.addObserver(this);
_inputFocus.addListener(_onFocusChanged); _inputFocus.addListener(_onFocusChanged);
_input.addListener(_onInputChanged); _input.addListener(_onInputChanged);
_keyboardInset.addListener(_onKeyboardInsetChanged); _keyboardInset.addListener(_onKeyboardInsetChanged);
@@ -77,7 +78,6 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet>
@override @override
void dispose() { void dispose() {
WidgetsBinding.instance.removeObserver(this);
_keyboardInset.removeListener(_onKeyboardInsetChanged); _keyboardInset.removeListener(_onKeyboardInsetChanged);
_inputFocus.removeListener(_onFocusChanged); _inputFocus.removeListener(_onFocusChanged);
_input.removeListener(_onInputChanged); _input.removeListener(_onInputChanged);
@@ -98,35 +98,6 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet>
void _onKeyboardInsetChanged() { void _onKeyboardInsetChanged() {
if (!mounted) return; if (!mounted) return;
setState(() {}); setState(() {});
_syncKeyboardVisibility(
math.max(
MediaQuery.viewInsetsOf(context).bottom,
_keyboardInset.value / MediaQuery.devicePixelRatioOf(context),
),
);
}
@override
void didChangeMetrics() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_syncKeyboardVisibility(
math.max(
MediaQuery.viewInsetsOf(context).bottom,
_keyboardInset.value / MediaQuery.devicePixelRatioOf(context),
),
);
});
}
void _syncKeyboardVisibility(num keyboardHeight) {
if (keyboardHeight > 0) {
_keyboardWasVisible = true;
return;
}
if (!_keyboardWasVisible) return;
_keyboardWasVisible = false;
if (_inputFocus.hasFocus) _inputFocus.unfocus();
} }
double _keyboardHeight(BuildContext context) => math.max( double _keyboardHeight(BuildContext context) => math.max(
@@ -134,6 +105,25 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet>
_keyboardInset.value / MediaQuery.devicePixelRatioOf(context), _keyboardInset.value / MediaQuery.devicePixelRatioOf(context),
); );
void _measureSheetWithoutKeyboard(double keyboardHeight) {
if (keyboardHeight > 0 || _sheetMeasureScheduled) return;
_sheetMeasureScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_sheetMeasureScheduled = false;
if (!mounted) return;
if (_keyboardHeight(context) > 0) return;
final box = _sheetMeasureKey.currentContext?.findRenderObject();
if (box is! RenderBox || !box.hasSize) return;
final height = box.size.height;
if (!height.isFinite ||
(_sheetHeightWithoutKeyboard != null &&
(height - _sheetHeightWithoutKeyboard!).abs() < 0.5)) {
return;
}
setState(() => _sheetHeightWithoutKeyboard = height);
});
}
Future<void> _post() async { Future<void> _post() async {
if (_controller.submitting) return; if (_controller.submitting) return;
if (!await ensureSignedIn(context) || !mounted) return; if (!await ensureSignedIn(context) || !mounted) return;
@@ -196,13 +186,12 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet>
: _maxSheetHeight; : _maxSheetHeight;
final focused = _inputFocus.hasFocus; final focused = _inputFocus.hasFocus;
final keyboardHeight = _keyboardHeight(context); final keyboardHeight = _keyboardHeight(context);
return AnimatedPadding( _measureSheetWithoutKeyboard(keyboardHeight);
duration: const Duration(milliseconds: 150), return GestureDetector(
curve: Curves.easeOut, behavior: HitTestBehavior.translucent,
padding: EdgeInsets.only(bottom: focused ? keyboardHeight : 0), onTap: focused ? _inputFocus.unfocus : null,
child: GestureDetector( child: SizedBox(
behavior: HitTestBehavior.translucent, key: _sheetMeasureKey,
onTap: focused ? _inputFocus.unfocus : null,
child: Container( child: Container(
key: const Key('player-comments-sheet'), key: const Key('player-comments-sheet'),
decoration: const BoxDecoration( decoration: const BoxDecoration(
@@ -216,22 +205,27 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet>
child: ListenableBuilder( child: ListenableBuilder(
listenable: _controller, listenable: _controller,
builder: (context, _) { builder: (context, _) {
final minHeight = !focused && _controller.comments.isEmpty final minHeight = _controller.comments.isEmpty
? (_minSheetHeight < maxHeight ? (_minSheetHeight < maxHeight
? _minSheetHeight ? _minSheetHeight
: maxHeight) : maxHeight)
: 0.0; : 0.0;
final pinnedHeight =
keyboardHeight > 0 && _sheetHeightWithoutKeyboard != null
? math.min(_sheetHeightWithoutKeyboard!, maxHeight)
: null;
return ConstrainedBox( return ConstrainedBox(
key: const Key('comment-sheet-constraints'), key: const Key('comment-sheet-constraints'),
constraints: BoxConstraints( constraints: pinnedHeight == null
minHeight: minHeight, ? BoxConstraints(
maxHeight: maxHeight, minHeight: minHeight,
), maxHeight: maxHeight,
)
: BoxConstraints.tightFor(height: pinnedHeight),
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16), padding: const EdgeInsets.symmetric(horizontal: 16),
child: _content( child: _content(
context, context,
maxHeight: maxHeight,
focused: focused, focused: focused,
keyboardHeight: keyboardHeight, keyboardHeight: keyboardHeight,
), ),
@@ -247,85 +241,86 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet>
Widget _content( Widget _content(
BuildContext context, { BuildContext context, {
required double maxHeight,
required bool focused, required bool focused,
required double keyboardHeight, required double keyboardHeight,
}) { }) {
final l10n = AppLocalizations.of(context)!; final l10n = AppLocalizations.of(context)!;
final count = _serverCount ?? _controller.exactCount; final count = _serverCount ?? _controller.exactCount;
final replyReserve = _replyTo == null ? 0.0 : _replyBannerHeight; final composerReserve = focused
final listMaxHeight = ? _expandedComposerReserve
maxHeight - : _composerHeight + _composerTopGap;
_headerHeight -
_composerHeight -
_composerTopGap -
replyReserve;
return Column( return Column(
key: const Key('comment-sheet-content'), key: const Key('comment-sheet-content'),
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
SizedBox( SizedBox(
height: focused ? 0 : _headerHeight, height: _headerHeight,
width: double.infinity, width: double.infinity,
child: focused child: Stack(
? null alignment: Alignment.center,
: Stack( children: [
alignment: Alignment.center, Text(
children: [ count == null ? l10n.comments : l10n.commentsWithCount(count),
Text( key: const Key('comment-count-label'),
count == null textAlign: TextAlign.center,
? l10n.comments style: const TextStyle(
: l10n.commentsWithCount(count), color: AppColors.onSurface,
key: const Key('comment-count-label'), fontSize: 16,
textAlign: TextAlign.center, fontWeight: FontWeight.w600,
style: const TextStyle(
color: AppColors.onSurface,
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
Positioned(
left: 0,
child: SizedBox.square(
dimension: 44,
child: IconButton(
key: const Key('player-comments-close'),
tooltip: l10n.close,
padding: EdgeInsets.zero,
onPressed: () => Navigator.pop(context),
icon: const Icon(
Icons.keyboard_arrow_down_rounded,
size: 24,
color: AppColors.cream,
),
),
),
),
],
), ),
),
Positioned(
left: 0,
child: SizedBox.square(
dimension: 44,
child: IconButton(
key: const Key('player-comments-close'),
tooltip: l10n.close,
padding: EdgeInsets.zero,
onPressed: () => Navigator.pop(context),
icon: const Icon(
Icons.keyboard_arrow_down_rounded,
size: 24,
color: AppColors.cream,
),
),
),
),
],
),
), ),
ConstrainedBox( Flexible(
constraints: BoxConstraints( fit: FlexFit.loose,
maxHeight: focused || listMaxHeight < 0 ? 0 : listMaxHeight, child: _list(
l10n,
composerReserve: composerReserve,
keyboardHeight: keyboardHeight,
), ),
child: focused
? const SizedBox.shrink()
: _list(l10n, keyboardHeight: keyboardHeight),
), ),
if (_replyTo != null) _replyBanner(l10n, _replyTo!), if (_replyTo != null) _replyBanner(l10n, _replyTo!),
Padding( AnimatedContainer(
padding: EdgeInsets.only( key: const Key('comment-input-lift'),
top: focused ? 12 : _composerTopGap, duration: const Duration(milliseconds: 200),
bottom: focused ? 12 : 0, curve: Curves.easeOut,
transform: Matrix4.translationValues(0, -keyboardHeight, 0),
child: Padding(
padding: EdgeInsets.only(
top: focused ? 12 : _composerTopGap,
bottom: focused ? 12 : 0,
),
child: _composer(l10n, focused: focused),
), ),
child: _composer(l10n, focused: focused),
), ),
], ],
); );
} }
Widget _list(AppLocalizations l10n, {required double keyboardHeight}) { Widget _list(
AppLocalizations l10n, {
required double composerReserve,
required double keyboardHeight,
}) {
if (_controller.loading && _controller.comments.isEmpty) { if (_controller.loading && _controller.comments.isEmpty) {
return const Padding( return const Padding(
padding: EdgeInsets.only(top: 4), padding: EdgeInsets.only(top: 4),
@@ -364,7 +359,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet>
shrinkWrap: true, shrinkWrap: true,
padding: EdgeInsets.only( padding: EdgeInsets.only(
top: 4, top: 4,
bottom: _composerHeight + keyboardHeight, bottom: composerReserve + keyboardHeight,
), ),
itemCount: _controller.comments.length + 1, itemCount: _controller.comments.length + 1,
itemBuilder: (context, index) { itemBuilder: (context, index) {
+42 -11
View File
@@ -247,7 +247,8 @@ void main() {
expect(tester.widget<TextField>(input).controller?.text, isEmpty); expect(tester.widget<TextField>(input).controller?.text, isEmpty);
expect(tester.widget<TextField>(input).focusNode?.hasFocus, isTrue); expect(tester.widget<TextField>(input).focusNode?.hasFocus, isTrue);
expect(tester.widget<TextField>(input).maxLines, 4); expect(tester.widget<TextField>(input).maxLines, 4);
expect(find.byKey(const Key('comment-list')), findsNothing); expect(find.byKey(const Key('comment-list')), findsOneWidget);
expect(find.byKey(const Key('comment-count-label')), findsOneWidget);
expect( expect(
tester tester
.widget<TextButton>(find.byKey(const Key('comment-post'))) .widget<TextButton>(find.byKey(const Key('comment-post')))
@@ -285,8 +286,8 @@ void main() {
await tester.tap(find.byKey(const Key('comment-input'))); await tester.tap(find.byKey(const Key('comment-input')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byKey(const Key('comment-list')), findsNothing); expect(find.byKey(const Key('comment-list')), findsOneWidget);
expect(find.byKey(const Key('comment-count-label')), findsNothing); expect(find.byKey(const Key('comment-count-label')), findsOneWidget);
expect(find.byKey(const Key('comment-composer')), findsOneWidget); expect(find.byKey(const Key('comment-composer')), findsOneWidget);
expect(find.byKey(const Key('comment-input-surface')), findsOneWidget); expect(find.byKey(const Key('comment-input-surface')), findsOneWidget);
final editableAfter = tester.state<EditableTextState>( final editableAfter = tester.state<EditableTextState>(
@@ -309,7 +310,6 @@ void main() {
isNull, isNull,
); );
expect(tester.getSize(find.byKey(const Key('comment-post'))).height, 32); expect(tester.getSize(find.byKey(const Key('comment-post'))).height, 32);
expect(find.byType(IconButton), findsNothing);
expect(find.byIcon(Icons.image_outlined), findsNothing); expect(find.byIcon(Icons.image_outlined), findsNothing);
expect(find.byIcon(Icons.emoji_emotions_outlined), findsNothing); expect(find.byIcon(Icons.emoji_emotions_outlined), findsNothing);
expect(find.byIcon(Icons.alternate_email_rounded), findsNothing); expect(find.byIcon(Icons.alternate_email_rounded), findsNothing);
@@ -323,24 +323,55 @@ void main() {
isNotNull, isNotNull,
); );
final sheet = find.byKey(const Key('player-comments-sheet'));
final list = find.byKey(const Key('comment-list'));
final sheetTop = tester.getTopLeft(sheet).dy;
final listTop = tester.getTopLeft(list).dy;
tester.view.viewInsets = const FakeViewPadding(bottom: 180); tester.view.viewInsets = const FakeViewPadding(bottom: 180);
await tester.pump(); await tester.pump();
await tester.pump(const Duration(milliseconds: 160)); await tester.pump(const Duration(milliseconds: 200));
expect(find.byKey(const Key('player-comments-sheet')), findsOneWidget); expect(sheet, findsOneWidget);
expect(find.byKey(const Key('comment-list')), findsNothing); expect(list, findsOneWidget);
expect(find.byKey(const Key('comment-count-label')), findsOneWidget);
final editableDuringKeyboard = tester.state<EditableTextState>(
find.descendant(
of: find.byKey(const Key('comment-input')),
matching: find.byType(EditableText),
),
);
expect(identical(editableAfter, editableDuringKeyboard), isTrue);
expect(tester.getTopLeft(sheet).dy, closeTo(sheetTop, 0.1));
expect(tester.getTopLeft(list).dy, closeTo(listTop, 0.1));
expect( expect(
tester.getBottomLeft(find.byKey(const Key('player-comments-sheet'))).dy, tester.widget<ListView>(list).padding?.resolve(TextDirection.ltr).bottom,
closeTo(844 - 180, 0.1), greaterThanOrEqualTo(180 + 44),
); );
expect( expect(
tester.getBottomLeft(find.byKey(const Key('comment-input'))).dy, tester.getBottomLeft(find.byKey(const Key('comment-input'))).dy,
lessThanOrEqualTo(844 - 180), lessThanOrEqualTo(844 - 180),
); );
expect(
tester
.widget<TextField>(find.byKey(const Key('comment-input')))
.focusNode
?.hasFocus,
isTrue,
);
tester.view.viewInsets = const FakeViewPadding(); tester.view.viewInsets = const FakeViewPadding();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byKey(const Key('comment-list')), findsOneWidget); expect(list, findsOneWidget);
expect(find.byKey(const Key('comment-count-label')), findsOneWidget);
expect(find.byKey(const Key('comment-composer')), findsOneWidget); expect(find.byKey(const Key('comment-composer')), findsOneWidget);
final editableAfterKeyboard = tester.state<EditableTextState>(
find.descendant(
of: find.byKey(const Key('comment-input')),
matching: find.byType(EditableText),
),
);
expect(identical(editableAfter, editableAfterKeyboard), isTrue);
expect(tester.getTopLeft(sheet).dy, closeTo(sheetTop, 0.1));
expect(tester.getTopLeft(list).dy, closeTo(listTop, 0.1));
expect( expect(
tester tester
.widget<TextField>(find.byKey(const Key('comment-input'))) .widget<TextField>(find.byKey(const Key('comment-input')))
@@ -353,7 +384,7 @@ void main() {
.widget<TextField>(find.byKey(const Key('comment-input'))) .widget<TextField>(find.byKey(const Key('comment-input')))
.focusNode .focusNode
?.hasFocus, ?.hasFocus,
isFalse, isTrue,
); );
}); });