Perf round 4: lazy chat sessions list
Chat sections are slivers: a lazy, keyed SliverList under the same heading, with SliverAnimatedExtent reproducing the clipped AnimatedSize for open, close and arriving rows. The first Chat tab visit no longer builds every row (150 chats: worst build frame 116 ms to 19 ms).
This commit is contained in:
@@ -1,11 +1,9 @@
|
||||
import '../../../../ui/layout/collapsible_list_section.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../domain/chat_sessions.dart';
|
||||
import 'chat_adaptive.dart';
|
||||
import 'chat_sessions_body.dart';
|
||||
import 'session_row_memo.dart';
|
||||
import 'session_list_items.dart';
|
||||
import '../../../../ui/adaptive/floating_bar_layout.dart';
|
||||
|
||||
class CupertinoSessionList extends StatelessWidget {
|
||||
@@ -44,79 +42,52 @@ class CupertinoSessionList extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
// Starts below a floating top bar (its height arrives as media top
|
||||
// padding) and ends clear of a floating bottom bar.
|
||||
padding: withFloatingBarClearance(
|
||||
context,
|
||||
EdgeInsets.only(top: MediaQuery.paddingOf(context).top, bottom: 24),
|
||||
),
|
||||
children: [
|
||||
for (final section in sections) ..._section(section),
|
||||
if (emptyMessage != null)
|
||||
ChatCupertinoMessage(
|
||||
message: emptyMessage!,
|
||||
actionLabel: onClearSearch == null ? null : 'Clear search',
|
||||
onAction: onClearSearch,
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverPadding(
|
||||
// Starts below a floating top bar (its height arrives as media top
|
||||
// padding) and ends clear of a floating bottom bar.
|
||||
padding: withFloatingBarClearance(
|
||||
context,
|
||||
EdgeInsets.only(top: MediaQuery.paddingOf(context).top, bottom: 24),
|
||||
),
|
||||
sliver: SliverMainAxisGroup(
|
||||
slivers: [
|
||||
for (final section in sections) _section(section),
|
||||
if (emptyMessage != null)
|
||||
SliverToBoxAdapter(
|
||||
child: ChatCupertinoMessage(
|
||||
message: emptyMessage!,
|
||||
actionLabel: onClearSearch == null ? null : 'Clear search',
|
||||
onAction: onClearSearch,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _section(ChatSessionSection section) {
|
||||
final groups = groupChatSessions(section.sessions);
|
||||
// Closed chats start folded away; the live ones start open.
|
||||
return [
|
||||
CollapsibleListSection(
|
||||
key: ValueKey('chat-section-${section.title}'),
|
||||
title: section.title,
|
||||
count: section.sessions.length,
|
||||
initiallyOpen: section.title != 'Closed',
|
||||
children: [
|
||||
for (final group in groups) ...[
|
||||
if (groups.length > 1)
|
||||
_DirectoryHeader(
|
||||
group.directory.isEmpty ? 'No directory' : group.directory,
|
||||
),
|
||||
for (var i = 0; i < group.sessions.length; i++)
|
||||
..._row(
|
||||
group.sessions[i],
|
||||
divider: i < group.sessions.length - 1,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// The row plus its refusal, the server's words in their own full-width
|
||||
/// row under it.
|
||||
List<Widget> _row(JsonMap session, {required bool divider}) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
final error = errorFor(id);
|
||||
return [
|
||||
memoChatSessionRow(
|
||||
session: session,
|
||||
selected: id == activeSessionId,
|
||||
duplicateTitles: duplicateTitles,
|
||||
unseen: isUnseen(session),
|
||||
// A refusal below the row separates it instead.
|
||||
divider: divider && error == null,
|
||||
onOpen: onOpen,
|
||||
onStar: onStar,
|
||||
onRename: onRename,
|
||||
onClose: onClose,
|
||||
onReopen: onReopen,
|
||||
onHide: onHide,
|
||||
),
|
||||
if (error != null)
|
||||
ChatRowError(
|
||||
message: error,
|
||||
messageKey: Key('chat-row-error-$id'),
|
||||
onDismiss: onDismissError == null ? null : () => onDismissError!(id),
|
||||
),
|
||||
];
|
||||
}
|
||||
Widget _section(ChatSessionSection section) => chatSessionSection(
|
||||
section: section,
|
||||
directoryHeader: _DirectoryHeader.new,
|
||||
row: (session, {required divider}) => chatSessionRowItem(
|
||||
session,
|
||||
divider: divider,
|
||||
activeSessionId: activeSessionId,
|
||||
duplicateTitles: duplicateTitles,
|
||||
isUnseen: isUnseen,
|
||||
onOpen: onOpen,
|
||||
onStar: onStar,
|
||||
onRename: onRename,
|
||||
onClose: onClose,
|
||||
onReopen: onReopen,
|
||||
onHide: onHide,
|
||||
),
|
||||
errorFor: errorFor,
|
||||
onDismissError: onDismissError,
|
||||
);
|
||||
}
|
||||
|
||||
/// A directory's name above its chats, like a grouped table's header.
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../../../ui/layout/collapsible_list_section.dart';
|
||||
import '../../domain/chat_sessions.dart';
|
||||
import 'chat_adaptive.dart';
|
||||
import 'chat_sessions_body.dart';
|
||||
import 'session_row_memo.dart';
|
||||
|
||||
/// One entry of a chat section's lazy list: a directory header, a row or a
|
||||
/// row's refusal.
|
||||
typedef SessionListItem = ({Key key, WidgetBuilder build});
|
||||
|
||||
/// A chat section as a sliver: its heading and its rows, built only when on
|
||||
/// screen. Material and Cupertino supply their own directory header.
|
||||
Widget chatSessionSection({
|
||||
required ChatSessionSection section,
|
||||
required Widget Function(String directory) directoryHeader,
|
||||
required SessionListItem Function(JsonMap session, {required bool divider})
|
||||
row,
|
||||
required String? Function(String sessionId) errorFor,
|
||||
required ValueChanged<String>? onDismissError,
|
||||
}) {
|
||||
final groups = groupChatSessions(section.sessions);
|
||||
final items = <SessionListItem>[
|
||||
for (final group in groups) ...[
|
||||
if (groups.length > 1)
|
||||
(
|
||||
key: ValueKey('chat-dir-${group.directory}'),
|
||||
build: (_) => directoryHeader(
|
||||
group.directory.isEmpty ? 'No directory' : group.directory,
|
||||
),
|
||||
),
|
||||
// Inset dividers between the rows of a group; the group header owns
|
||||
// the boundary between directories.
|
||||
for (var i = 0; i < group.sessions.length; i++)
|
||||
...() {
|
||||
final session = group.sessions[i];
|
||||
final id = '${session['id'] ?? ''}';
|
||||
final error = errorFor(id);
|
||||
return [
|
||||
// A refusal below the row separates it instead.
|
||||
row(
|
||||
session,
|
||||
divider: i < group.sessions.length - 1 && error == null,
|
||||
),
|
||||
// The refusal at full width under its row (a long sentence in a
|
||||
// subtitle made the row taller than the viewport at 320px with
|
||||
// 2x text).
|
||||
if (error != null)
|
||||
(
|
||||
key: ValueKey('chat-error-$id'),
|
||||
build: (_) => ChatRowError(
|
||||
message: error,
|
||||
messageKey: Key('chat-row-error-$id'),
|
||||
onDismiss: onDismissError == null
|
||||
? null
|
||||
: () => onDismissError(id),
|
||||
),
|
||||
),
|
||||
];
|
||||
}(),
|
||||
],
|
||||
];
|
||||
// Closed chats start folded away; the live ones start open.
|
||||
return SliverCollapsibleListSection(
|
||||
key: ValueKey('chat-section-${section.title}'),
|
||||
title: section.title,
|
||||
count: section.sessions.length,
|
||||
initiallyOpen: section.title != 'Closed',
|
||||
itemCount: items.length,
|
||||
itemKey: (index) => items[index].key,
|
||||
itemBuilder: (context, index) => items[index].build(context),
|
||||
);
|
||||
}
|
||||
|
||||
/// A chat row as a list entry, memoised (see [memoChatSessionRow]).
|
||||
SessionListItem chatSessionRowItem(
|
||||
JsonMap session, {
|
||||
required bool divider,
|
||||
required String? activeSessionId,
|
||||
required Set<String> duplicateTitles,
|
||||
required bool Function(JsonMap) isUnseen,
|
||||
required ValueChanged<JsonMap> onOpen,
|
||||
required ValueChanged<JsonMap> onStar,
|
||||
required ValueChanged<JsonMap> onRename,
|
||||
required ValueChanged<JsonMap> onClose,
|
||||
required ValueChanged<JsonMap> onReopen,
|
||||
required ValueChanged<JsonMap> onHide,
|
||||
}) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
return (
|
||||
key: ValueKey('chat-item-$id'),
|
||||
build: (_) => memoChatSessionRow(
|
||||
session: session,
|
||||
selected: id == activeSessionId,
|
||||
duplicateTitles: duplicateTitles,
|
||||
unseen: isUnseen(session),
|
||||
divider: divider,
|
||||
onOpen: onOpen,
|
||||
onStar: onStar,
|
||||
onRename: onRename,
|
||||
onClose: onClose,
|
||||
onReopen: onReopen,
|
||||
onHide: onHide,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,9 @@
|
||||
import '../../../../ui/layout/collapsible_list_section.dart';
|
||||
import '../../../../ui/layout/section_heading.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../domain/chat_sessions.dart';
|
||||
import 'chat_adaptive.dart';
|
||||
import 'chat_sessions_body.dart';
|
||||
import 'session_row_memo.dart';
|
||||
import 'session_list_items.dart';
|
||||
|
||||
class MaterialSessionList extends StatelessWidget {
|
||||
const MaterialSessionList({
|
||||
@@ -44,65 +41,59 @@ class MaterialSessionList extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
children: [
|
||||
for (final section in sections) _section(context, section),
|
||||
if (emptyMessage != null)
|
||||
ListTile(
|
||||
title: Text(emptyMessage!),
|
||||
trailing: onClearSearch == null
|
||||
? null
|
||||
: TextButton(
|
||||
onPressed: onClearSearch,
|
||||
child: const Text('Clear search'),
|
||||
// Clears the media padding above and below (a floating top bar's height
|
||||
// arrives as top padding) and leaves only the side padding to the rows,
|
||||
// as a ListView does.
|
||||
final media = MediaQuery.of(context);
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverPadding(
|
||||
padding: media.padding.copyWith(left: 0, right: 0),
|
||||
sliver: MediaQuery(
|
||||
data: media.copyWith(
|
||||
padding: media.padding.copyWith(top: 0, bottom: 0),
|
||||
),
|
||||
child: SliverMainAxisGroup(
|
||||
slivers: [
|
||||
for (final section in sections) _section(context, section),
|
||||
if (emptyMessage != null)
|
||||
SliverToBoxAdapter(
|
||||
child: ListTile(
|
||||
title: Text(emptyMessage!),
|
||||
trailing: onClearSearch == null
|
||||
? null
|
||||
: TextButton(
|
||||
onPressed: onClearSearch,
|
||||
child: const Text('Clear search'),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _section(BuildContext context, ChatSessionSection section) {
|
||||
final groups = groupChatSessions(section.sessions);
|
||||
final heading = SectionHeadingStyle.of(context);
|
||||
// Closed chats start folded away; the live ones start open.
|
||||
return CollapsibleListSection(
|
||||
key: ValueKey('chat-section-${section.title}'),
|
||||
title: section.title,
|
||||
count: section.sessions.length,
|
||||
initiallyOpen: section.title != 'Closed',
|
||||
children: [
|
||||
for (final group in groups) ...[
|
||||
if (groups.length > 1)
|
||||
ListTile(
|
||||
dense: true,
|
||||
leading: const Icon(Icons.folder_outlined),
|
||||
title: Text(
|
||||
group.directory.isEmpty ? 'No directory' : group.directory,
|
||||
style: heading.title.copyWith(fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
// Inset dividers between the rows of a group; the group header
|
||||
// owns the boundary between directories.
|
||||
for (var i = 0; i < group.sessions.length; i++)
|
||||
..._row(group.sessions[i], divider: i < group.sessions.length - 1),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// The row plus its refusal at full width (a long sentence in a subtitle
|
||||
/// made the row taller than the viewport at 320px with 2x text).
|
||||
List<Widget> _row(JsonMap session, {required bool divider}) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
final error = errorFor(id);
|
||||
return [
|
||||
memoChatSessionRow(
|
||||
session: session,
|
||||
selected: id == activeSessionId,
|
||||
return chatSessionSection(
|
||||
section: section,
|
||||
directoryHeader: (directory) => ListTile(
|
||||
dense: true,
|
||||
leading: const Icon(Icons.folder_outlined),
|
||||
title: Text(
|
||||
directory,
|
||||
style: heading.title.copyWith(fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
row: (session, {required divider}) => chatSessionRowItem(
|
||||
session,
|
||||
divider: divider,
|
||||
activeSessionId: activeSessionId,
|
||||
duplicateTitles: duplicateTitles,
|
||||
unseen: isUnseen(session),
|
||||
// A refusal below the row separates it instead.
|
||||
divider: divider && error == null,
|
||||
isUnseen: isUnseen,
|
||||
onOpen: onOpen,
|
||||
onStar: onStar,
|
||||
onRename: onRename,
|
||||
@@ -110,12 +101,8 @@ class MaterialSessionList extends StatelessWidget {
|
||||
onReopen: onReopen,
|
||||
onHide: onHide,
|
||||
),
|
||||
if (error != null)
|
||||
ChatRowError(
|
||||
message: error,
|
||||
messageKey: Key('chat-row-error-$id'),
|
||||
onDismiss: onDismissError == null ? null : () => onDismissError!(id),
|
||||
),
|
||||
];
|
||||
errorFor: errorFor,
|
||||
onDismissError: onDismissError,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,14 +4,22 @@ import 'package:flutter/material.dart';
|
||||
import '../adaptive/host.dart';
|
||||
import '../motion/motion.dart';
|
||||
import 'section_heading.dart';
|
||||
import 'sliver_animated_extent.dart';
|
||||
|
||||
/// A titled group in a list: a [SectionHeading] strip (bold title, count,
|
||||
/// chevron) that reads as a divider, and opens or closes its rows on a tap.
|
||||
class CollapsibleListSection extends StatefulWidget {
|
||||
const CollapsibleListSection({
|
||||
/// A titled group in a [CustomScrollView]: a [SectionHeading] strip (bold
|
||||
/// title, count, chevron) that reads as a divider, and opens or closes its
|
||||
/// rows on a tap.
|
||||
///
|
||||
/// The rows are a lazy sliver list: only the visible ones are built, however
|
||||
/// many there are. The section grows and shrinks like a clipped, top-aligned
|
||||
/// `AnimatedSize` when it opens or closes and when rows arrive or leave.
|
||||
class SliverCollapsibleListSection extends StatefulWidget {
|
||||
const SliverCollapsibleListSection({
|
||||
super.key,
|
||||
required this.title,
|
||||
required this.children,
|
||||
required this.itemCount,
|
||||
required this.itemBuilder,
|
||||
this.itemKey,
|
||||
this.count,
|
||||
this.initiallyOpen = true,
|
||||
});
|
||||
@@ -19,22 +27,70 @@ class CollapsibleListSection extends StatefulWidget {
|
||||
final String title;
|
||||
final int? count;
|
||||
final bool initiallyOpen;
|
||||
final List<Widget> children;
|
||||
final int itemCount;
|
||||
final IndexedWidgetBuilder itemBuilder;
|
||||
|
||||
/// The key of the item at an index, so a row keeps its element when rows
|
||||
/// before it arrive or leave.
|
||||
final Key Function(int index)? itemKey;
|
||||
|
||||
@override
|
||||
State<CollapsibleListSection> createState() => _CollapsibleListSectionState();
|
||||
State<SliverCollapsibleListSection> createState() =>
|
||||
_SliverCollapsibleListSectionState();
|
||||
}
|
||||
|
||||
class _CollapsibleListSectionState extends State<CollapsibleListSection> {
|
||||
class _SliverCollapsibleListSectionState
|
||||
extends State<SliverCollapsibleListSection> {
|
||||
late bool _open = widget.initiallyOpen;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final duration = Motion.of(context, Motion.standard);
|
||||
return SliverMainAxisGroup(
|
||||
slivers: [
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: _heading(context),
|
||||
),
|
||||
),
|
||||
SliverAnimatedExtent(
|
||||
duration: duration,
|
||||
curve: Motion.curve,
|
||||
changeToken: (_open, widget.itemCount),
|
||||
sliver: _open ? _rows() : const SliverToBoxAdapter(),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _rows() {
|
||||
final itemKey = widget.itemKey;
|
||||
Map<Key, int>? indexOf;
|
||||
return SliverList(
|
||||
delegate: SliverChildBuilderDelegate(
|
||||
(context, index) => itemKey == null
|
||||
? widget.itemBuilder(context, index)
|
||||
: KeyedSubtree(
|
||||
key: itemKey(index),
|
||||
child: widget.itemBuilder(context, index),
|
||||
),
|
||||
childCount: widget.itemCount,
|
||||
findChildIndexCallback: itemKey == null
|
||||
? null
|
||||
: (key) => (indexOf ??= {
|
||||
for (var i = 0; i < widget.itemCount; i++) itemKey(i): i,
|
||||
})[key],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _heading(BuildContext context) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final muted = cupertino
|
||||
? CupertinoColors.secondaryLabel.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.onSurfaceVariant;
|
||||
final heading = Semantics(
|
||||
return Semantics(
|
||||
container: true,
|
||||
header: true,
|
||||
button: true,
|
||||
@@ -73,31 +129,6 @@ class _CollapsibleListSectionState extends State<CollapsibleListSection> {
|
||||
),
|
||||
),
|
||||
);
|
||||
final rows = _open
|
||||
? Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: widget.children,
|
||||
)
|
||||
: const SizedBox(width: double.infinity);
|
||||
final duration = Motion.of(context, Motion.standard);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(padding: const EdgeInsets.only(top: 8), child: heading),
|
||||
ClipRect(
|
||||
// A zero-duration AnimatedSize can notify during its own layout when
|
||||
// rows arrive asynchronously. Reduced motion should skip it entirely.
|
||||
child: duration == Duration.zero
|
||||
? rows
|
||||
: AnimatedSize(
|
||||
duration: duration,
|
||||
curve: Motion.curve,
|
||||
alignment: Alignment.topCenter,
|
||||
child: rows,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
void _toggle() => setState(() => _open = !_open);
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' show lerpDouble;
|
||||
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// The sliver counterpart of a clipped, top-aligned `AnimatedSize`: when
|
||||
/// [changeToken] changes, the sliver's extent moves from what it showed to
|
||||
/// its child's new extent over [duration]. The child is laid out (and drawn)
|
||||
/// at its new extent at once and clipped to the moving one, so a closing
|
||||
/// section (an empty child) leaves blank space that shrinks away. The child
|
||||
/// stays lazy: only its visible part is built.
|
||||
///
|
||||
/// The token, rather than every change of the child's extent, starts the
|
||||
/// animation: a lazy list's extent is an estimate that moves while it
|
||||
/// scrolls, and that must not animate.
|
||||
class SliverAnimatedExtent extends StatefulWidget {
|
||||
const SliverAnimatedExtent({
|
||||
super.key,
|
||||
required this.duration,
|
||||
required this.curve,
|
||||
required this.changeToken,
|
||||
required this.sliver,
|
||||
});
|
||||
|
||||
final Duration duration;
|
||||
final Curve curve;
|
||||
final Object? changeToken;
|
||||
final Widget sliver;
|
||||
|
||||
@override
|
||||
State<SliverAnimatedExtent> createState() => _SliverAnimatedExtentState();
|
||||
}
|
||||
|
||||
class _SliverAnimatedExtentState extends State<SliverAnimatedExtent>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _controller = AnimationController(
|
||||
vsync: this,
|
||||
duration: widget.duration,
|
||||
value: 1,
|
||||
);
|
||||
int _generation = 0;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(SliverAnimatedExtent oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
_controller.duration = widget.duration;
|
||||
if (widget.changeToken == oldWidget.changeToken) return;
|
||||
if (widget.duration == Duration.zero) {
|
||||
_controller.value = 1;
|
||||
return;
|
||||
}
|
||||
_generation++;
|
||||
_controller.forward(from: 0);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AnimatedBuilder(
|
||||
animation: _controller,
|
||||
builder: (context, sliver) => _SliverExtentLerp(
|
||||
generation: _generation,
|
||||
progress: _controller.isCompleted
|
||||
? 1
|
||||
: widget.curve.transform(_controller.value),
|
||||
sliver: sliver,
|
||||
),
|
||||
child: widget.sliver,
|
||||
);
|
||||
}
|
||||
|
||||
class _SliverExtentLerp extends SingleChildRenderObjectWidget {
|
||||
const _SliverExtentLerp({
|
||||
required this.generation,
|
||||
required this.progress,
|
||||
Widget? sliver,
|
||||
}) : super(child: sliver);
|
||||
|
||||
final int generation;
|
||||
final double progress;
|
||||
|
||||
@override
|
||||
RenderObject createRenderObject(BuildContext context) =>
|
||||
_RenderSliverExtentLerp(generation, progress);
|
||||
|
||||
@override
|
||||
void updateRenderObject(
|
||||
BuildContext context,
|
||||
_RenderSliverExtentLerp renderObject,
|
||||
) => renderObject
|
||||
..generation = generation
|
||||
..progress = progress;
|
||||
}
|
||||
|
||||
/// Reports an extent between the one it last reported when [generation]
|
||||
/// changed and its child's extent, by [progress], clipping the child to it.
|
||||
class _RenderSliverExtentLerp extends RenderProxySliver {
|
||||
_RenderSliverExtentLerp(this._generation, this._progress);
|
||||
|
||||
int _generation;
|
||||
set generation(int value) {
|
||||
if (value == _generation) return;
|
||||
_generation = value;
|
||||
_from = _shown;
|
||||
markNeedsLayout();
|
||||
}
|
||||
|
||||
double _progress;
|
||||
set progress(double value) {
|
||||
if (value == _progress) return;
|
||||
_progress = value;
|
||||
markNeedsLayout();
|
||||
}
|
||||
|
||||
/// The extent reported by the last layout, and where the current
|
||||
/// animation started.
|
||||
double _shown = 0;
|
||||
double _from = 0;
|
||||
bool _clipped = false;
|
||||
|
||||
@override
|
||||
void performLayout() {
|
||||
final child = this.child!;
|
||||
child.layout(constraints, parentUsesSize: true);
|
||||
final full = child.geometry!;
|
||||
_clipped = false;
|
||||
if (_progress >= 1 || full.scrollOffsetCorrection != null) {
|
||||
geometry = full;
|
||||
_shown = full.scrollExtent;
|
||||
return;
|
||||
}
|
||||
final extent = math.max(
|
||||
0.0,
|
||||
lerpDouble(_from, full.scrollExtent, _progress)!,
|
||||
);
|
||||
_shown = extent;
|
||||
_clipped = extent < full.scrollExtent;
|
||||
final paintExtent = calculatePaintOffset(constraints, from: 0, to: extent);
|
||||
geometry = SliverGeometry(
|
||||
scrollExtent: extent,
|
||||
paintExtent: paintExtent,
|
||||
layoutExtent: paintExtent,
|
||||
maxPaintExtent: extent,
|
||||
cacheExtent: calculateCacheOffset(constraints, from: 0, to: extent),
|
||||
hasVisualOverflow: _clipped || full.hasVisualOverflow,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool hitTestChildren(
|
||||
SliverHitTestResult result, {
|
||||
required double mainAxisPosition,
|
||||
required double crossAxisPosition,
|
||||
}) {
|
||||
if (mainAxisPosition >= geometry!.paintExtent) return false;
|
||||
return super.hitTestChildren(
|
||||
result,
|
||||
mainAxisPosition: mainAxisPosition,
|
||||
crossAxisPosition: crossAxisPosition,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void paint(PaintingContext context, Offset offset) {
|
||||
if (child == null || geometry!.paintExtent <= 0) return;
|
||||
if (!_clipped) {
|
||||
_clip.layer = null;
|
||||
return super.paint(context, offset);
|
||||
}
|
||||
final extent = geometry!.paintExtent;
|
||||
final cross = constraints.crossAxisExtent;
|
||||
final clip = switch (constraints.axis) {
|
||||
Axis.vertical => Rect.fromLTWH(0, 0, cross, extent),
|
||||
Axis.horizontal => Rect.fromLTWH(0, 0, extent, cross),
|
||||
};
|
||||
_clip.layer = context.pushClipRect(
|
||||
needsCompositing,
|
||||
offset,
|
||||
clip,
|
||||
super.paint,
|
||||
oldLayer: _clip.layer,
|
||||
);
|
||||
}
|
||||
|
||||
final _clip = LayerHandle<ClipRectLayer>();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_clip.layer = null;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
# Performance round 4: lazy chat sessions list
|
||||
|
||||
Round 3's top candidate (`notes/perf-round3.md`): the first visit to the Chat
|
||||
tab built every row of an open section at once, about 0.75 ms per chat.
|
||||
|
||||
## Change
|
||||
|
||||
- `SliverCollapsibleListSection` (`lib/ui/layout/collapsible_list_section.dart`)
|
||||
replaces the box `CollapsibleListSection`, which only the chat list used:
|
||||
the same heading, then a lazy `SliverList` of the section's entries
|
||||
(directory headers, rows, row refusals). Entries are keyed, with a
|
||||
`findChildIndexCallback`, so rows keep their elements when rows before them
|
||||
arrive or leave. Rows are still the round-2 memo (`session_row_memo.dart`).
|
||||
- `SliverAnimatedExtent` (`lib/ui/layout/sliver_animated_extent.dart`) is the
|
||||
sliver form of the clipped, top-aligned `AnimatedSize` that the section
|
||||
used: on open, close or a change of row count it moves the reported extent
|
||||
from what it showed to the child's new extent (`Motion.standard`,
|
||||
`Motion.curve`), drawing the child at once and clipping it. Closing leaves
|
||||
blank space that shrinks, as before. Reduced motion snaps. `SliverReveal`
|
||||
did not fit: it scales the child's extent by a factor (so closing would show
|
||||
the rows shrinking, and arriving rows would not animate).
|
||||
- `MaterialSessionList` and `CupertinoSessionList` are `CustomScrollView`s.
|
||||
Material reproduces `ListView`'s media-padding handling (vertical padding on
|
||||
the scroll view, side padding left to the rows); Cupertino keeps its explicit
|
||||
floating-bar padding. Shared entry building: `session_list_items.dart`.
|
||||
|
||||
Not animated any more: a row whose own height changes without the row count
|
||||
changing (for example a longer subtitle) now snaps instead of animating the
|
||||
section's height. Row counts, refusals (separate entries), open and close
|
||||
still animate.
|
||||
|
||||
## Measurements (release, `tool/perf/interaction_bench.mjs`, medians of 5, two alternating rounds)
|
||||
|
||||
| scenario | metric | main 2f6d967f | branch |
|
||||
| --- | --- | --- | --- |
|
||||
| Chat tab first visit, 30 chats | build max (ms) | 31.5 / 31.6 | 23.1 / 23.0 |
|
||||
| | build sum | 73.5 / 75.1 | 63.4 / 54.5 |
|
||||
| | longest frame | 59.3 / 59.2 | 51.4 / 48.4 |
|
||||
| Chat tab first visit, 150 chats | build max | 117.3 / 114.0 | 18.9 / 18.4 |
|
||||
| | build sum | 185 / 180 | 54 / 56 |
|
||||
| | longest frame | 127 / 140 | 45.2 / 45.8 |
|
||||
| Chat list to open chat (control) | build max | 20.3 / 18.1 | 20.3 / 22.9 |
|
||||
|
||||
The cost no longer scales with the number of chats. `test/perf/list_and_gallery_bench_test.dart`
|
||||
(200 chats): rows built 200 to 12; total rebuilds over 50 running-state
|
||||
changes 18850 to 9900.
|
||||
|
||||
## Visual check
|
||||
|
||||
`tool/capture` over both release builds, `?chats=30`, Material and Cupertino,
|
||||
light and dark, 560x1000: top, scrolled 600 px, bottom, section closed and
|
||||
reopened (20 pairs), plus the bench's settled shots at 30 and 150 chats and the
|
||||
empty state. All byte-identical except the Cupertino scrolled pair, where
|
||||
14 pixels at the ends of the transient scrollbar thumb differ: a lazy list
|
||||
estimates its total extent until every row has been laid out (at the bottom
|
||||
the shots are identical).
|
||||
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/ui/adaptive/segmented_bar.dart';
|
||||
import 'package:pipelines_app/ui/layout/section_heading.dart';
|
||||
|
||||
import 'chat_test_harness.dart';
|
||||
import 'fake_chat_gateway.dart';
|
||||
@@ -30,12 +31,15 @@ void main() {
|
||||
}
|
||||
|
||||
final bar = tester.getRect(find.byType(SegmentedBar));
|
||||
final list = tester.getRect(find.byType(ListView).first);
|
||||
final list = tester.getRect(find.byType(CustomScrollView).first);
|
||||
// The list reaches under the bar ...
|
||||
expect(list.top, lessThan(bar.bottom));
|
||||
// ... yet at rest its first row is clear of it.
|
||||
final first = tester.getRect(
|
||||
find.byKey(const ValueKey('chat-section-Chats')),
|
||||
find.descendant(
|
||||
of: find.byKey(const ValueKey('chat-section-Chats')),
|
||||
matching: find.byType(SectionHeading),
|
||||
),
|
||||
);
|
||||
expect(first.top, greaterThanOrEqualTo(bar.bottom));
|
||||
expect(tester.takeException(), isNull);
|
||||
|
||||
@@ -111,8 +111,11 @@ void main() {
|
||||
'rowRebuilds=${rebuilds.of(ChatSessionRow)} '
|
||||
'totalRebuilds=${rebuilds.total}',
|
||||
);
|
||||
// One row per change, not all 200 (10,000 row rebuilds before).
|
||||
expect(rebuilds.of(ChatSessionRow), 50);
|
||||
// Only the rows on screen are built (the list is lazy) ...
|
||||
expect(built, lessThan(40));
|
||||
// ... and at most the changed row rebuilds per change, not all 200
|
||||
// (10,000 row rebuilds before); a change to an offscreen row builds none.
|
||||
expect(rebuilds.of(ChatSessionRow), inInclusiveRange(1, 50));
|
||||
});
|
||||
|
||||
testWidgets('gallery: open a visit with 500 artifacts', (tester) async {
|
||||
|
||||
@@ -3,6 +3,26 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/ui/layout/collapsible_list_section.dart';
|
||||
|
||||
Widget _app(bool cupertino, Widget body) => cupertino
|
||||
? CupertinoApp(home: CupertinoPageScaffold(child: body))
|
||||
: MaterialApp(home: Scaffold(body: body));
|
||||
|
||||
Widget _list(ValueNotifier<int> rows) => ValueListenableBuilder<int>(
|
||||
valueListenable: rows,
|
||||
builder: (context, count, _) => CustomScrollView(
|
||||
slivers: [
|
||||
SliverCollapsibleListSection(
|
||||
title: 'Group',
|
||||
count: count,
|
||||
itemCount: count,
|
||||
itemKey: (i) => ValueKey(i),
|
||||
itemBuilder: (_, i) => SizedBox(height: 40, child: Text('Row $i')),
|
||||
),
|
||||
const SliverToBoxAdapter(child: Text('After')),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
void main() {
|
||||
for (final cupertino in [false, true]) {
|
||||
testWidgets(
|
||||
@@ -15,32 +35,64 @@ void main() {
|
||||
);
|
||||
final rows = ValueNotifier<int>(1);
|
||||
addTearDown(rows.dispose);
|
||||
final body = ValueListenableBuilder<int>(
|
||||
valueListenable: rows,
|
||||
builder: (context, count, _) => SingleChildScrollView(
|
||||
child: CollapsibleListSection(
|
||||
title: 'Group',
|
||||
count: count,
|
||||
children: [for (var i = 0; i < count; i++) Text('Row $i')],
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
cupertino
|
||||
? CupertinoApp(home: CupertinoPageScaffold(child: body))
|
||||
: MaterialApp(home: Scaffold(body: body)),
|
||||
);
|
||||
await tester.pumpWidget(_app(cupertino, _list(rows)));
|
||||
await tester.pumpAndSettle();
|
||||
rows.value = 3;
|
||||
await tester.pumpAndSettle();
|
||||
await tester.pump();
|
||||
expect(find.text('Row 2'), findsOneWidget);
|
||||
expect(find.byType(AnimatedSize), findsNothing);
|
||||
expect(tester.hasRunningAnimations, isFalse);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.tap(find.text('Group'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.pump();
|
||||
expect(find.text('Row 0'), findsNothing);
|
||||
expect(tester.takeException(), isNull);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('arriving rows, opening and closing animate the height', (
|
||||
tester,
|
||||
) async {
|
||||
final rows = ValueNotifier<int>(2);
|
||||
addTearDown(rows.dispose);
|
||||
await tester.pumpWidget(_app(false, _list(rows)));
|
||||
double after() => tester.getTopLeft(find.text('After')).dy;
|
||||
final top = after() - 80;
|
||||
|
||||
// Rows arriving: what follows moves down over the animation.
|
||||
rows.value = 4;
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
expect(after(), inExclusiveRange(top + 80, top + 160));
|
||||
await tester.pumpAndSettle();
|
||||
expect(after(), top + 160);
|
||||
|
||||
// Closing: the rows go at once and the space shrinks away.
|
||||
await tester.tap(find.text('Group'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
expect(find.text('Row 0'), findsNothing);
|
||||
expect(after(), inExclusiveRange(top, top + 160));
|
||||
await tester.pumpAndSettle();
|
||||
expect(after(), top);
|
||||
|
||||
// Opening: the rows are drawn at once and revealed from the top.
|
||||
await tester.tap(find.text('Group'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
expect(find.text('Row 0'), findsOneWidget);
|
||||
expect(after(), inExclusiveRange(top, top + 160));
|
||||
await tester.pumpAndSettle();
|
||||
expect(after(), top + 160);
|
||||
});
|
||||
|
||||
testWidgets('only the visible rows of a long section are built', (
|
||||
tester,
|
||||
) async {
|
||||
final rows = ValueNotifier<int>(500);
|
||||
addTearDown(rows.dispose);
|
||||
await tester.pumpWidget(_app(false, _list(rows)));
|
||||
expect(find.text('Row 0'), findsOneWidget);
|
||||
expect(find.text('Row 100'), findsNothing);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user