Merge main

This commit is contained in:
2026-11-02 00:36:49 +00:00
33 changed files with 2239 additions and 378 deletions
@@ -0,0 +1,78 @@
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
/// An image's bytes decoded no larger than needed to cover a box of
/// [width] x [height] device pixels (as `BoxFit.cover` shows it), keeping the
/// image's aspect ratio and never upscaling. A gallery of full-size pictures
/// then holds thumbnails, not originals, in memory.
@immutable
class CoverSizedMemoryImage extends ImageProvider<CoverSizedMemoryImage> {
const CoverSizedMemoryImage(
this.bytes, {
required this.width,
required this.height,
});
final Uint8List bytes;
final int width;
final int height;
@override
Future<CoverSizedMemoryImage> obtainKey(ImageConfiguration configuration) =>
SynchronousFuture<CoverSizedMemoryImage>(this);
@override
ImageStreamCompleter loadImage(
CoverSizedMemoryImage key,
ImageDecoderCallback decode,
) => MultiFrameImageStreamCompleter(
codec: _decode(key, decode),
scale: 1,
debugLabel: 'CoverSizedMemoryImage(${describeIdentity(key.bytes)})',
);
static Future<ui.Codec> _decode(
CoverSizedMemoryImage key,
ImageDecoderCallback decode,
) async {
final buffer = await ui.ImmutableBuffer.fromUint8List(key.bytes);
return decode(
buffer,
getTargetSize: (intrinsicWidth, intrinsicHeight) => coverTargetSize(
intrinsicWidth,
intrinsicHeight,
width: key.width,
height: key.height,
),
);
}
@override
bool operator ==(Object other) =>
other is CoverSizedMemoryImage &&
identical(other.bytes, bytes) &&
other.width == width &&
other.height == height;
@override
int get hashCode => Object.hash(identityHashCode(bytes), width, height);
}
/// The decode size that still covers a [width] x [height] box: the picture's
/// aspect ratio scaled down until its shorter side fits, never scaled up.
ui.TargetImageSize coverTargetSize(
int intrinsicWidth,
int intrinsicHeight, {
required int width,
required int height,
}) {
final scale = math.max(width / intrinsicWidth, height / intrinsicHeight);
if (scale >= 1) return const ui.TargetImageSize();
return ui.TargetImageSize(
width: math.max(1, (intrinsicWidth * scale).ceil()),
height: math.max(1, (intrinsicHeight * scale).ceil()),
);
}
@@ -7,6 +7,7 @@ import '../domain/artifact_kind.dart';
import '../domain/artifact_record.dart';
import '../domain/artifact_url.dart';
import 'artifact_row_labels.dart';
import 'artifact_thumbnail_image.dart';
import 'artifact_viewer_fetch.dart';
/// One artifact in the gallery grid: a thumbnail for an image, otherwise an
@@ -139,9 +140,15 @@ class ArtifactThumbnail extends StatefulWidget {
State<ArtifactThumbnail> createState() => _ArtifactThumbnailState();
}
class _ArtifactThumbnailState extends State<ArtifactThumbnail> {
class _ArtifactThumbnailState extends State<ArtifactThumbnail>
with AutomaticKeepAliveClientMixin {
Future<ArtifactFetchResult>? _image;
/// A loaded picture stays alive when a lazy gallery scrolls it away, so
/// scrolling back does not fetch it again.
@override
bool get wantKeepAlive => _image != null;
@override
void initState() {
super.initState();
@@ -160,6 +167,7 @@ class _ArtifactThumbnailState extends State<ArtifactThumbnail> {
@override
Widget build(BuildContext context) {
super.build(context);
final cupertino = usesCupertinoHost(context);
final icon = Icon(
artifactKindIcon(widget.artifact, cupertino: cupertino),
@@ -176,11 +184,25 @@ class _ArtifactThumbnailState extends State<ArtifactThumbnail> {
if (result == null || !result.ok || result.bytes.isEmpty) {
return Center(child: icon);
}
return Image.memory(
result.bytes,
fit: BoxFit.cover,
gaplessPlayback: true,
errorBuilder: (_, _, _) => Center(child: icon),
return LayoutBuilder(
builder: (context, constraints) {
final ratio = MediaQuery.devicePixelRatioOf(context);
// Decoded at the size shown, not the picture's full size.
final sized =
constraints.hasBoundedWidth && constraints.hasBoundedHeight
? CoverSizedMemoryImage(
result.bytes,
width: (constraints.maxWidth * ratio).ceil(),
height: (constraints.maxHeight * ratio).ceil(),
)
: null;
return Image(
image: sized ?? MemoryImage(result.bytes),
fit: BoxFit.cover,
gaplessPlayback: true,
errorBuilder: (_, _, _) => Center(child: icon),
);
},
);
},
);
@@ -1,3 +1,5 @@
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
@@ -143,19 +145,25 @@ class _ArtifactVisitListState extends State<ArtifactVisitList> {
key: key,
title: artifactGroupLabel(group),
count: group.artifacts.length,
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Lazy: a visit with hundreds of artifacts builds and lays out
// only the rows on screen.
body: SliverMainAxisGroup(
slivers: [
if (group.artifacts.isNotEmpty)
_mode == ArtifactGalleryMode.grid
? _grid(group)
: _list(group),
if (widget.showTurnDocuments && group.documents.isNotEmpty)
ArtifactDocumentSection(
group: group,
selectedIdentity: widget.selectedIdentity,
onSelected: widget.onSelected,
showHeader: false,
SliverToBoxAdapter(
child: _inkSurface(
context,
ArtifactDocumentSection(
group: group,
selectedIdentity: widget.selectedIdentity,
onSelected: widget.onSelected,
showHeader: false,
),
),
),
],
),
@@ -194,7 +202,7 @@ class _ArtifactVisitListState extends State<ArtifactVisitList> {
child: Text('$count'),
),
],
body: body,
sliverBody: body,
);
Widget _modeSwitch(BuildContext context) {
@@ -241,70 +249,89 @@ class _ArtifactVisitListState extends State<ArtifactVisitList> {
);
}
/// Rows keep a Material surface for their ink, as the section body's own
/// surface was when it was one box around every row.
Widget _inkSurface(BuildContext context, Widget child) =>
usesCupertinoHost(context)
? child
: Material(type: MaterialType.transparency, child: child);
/// The list view: one row per artifact with a small thumbnail beside it.
Widget _list(ArtifactGroup group) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var index = 0; index < group.artifacts.length; index += 1)
Widget _list(ArtifactGroup group) => SliverList.builder(
itemCount: group.artifacts.length,
itemBuilder: (context, index) {
final artifact = group.artifacts[index];
final identity = artifactVisitIdentity(group, artifact);
return _inkSurface(
context,
ArtifactRecordRow(
key: ValueKey<String>(
'${artifactVisitIdentity(group, group.artifacts[index])}'
'\u0000$index',
),
key: ValueKey<String>('$identity\u0000$index'),
group: group,
artifact: group.artifacts[index],
selected:
widget.selectedIdentity ==
artifactVisitIdentity(group, group.artifacts[index]),
artifact: artifact,
selected: widget.selectedIdentity == identity,
onSelected: widget.onSelected,
leading: ClipRRect(
borderRadius: BorderRadius.circular(6),
child: SizedBox.square(
dimension: 44,
child: ArtifactThumbnail(
artifact: group.artifacts[index],
artifact: artifact,
configuredEndpoint: widget.configuredEndpoint,
fetch: widget.fetch,
),
),
),
),
],
);
},
);
/// A group's artifacts as a grid: two tiles across on a phone, more as the
/// pane widens.
Widget _grid(ArtifactGroup group) => LayoutBuilder(
/// pane widens. Each line of tiles is one lazy item, top-aligned like the
/// runs of a wrap.
Widget _grid(ArtifactGroup group) => SliverLayoutBuilder(
builder: (context, constraints) {
const gap = 12.0;
final width = constraints.maxWidth - 32;
final width = constraints.crossAxisExtent - 32;
final columns = (width / 170).floor().clamp(2, 6);
final tile = (width - gap * (columns - 1)) / columns;
return Padding(
final artifacts = group.artifacts;
return SliverPadding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
child: Wrap(
spacing: gap,
runSpacing: gap,
children: [
for (var index = 0; index < group.artifacts.length; index += 1)
SizedBox(
width: tile,
child: ArtifactTile(
key: ValueKey<String>(
'${artifactVisitIdentity(group, group.artifacts[index])}'
'\u0000$index',
),
group: group,
artifact: group.artifacts[index],
selected:
widget.selectedIdentity ==
artifactVisitIdentity(group, group.artifacts[index]),
configuredEndpoint: widget.configuredEndpoint,
fetch: widget.fetch,
onSelected: widget.onSelected,
),
sliver: SliverList.builder(
itemCount: (artifacts.length + columns - 1) ~/ columns,
itemBuilder: (context, line) {
final first = line * columns;
final end = math.min(first + columns, artifacts.length);
return Padding(
padding: EdgeInsets.only(top: line == 0 ? 0 : gap),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (var index = first; index < end; index += 1) ...[
if (index > first) const SizedBox(width: gap),
SizedBox(
width: tile,
child: ArtifactTile(
key: ValueKey<String>(
'${artifactVisitIdentity(group, artifacts[index])}'
'\u0000$index',
),
group: group,
artifact: artifacts[index],
selected:
widget.selectedIdentity ==
artifactVisitIdentity(group, artifacts[index]),
configuredEndpoint: widget.configuredEndpoint,
fetch: widget.fetch,
onSelected: widget.onSelected,
),
),
],
],
),
],
);
},
),
);
},
@@ -0,0 +1,74 @@
import 'package:flutter/widgets.dart';
/// Reuses a built widget while the content and inputs it was built from are
/// unchanged: one per transcript row, or per piece of conversation chrome.
///
/// Every streamed delta rebuilds the conversation, and each build makes a new
/// message widget for every row. Handing Flutter the identical widget instance
/// for an unchanged row lets it skip that row's whole subtree, so during
/// streaming only the live turn rebuilds. Inherited changes (theme, platform
/// style, text scale) still reach the reused subtree through its own
/// dependencies.
class ChatRowWidgets {
final Map<String, ({Object? row, Object? inputs, Widget widget})> _held = {};
Set<String> _seen = {};
/// The widget held for [key] when [row] and [inputs] deep-equal the ones it
/// was built from, else a fresh [build] that is held instead.
///
/// [row] is decoded JSON (maps, lists and scalars); [inputs] are the other
/// values the row's widget depends on, compared the same way.
Widget widgetFor(
String key,
Object? row,
Object? inputs,
Widget Function() build,
) {
_seen.add(key);
final held = _held[key];
if (held != null &&
chatJsonEquals(held.row, row) &&
chatJsonEquals(held.inputs, inputs)) {
return held.widget;
}
final widget = build();
_held[key] = (row: row, inputs: inputs, widget: widget);
return widget;
}
/// Drops rows the last build did not ask for. Call once after each build.
void prune() {
_held.removeWhere((key, _) => !_seen.contains(key));
_seen = {};
}
void clear() {
_held.clear();
_seen = {};
}
}
/// Structural equality for decoded JSON. Strings shared between snapshots are
/// identical, so an unchanged transcript compares in near-constant time per
/// field.
bool chatJsonEquals(Object? a, Object? b) {
if (identical(a, b)) return true;
if (a is Map && b is Map) {
if (a.length != b.length) return false;
for (final entry in a.entries) {
if (!b.containsKey(entry.key) ||
!chatJsonEquals(entry.value, b[entry.key])) {
return false;
}
}
return true;
}
if (a is List && b is List) {
if (a.length != b.length) return false;
for (var index = 0; index < a.length; index++) {
if (!chatJsonEquals(a[index], b[index])) return false;
}
return true;
}
return a == b;
}
@@ -26,6 +26,7 @@ import 'chat_mode_control.dart';
import 'chat_model_control.dart';
import 'chat_models.dart';
import 'chat_row_keys.dart';
import 'chat_row_widgets.dart';
import 'chat_scroll.dart';
import 'chat_server_queue.dart';
import 'chat_thread_controller.dart';
@@ -136,6 +137,11 @@ class _ChatThreadViewState extends State<ChatThreadView> {
late ChatThreadController _controller = _attach();
late ChatComposerController _composer = _attachComposer();
late ChatRowKeys _rowKeys = ChatRowKeys();
final _rowWidgets = ChatRowWidgets();
/// The floating bar and composer, reused while their inputs hold so a
/// streamed delta does not rebuild the conversation's chrome.
final _chrome = ChatRowWidgets();
/// Sent images' bytes for this server, cached across rebuilds and scrolling.
late ChatAttachmentImages _images = ChatAttachmentImages(widget.gateway);
@@ -402,6 +408,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_controller = _attach();
_composer = _attachComposer();
_rowKeys = ChatRowKeys();
_rowWidgets.clear();
_chrome.clear();
_dismissals = ChatNoticeDismissals();
_reconnecting = false;
_adoptCachedTranscript();
@@ -757,8 +765,13 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// The transcript fills the page; the conversation's bar floats over its
// top and the frosted composer over its bottom, and history scrolls
// behind both.
final column = FloatingBarOverlay(
bar: ChatComposerBar(
// Every input of the composer comes from this widget's configuration,
// the composer, the images and the running state.
final composerBar = _chrome.widgetFor(
'composer',
_controller.running,
[widget, _composer, _images],
() => ChatComposerBar(
key: ValueKey<String>('chat-composer-${widget.sessionId}'),
composer: _composer,
running: _controller.running,
@@ -775,6 +788,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
syncToken: widget.syncToken,
),
),
);
final column = FloatingBarOverlay(
bar: composerBar,
child: SegmentedBarOverlay(
bar: _header(context, inShellBar),
child: NotificationListener<ScrollMetricsNotification>(
@@ -787,6 +803,24 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// window; the margins beside it still scroll the list.
final side = chatReadingInset(constraints.maxWidth);
final media = MediaQuery.paddingOf(context);
final transcript = [
for (var index = 0; index < rows.length; index++)
Padding(
key: ValueKey<String>(keys[index]),
padding: const EdgeInsets.symmetric(horizontal: 16),
child: _transcriptRow(
rows[index],
keys[index],
onDismissCompaction:
compactionNotice != null &&
chatNoticeActivityCondition(rows[index]) ==
compactionNotice.condition
? () => _dismiss(compactionNotice)
: null,
),
),
];
_rowWidgets.prune();
return Stack(
children: [
// At rest the first item starts below the floating bar
@@ -861,24 +895,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
padding: EdgeInsets.all(16),
child: Text('No messages in this chat yet.'),
),
for (var index = 0; index < rows.length; index++)
Padding(
key: ValueKey<String>(keys[index]),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: _transcriptRow(
rows[index],
onDismissCompaction:
compactionNotice != null &&
chatNoticeActivityCondition(
rows[index],
) ==
compactionNotice.condition
? () => _dismiss(compactionNotice)
: null,
),
),
...transcript,
// Messages the server holds queued (one sent before
// a reload, or from another device) follow the
// transcript: none has reached the harness yet.
@@ -952,15 +969,29 @@ class _ChatThreadViewState extends State<ChatThreadView> {
/// the model and mode controls.
Widget _header(BuildContext context, bool inShellBar) {
final session = widget.session;
final canGoBack = inShellBar
? ModalRoute.of(context)?.impliesAppBarDismissal ?? false
: true;
final answeredBy = latestReplyModel(_controller.messages);
return _chrome.widgetFor('header', answeredBy, [
widget,
inShellBar,
canGoBack,
], () => _buildHeader(session, inShellBar, canGoBack, answeredBy));
}
Widget _buildHeader(
JsonMap? session,
bool inShellBar,
bool canGoBack,
String answeredBy,
) {
final hasModel =
session != null && supportsChatModels('${session['backend'] ?? ''}');
// The mode control has nothing to show (or change) without both facts.
final hasMode =
'${session?['mode'] ?? ''}'.trim().isNotEmpty &&
'${session?['mode_name'] ?? ''}'.trim().isNotEmpty;
final canGoBack = inShellBar
? ModalRoute.of(context)?.impliesAppBarDismissal ?? false
: true;
final directory = '${session?['directory'] ?? ''}'.trim();
final folder = directory
.split(RegExp(r'[/\\]'))
@@ -991,7 +1022,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
sessionId: widget.sessionId,
session: session,
onChanged: widget.onModelChanged,
answeredBy: latestReplyModel(_controller.messages),
answeredBy: answeredBy,
),
),
if (hasMode)
@@ -1061,7 +1092,11 @@ class _ChatThreadViewState extends State<ChatThreadView> {
});
}
Widget _transcriptRow(JsonMap row, {VoidCallback? onDismissCompaction}) {
Widget _transcriptRow(
JsonMap row,
String key, {
VoidCallback? onDismissCompaction,
}) {
final kind = '${row['kind'] ?? ''}';
if (kind == 'activity') {
return _ChatActivityLine(row: row, onDismiss: onDismissCompaction);
@@ -1090,20 +1125,32 @@ class _ChatThreadViewState extends State<ChatThreadView> {
final delivery = message != null
? _composer.deliveries.stateFor(message)
: null;
return ChatMessageView(
row: row,
textBuilder: chatMarkdownText,
footer: [
...chips,
if (delivery != null)
ChatDeliveryIndicator(
state: delivery,
cupertino:
chatControlsStyleOf(context) == ChatControlsStyle.cupertino,
onRemove: _removeAction('${message?['operation_id'] ?? ''}'),
),
],
images: _images,
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final onRemove = _removeAction('${message?['operation_id'] ?? ''}');
// An unchanged finished row hands back its previous widget, so a streamed
// delta rebuilds only the live turn. Transcript snapshots are copied on
// write, never mutated, so a deep-equal row is the same content. Permission
// chips carry objects that compare by identity, so a row with chips is
// always rebuilt.
return _rowWidgets.widgetFor(
key,
row,
[delivery, cupertino, onRemove != null, _images, _controller, _composer],
() => ChatMessageView(
row: row,
textBuilder: chatMarkdownText,
footer: [
...chips,
if (delivery != null)
ChatDeliveryIndicator(
state: delivery,
cupertino: cupertino,
onRemove: onRemove,
),
],
images: _images,
),
);
}
@@ -175,6 +175,13 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
widget.onOpen(session);
}
// Methods rather than closures, so the list's memoized rows see the same
// callbacks from one build to the next.
void _reopen(JsonMap session) => _controller.reopen(_sessionId(session));
void _star(JsonMap session) =>
_controller.star(_sessionId(session), session['starred'] != true);
Future<void> _hide(JsonMap session) async {
await _controller.hide(_sessionId(session));
_undoTimer?.cancel();
@@ -226,12 +233,8 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
onOpen: _open,
onRename: _rename,
onClose: _close,
onReopen: (session) =>
_controller.reopen(_sessionId(session)),
onStar: (session) => _controller.star(
_sessionId(session),
session['starred'] != true,
),
onReopen: _reopen,
onStar: _star,
onHide: _hide,
onClearSearch: () {
_search.clear();
@@ -5,8 +5,7 @@ import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_sessions_body.dart';
import 'session_actions.dart';
import 'session_row_content.dart';
import 'session_row_memo.dart';
import '../../../../ui/adaptive/floating_bar_layout.dart';
class CupertinoSessionList extends StatelessWidget {
@@ -96,7 +95,7 @@ class CupertinoSessionList extends StatelessWidget {
final id = '${session['id'] ?? ''}';
final error = errorFor(id);
return [
ChatSessionRow(
memoChatSessionRow(
session: session,
selected: id == activeSessionId,
duplicateTitles: duplicateTitles,
@@ -104,15 +103,11 @@ class CupertinoSessionList extends StatelessWidget {
// A refusal below the row separates it instead.
divider: divider && error == null,
onOpen: onOpen,
onAction: (action) => _dispatch(
action,
session,
onStar: onStar,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onHide: onHide,
),
onStar: onStar,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onHide: onHide,
),
if (error != null)
ChatRowError(
@@ -124,30 +119,6 @@ class CupertinoSessionList extends StatelessWidget {
}
}
/// Routes a row's menu choice to the list's callbacks.
void _dispatch(
SessionAction action,
JsonMap session, {
required ValueChanged<JsonMap> onStar,
required ValueChanged<JsonMap> onRename,
required ValueChanged<JsonMap> onClose,
required ValueChanged<JsonMap> onReopen,
required ValueChanged<JsonMap> onHide,
}) {
switch (action) {
case SessionAction.star:
onStar(session);
case SessionAction.rename:
onRename(session);
case SessionAction.close:
onClose(session);
case SessionAction.reopen:
onReopen(session);
case SessionAction.hide:
onHide(session);
}
}
/// A directory's name above its chats, like a grouped table's header.
class _DirectoryHeader extends StatelessWidget {
const _DirectoryHeader(this.directory);
@@ -6,8 +6,7 @@ import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_sessions_body.dart';
import 'session_actions.dart';
import 'session_row_content.dart';
import 'session_row_memo.dart';
class MaterialSessionList extends StatelessWidget {
const MaterialSessionList({
@@ -97,7 +96,7 @@ class MaterialSessionList extends StatelessWidget {
final id = '${session['id'] ?? ''}';
final error = errorFor(id);
return [
ChatSessionRow(
memoChatSessionRow(
session: session,
selected: id == activeSessionId,
duplicateTitles: duplicateTitles,
@@ -105,15 +104,11 @@ class MaterialSessionList extends StatelessWidget {
// A refusal below the row separates it instead.
divider: divider && error == null,
onOpen: onOpen,
onAction: (action) => _dispatch(
action,
session,
onStar: onStar,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onHide: onHide,
),
onStar: onStar,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onHide: onHide,
),
if (error != null)
ChatRowError(
@@ -124,27 +119,3 @@ class MaterialSessionList extends StatelessWidget {
];
}
}
/// Routes a row's menu choice to the list's callbacks.
void _dispatch(
SessionAction action,
JsonMap session, {
required ValueChanged<JsonMap> onStar,
required ValueChanged<JsonMap> onRename,
required ValueChanged<JsonMap> onClose,
required ValueChanged<JsonMap> onReopen,
required ValueChanged<JsonMap> onHide,
}) {
switch (action) {
case SessionAction.star:
onStar(session);
case SessionAction.rename:
onRename(session);
case SessionAction.close:
onClose(session);
case SessionAction.reopen:
onReopen(session);
case SessionAction.hide:
onHide(session);
}
}
@@ -0,0 +1,57 @@
import 'package:flutter/widgets.dart';
import '../../../../core/api_gateway.dart';
import '../../../../ui/layout/memo_subtree.dart';
import '../../domain/chat_sessions.dart';
import 'session_actions.dart';
import 'session_row_content.dart';
/// A chat row that rebuilds only when its own session or state changes, so a
/// running-state change in one chat does not rebuild every row of the list.
///
/// The list's callbacks are part of the memo: the screen passes its own
/// methods, so they compare equal from one build to the next.
Widget memoChatSessionRow({
required JsonMap session,
required bool selected,
required Set<String> duplicateTitles,
required bool unseen,
required bool divider,
required ValueChanged<JsonMap> onOpen,
required ValueChanged<JsonMap> onStar,
required ValueChanged<JsonMap> onRename,
required ValueChanged<JsonMap> onClose,
required ValueChanged<JsonMap> onReopen,
required ValueChanged<JsonMap> onHide,
}) => MemoSubtree(
key: ValueKey('chat-row-memo-${session['id'] ?? ''}'),
memo: (
MemoMap(session),
selected,
// The row reads the set only for its own title.
duplicateTitles.contains(chatSessionTitle(session)),
unseen,
divider,
onOpen,
onStar,
onRename,
onClose,
onReopen,
onHide,
),
builder: (_) => ChatSessionRow(
session: session,
selected: selected,
duplicateTitles: duplicateTitles,
unseen: unseen,
divider: divider,
onOpen: onOpen,
onAction: (action) => switch (action) {
SessionAction.star => onStar(session),
SessionAction.rename => onRename(session),
SessionAction.close => onClose(session),
SessionAction.reopen => onReopen(session),
SessionAction.hide => onHide(session),
},
),
);
@@ -0,0 +1,49 @@
import 'dart:collection';
import 'chat_markdown.dart';
/// Parsed markdown blocks shared by every markdown view, keyed by the text.
///
/// A lazily built transcript disposes rows scrolled out of view, so scrolling
/// back would parse the same answer again. Blocks are immutable and depend on
/// the text alone, so one parse serves every later view of that text. Bounded
/// by entries and by held characters, evicting the least recently used first,
/// so a long streamed reply's intermediate texts cannot grow it without limit.
class ChatMarkdownCache {
ChatMarkdownCache({this.maxEntries = 400, this.maxChars = 1000000});
final int maxEntries;
final int maxChars;
/// Least recently used first.
final LinkedHashMap<String, List<MarkdownBlock>> _blocks = LinkedHashMap();
int _chars = 0;
/// How many texts were actually parsed (cache misses).
int parses = 0;
List<MarkdownBlock> blocksFor(String text) {
final held = _blocks.remove(text);
if (held != null) return _blocks[text] = held;
final blocks = List<MarkdownBlock>.unmodifiable(parseMarkdown(text));
parses++;
if (text.length > maxChars) return blocks;
_blocks[text] = blocks;
_chars += text.length;
while (_blocks.length > maxEntries || _chars > maxChars) {
final oldest = _blocks.keys.first;
_blocks.remove(oldest);
_chars -= oldest.length;
}
return blocks;
}
void clear() {
_blocks.clear();
_chars = 0;
parses = 0;
}
}
/// The one cache the transcript's markdown views share.
final chatMarkdownCache = ChatMarkdownCache();
@@ -6,6 +6,7 @@ import 'package:flutter/semantics.dart';
import '../../../../ui/adaptive/host.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_markdown.dart';
import 'chat_markdown_cache.dart';
import 'chat_message_bubble.dart';
/// Renders one assistant text part with native text widgets and the host's own
@@ -68,7 +69,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final gap = chatParagraphGap(context);
final blocks = parseMarkdown(widget.text);
final blocks = chatMarkdownCache.blocksFor(widget.text);
return _rendered = _selectable(
context,
Column(
+15 -1
View File
@@ -187,12 +187,26 @@ JsonMap? newRunSummaryFromFrame(JsonMap frame) {
: (runs: [row, ...runs], needsResync: false);
}
final updated = _mergeRunFields(runs[index], frame);
if (identical(updated, runs[index])) return (runs: runs, needsResync: false);
// A frame that repeats the row's state (a busy run's progress stream)
// keeps the same list, so its holders can skip a rebuild.
if (identical(updated, runs[index]) || _sameFields(updated, runs[index])) {
return (runs: runs, needsResync: false);
}
final next = [...runs];
next[index] = updated;
return (runs: next, needsResync: false);
}
/// Shallow equality: nested values compare by identity, so a rebuilt nested
/// map counts as a change.
bool _sameFields(JsonMap a, JsonMap b) {
if (a.length != b.length) return false;
for (final entry in a.entries) {
if (!b.containsKey(entry.key) || b[entry.key] != entry.value) return false;
}
return true;
}
JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) {
if (detail == null || detail['id'] != frame['run_id']) return detail;
if (_stale(detail['status'], frame['status'], runLifecycleRank) &&
@@ -271,6 +271,7 @@ class RunsController extends ChangeNotifier {
void _event(JsonMap frame) {
if (_removed.contains(frame['run_id'])) return;
final folded = foldRunEvent(runs, frame);
final before = (runs: runs, detail: detail);
runs = folded.runs;
selection.retain(runs);
if (detail?['id'] == frame['run_id']) {
@@ -285,6 +286,11 @@ class RunsController extends ChangeNotifier {
(folded.needsResync || runDetailNeedsFullSync(frame))) {
_scheduleDetailRefresh(selected);
}
// A frame that changed neither the list nor the open detail shows
// nothing new; the refreshes above notify for themselves.
if (identical(before.runs, runs) && identical(before.detail, detail)) {
return;
}
notifyListeners();
}
+34 -8
View File
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/floating_bar_layout.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/layout/memo_subtree.dart';
import '../../attention/notify/notification_controller.dart';
import '../../attention/runtime/attention_controller.dart';
import '../../attention/runtime/attention_store.dart';
@@ -146,7 +147,9 @@ class RunsList extends StatelessWidget {
RunsDeleteReport(controller: controller),
RunsFilters(controller: controller),
];
if (controller.visibleRuns.isNotEmpty) return _groupedRuns(context, header);
// Filtered and sorted once per build: the getter recomputes every read.
final visible = controller.visibleRuns;
if (visible.isNotEmpty) return _groupedRuns(context, header, visible);
return BelowTopBar(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -169,15 +172,17 @@ class RunsList extends StatelessWidget {
);
}
Widget _groupedRuns(BuildContext context, List<Widget> header) {
Widget _groupedRuns(
BuildContext context,
List<Widget> header,
List<JsonMap> visible,
) {
final entries = <_Entry>[];
if (flatRunSorts.contains(controller.sort)) {
// An order by size is one flat list: day headings would split it.
entries.addAll(
controller.visibleRuns.map((run) => (day: null, run: run)),
);
entries.addAll(visible.map((run) => (day: null, run: run)));
} else {
final groups = groupRunsByDay(controller.visibleRuns, DateTime.now());
final groups = groupRunsByDay(visible, DateTime.now());
for (final group in groups) {
entries.add((day: group, run: null));
entries.addAll(group.runs.map((run) => (day: null, run: run)));
@@ -185,7 +190,7 @@ class RunsList extends StatelessWidget {
}
// Runs that start while the list is open enter with a short fade.
return ArrivalScope(
ids: [for (final run in controller.visibleRuns) '${run['id']}'],
ids: [for (final run in visible) '${run['id']}'],
child: _entriesList(entries, header),
);
}
@@ -296,6 +301,27 @@ class RunsList extends StatelessWidget {
Widget _runTile(BuildContext context, JsonMap run, {bool divider = true}) {
final id = run['id'];
final selection = controller.selection;
final now = DateTime.now();
// A run event for one run rebuilds only that run's row: the others keep
// their built subtree (their menu, ripple and tooltip included).
return MemoSubtree(
memo: (
MemoMap(run),
divider,
selection.active,
selection.contains(id),
id == controller.selectedRunId,
controller,
onSelected,
// An executing run's duration reads the clock, as before.
run['executing'] == true ? runRowFacts(run, now).duration : null,
),
builder: (context) => _runRow(run, id, now, divider: divider),
);
}
Widget _runRow(JsonMap run, Object? id, DateTime now, {bool divider = true}) {
final selection = controller.selection;
return RunListRow(
selecting: selection.active,
@@ -307,7 +333,7 @@ class RunsList extends StatelessWidget {
run: run,
divider: divider,
selected: id == controller.selectedRunId,
now: DateTime.now(),
now: now,
onTap: id is num ? () => onSelected(id) : null,
gateway: controller.repository.gateway,
onRunChanged: controller.acceptRunDetail,
+95 -78
View File
@@ -140,78 +140,81 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
),
);
}).toList();
return ListenableBuilder(
listenable: _bar,
builder: (context, _) {
final spec = _bar.specFor(_selected);
// One floating glass tab bar at every width: full width on a phone,
// sized to its tabs at the right edge on a wide window (the bar judges
// that itself, live). Content keeps the whole width and scrolls behind
// it, learning the bar's height as its bottom media padding. Neither
// scaffold's structure depends on the width, so resizing never
// remounts a destination.
//
// While the tab shows its list beside an open item the bar keeps
// the same place, bottom right near the thumb: the item pane learns
// the bar's height (see ListDetailPanes) and floats its own tabs or
// composer above it, so the two never overlap.
final split = _bar.split(_selected);
final bar = FloatingDestinationBar(
cupertino: widget.cupertino,
currentIndex: index,
onTap: (value) => _select(shellTabDestinations[value]),
items: _destinationItems(),
);
// Destinations reach the top edge and scroll behind the floating top
// bar too: each learns the bar's height as its top media padding and
// pads its own lists by it (see withTopBarClearance).
final topBar = _ListPaneBar(
split: split,
bar: _segmentedBar(spec, details.label, page: page),
);
// The scaffolds below swap the system insets for their bars'
// heights; panes beside a list read the real ones from here.
final system = MediaQuery.paddingOf(context);
// A page (Settings) closes to Pipelines on the system Back too. The
// scope is always there, so opening the page never remounts the shell.
Widget backable(Widget child) => PopScope(
canPop: !page,
onPopInvokedWithResult: (didPop, _) {
if (!didPop) _closePage();
},
child: child,
);
if (widget.cupertino) {
return backable(
ShellSystemInsets(
padding: system,
child: CupertinoPageScaffold(
navigationBar: topBar,
child: SafeArea(
top: false,
bottom: false,
child: FloatingBarOverlay(
bar: bar,
child: _destinationStack(contents),
),
),
// Only the bar shows the registry's state, so a published bar or badge
// rebuilds its bar alone; the destinations and scaffold stay as built.
_bar.focus = _selected;
// One floating glass tab bar at every width: full width on a phone,
// sized to its tabs at the right edge on a wide window (the bar judges
// that itself, live). Content keeps the whole width and scrolls behind
// it, learning the bar's height as its bottom media padding. Neither
// scaffold's structure depends on the width, so resizing never
// remounts a destination.
//
// While the tab shows its list beside an open item the bar keeps
// the same place, bottom right near the thumb: the item pane learns
// the bar's height (see ListDetailPanes) and floats its own tabs or
// composer above it, so the two never overlap.
final bar = ListenableBuilder(
listenable: _bar.badges,
builder: (context, _) => FloatingDestinationBar(
cupertino: widget.cupertino,
currentIndex: index,
onTap: (value) => _select(shellTabDestinations[value]),
items: _destinationItems(),
),
);
// Destinations reach the top edge and scroll behind the floating top
// bar too: each learns the bar's height as its top media padding and
// pads its own lists by it (see withTopBarClearance).
SegmentedBar currentBar() =>
_segmentedBar(_bar.specFor(_selected), details.label, page: page);
final topBar = _ListPaneBar(
listenable: _bar.bar,
initial: currentBar(),
split: () => _bar.split(_selected),
bar: currentBar,
);
// The scaffolds below swap the system insets for their bars'
// heights; panes beside a list read the real ones from here.
final system = MediaQuery.paddingOf(context);
// A page (Settings) closes to Pipelines on the system Back too. The
// scope is always there, so opening the page never remounts the shell.
Widget backable(Widget child) => PopScope(
canPop: !page,
onPopInvokedWithResult: (didPop, _) {
if (!didPop) _closePage();
},
child: child,
);
if (widget.cupertino) {
return backable(
ShellSystemInsets(
padding: system,
child: CupertinoPageScaffold(
navigationBar: topBar,
child: SafeArea(
top: false,
bottom: false,
child: FloatingBarOverlay(
bar: bar,
child: _destinationStack(contents),
),
),
);
}
return backable(
ShellSystemInsets(
padding: system,
child: Scaffold(
extendBodyBehindAppBar: true,
appBar: topBar,
body: _destinationStack(contents),
extendBody: true,
bottomNavigationBar: bar,
),
),
);
},
),
);
}
return backable(
ShellSystemInsets(
padding: system,
child: Scaffold(
extendBodyBehindAppBar: true,
appBar: topBar,
body: _destinationStack(contents),
extendBody: true,
bottomNavigationBar: bar,
),
),
);
}
@@ -328,24 +331,38 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
/// beside an open item ([ShellPaneSplit]); the item's own bar takes the rest
/// of the same row. The bar keeps its place in the scaffold either way, so a
/// split never remounts it.
///
/// It rebuilds itself when [listenable] (the focused destination's published
/// bar) changes; [initial] supplies the size and obstruction, which do not
/// depend on the published contents.
class _ListPaneBar extends StatelessWidget
implements ObstructingPreferredSizeWidget {
const _ListPaneBar({required this.split, required this.bar});
const _ListPaneBar({
required this.listenable,
required this.initial,
required this.split,
required this.bar,
});
final bool split;
final SegmentedBar bar;
final Listenable listenable;
final SegmentedBar initial;
final bool Function() split;
final SegmentedBar Function() bar;
@override
Size get preferredSize => bar.preferredSize;
Size get preferredSize => initial.preferredSize;
@override
bool shouldFullyObstruct(BuildContext context) =>
bar.shouldFullyObstruct(context);
initial.shouldFullyObstruct(context);
@override
Widget build(BuildContext context) => ListPaneWidth(
split: split,
alignment: AlignmentDirectional.topStart,
child: bar,
Widget build(BuildContext context) => ListenableBuilder(
listenable: listenable,
builder: (context, _) => ListPaneWidth(
split: split(),
alignment: AlignmentDirectional.topStart,
child: bar(),
),
);
}
+38 -3
View File
@@ -53,9 +53,37 @@ class ShellBarSpec {
}
/// The bar contents each tab's open screen has published.
///
/// It notifies its own listeners of every visible change. A host that shows
/// one destination's bar at a time sets [focus] and may listen to [bar] and
/// [badges] separately: a hidden tab republishing its bar (a list rebuilding
/// on a run event) then rebuilds nothing, and a badge change rebuilds only
/// the tab bar.
class ShellBarRegistry extends ChangeNotifier {
final Map<AppDestination, (Object, ShellBarSpec)> _specs = {};
final Map<(AppDestination, ShellBadgeKind), int> _badges = {};
final _Notifier _bar = _Notifier();
final _Notifier _badgeNotifier = _Notifier();
/// The destination whose bar is on screen; null treats every destination
/// as shown. Bar changes of other destinations are kept without notifying:
/// the host rebuilds when it changes the focus.
AppDestination? focus;
/// Notifies when the focused destination's bar spec or split changes.
Listenable get bar => _bar;
/// Notifies when any tab badge count changes.
Listenable get badges => _badgeNotifier;
bool _shown(AppDestination destination) =>
focus == null || focus == destination;
void _barChanged(AppDestination destination) {
if (!_shown(destination)) return;
_bar.notify();
notifyListeners();
}
final Map<AppDestination, int> _splits = {};
@@ -68,7 +96,7 @@ class ShellBarRegistry extends ChangeNotifier {
if (_disposed) return;
final before = split(destination);
_splits[destination] = (_splits[destination] ?? 0) + (value ? 1 : -1);
if (split(destination) != before) notifyListeners();
if (split(destination) != before) _barChanged(destination);
}
/// The count a tab's screen published for [kind], 0 when none.
@@ -78,6 +106,7 @@ class ShellBarRegistry extends ChangeNotifier {
void _setBadge(AppDestination destination, ShellBadgeKind kind, int count) {
if (_disposed || badge(destination, kind) == count) return;
_badges[(destination, kind)] = count;
_badgeNotifier.notify();
notifyListeners();
}
@@ -86,6 +115,8 @@ class ShellBarRegistry extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
_bar.dispose();
_badgeNotifier.dispose();
super.dispose();
}
@@ -99,17 +130,21 @@ class ShellBarRegistry extends ChangeNotifier {
// A screen's update can land after the shell itself has gone.
if (_disposed) return;
_specs[destination] = (owner, spec);
notifyListeners();
_barChanged(destination);
}
void _clear(AppDestination destination, Object owner) {
if (_disposed) return;
if (_specs[destination]?.$1 != owner) return;
_specs.remove(destination);
notifyListeners();
_barChanged(destination);
}
}
class _Notifier extends ChangeNotifier {
void notify() => notifyListeners();
}
/// Places one tab's content under the shell's bar registry.
class ShellBarScope extends InheritedWidget {
const ShellBarScope({
+65
View File
@@ -0,0 +1,65 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
/// Builds [builder] once and hands Flutter the same child until [memo]
/// changes, so a list that rebuilds on every notification skips the rows
/// whose own data did not change.
///
/// [memo] must capture everything the built subtree shows or calls: the
/// row's data and every callback or controller its closures use (compare
/// callbacks by `==`, so a tear-off of the same method still matches). The
/// subtree's own inherited dependencies (theme, host, media) still rebuild
/// it directly, as they mark its elements rather than this one.
class MemoSubtree extends StatefulWidget {
const MemoSubtree({super.key, required this.memo, required this.builder});
final Object? memo;
final WidgetBuilder builder;
@override
State<MemoSubtree> createState() => _MemoSubtreeState();
}
class _MemoSubtreeState extends State<MemoSubtree> {
Widget? _child;
@override
void didUpdateWidget(MemoSubtree oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.memo != widget.memo) _child = null;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// A builder that read an inherited widget through this context.
_child = null;
}
@override
void reassemble() {
super.reassemble();
_child = null;
}
@override
Widget build(BuildContext context) => _child ??= widget.builder(context);
}
/// A JSON row map as a [MemoSubtree] memo: equal when it is the same map or
/// has the same entries (nested values compare by `==`, so a rebuilt nested
/// map counts as a change).
@immutable
class MemoMap {
const MemoMap(this.map);
final Map<String, dynamic>? map;
@override
bool operator ==(Object other) =>
other is MemoMap &&
(identical(map, other.map) || mapEquals(map, other.map));
@override
int get hashCode => map?.length ?? 0;
}
+152
View File
@@ -0,0 +1,152 @@
import 'dart:math' as math;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
/// Opens and closes a sliver by growing or shrinking it from its top, the
/// sliver counterpart of a clipped `AnimatedSize` with top alignment. The
/// sliver stays lazy: only its visible part is built and laid out, however
/// long it is. Closed, it takes no space and builds nothing.
class SliverReveal extends StatefulWidget {
const SliverReveal({
super.key,
required this.open,
required this.duration,
required this.curve,
required this.sliver,
});
final bool open;
final Duration duration;
final Curve curve;
final Widget sliver;
@override
State<SliverReveal> createState() => _SliverRevealState();
}
class _SliverRevealState extends State<SliverReveal>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: widget.duration,
value: widget.open ? 1 : 0,
);
@override
void didUpdateWidget(SliverReveal oldWidget) {
super.didUpdateWidget(oldWidget);
_controller.duration = widget.duration;
if (widget.open == oldWidget.open) return;
if (widget.duration == Duration.zero) {
_controller.value = widget.open ? 1 : 0;
} else if (widget.open) {
_controller.forward();
} else {
_controller.reverse();
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: _controller,
builder: (context, sliver) {
if (_controller.isDismissed) return const SliverToBoxAdapter();
final value = _controller.value;
return _SliverExtentFactor(
factor: value >= 1 ? 1 : widget.curve.transform(value),
sliver: sliver,
);
},
child: widget.sliver,
);
}
class _SliverExtentFactor extends SingleChildRenderObjectWidget {
const _SliverExtentFactor({required this.factor, Widget? sliver})
: super(child: sliver);
final double factor;
@override
RenderObject createRenderObject(BuildContext context) =>
_RenderSliverExtentFactor(factor);
@override
void updateRenderObject(
BuildContext context,
_RenderSliverExtentFactor renderObject,
) => renderObject.factor = factor;
}
/// Lays its sliver out normally and reports [factor] of its extent, clipping
/// what lies beyond.
class _RenderSliverExtentFactor extends RenderProxySliver {
_RenderSliverExtentFactor(this._factor);
double _factor;
set factor(double value) {
if (value == _factor) return;
_factor = value;
markNeedsLayout();
}
bool get _clipped => _factor < 1;
@override
void performLayout() {
final child = this.child!;
child.layout(constraints, parentUsesSize: true);
final full = child.geometry!;
if (!_clipped || full.scrollOffsetCorrection != null) {
geometry = full;
return;
}
final extent = full.scrollExtent * _factor;
final paintExtent = math.min(
calculatePaintOffset(constraints, from: 0, to: extent),
full.paintExtent,
);
geometry = SliverGeometry(
scrollExtent: extent,
paintExtent: paintExtent,
layoutExtent: paintExtent,
maxPaintExtent: extent,
cacheExtent: calculateCacheOffset(constraints, from: 0, to: extent),
hasVisualOverflow: true,
);
}
@override
void paint(PaintingContext context, Offset offset) {
if (child == null || geometry!.paintExtent <= 0) return;
if (!_clipped) 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();
}
}
+34 -17
View File
@@ -7,6 +7,7 @@ import '../adaptive/host.dart';
import '../theme/app_theme.dart';
import '../motion/motion.dart';
import 'section_heading.dart';
import 'sliver_reveal.dart';
/// A collapsible section for a [CustomScrollView]: its title stays pinned at
/// the top while its content scrolls under it, so it can always be closed
@@ -17,17 +18,22 @@ class StickySection extends StatelessWidget {
required this.title,
required this.open,
required this.onToggle,
required this.body,
this.body,
this.sliverBody,
this.trailing = const [],
this.titleColor,
});
}) : assert((body == null) != (sliverBody == null));
final String title;
final bool open;
final VoidCallback onToggle;
/// The content shown while open (a box widget).
final Widget body;
final Widget? body;
/// The content shown while open as a sliver, in place of [body]: a long
/// body (hundreds of items) then builds and lays out only what is visible.
final Widget? sliverBody;
/// Small actions beside the title (a count, a copy button).
final List<Widget> trailing;
@@ -54,18 +60,30 @@ class StickySection extends StatelessWidget {
),
// The content grows and shrinks under the pinned title, on its own
// surface with the title's accent continuing down its edge.
SliverToBoxAdapter(
child: ClipRect(
child: AnimatedSize(
duration: Motion.of(context, Motion.standard),
curve: Motion.curve,
alignment: Alignment.topCenter,
child: open
? _SectionBody(child: body)
: const SizedBox(width: double.infinity),
if (sliverBody case final sliver?)
SliverReveal(
open: open,
duration: Motion.of(context, Motion.standard),
curve: Motion.curve,
// The body's padding; its rows bring their own ink surface.
sliver: SliverPadding(
padding: _SectionBody.padding,
sliver: sliver,
),
)
else
SliverToBoxAdapter(
child: ClipRect(
child: AnimatedSize(
duration: Motion.of(context, Motion.standard),
curve: Motion.curve,
alignment: Alignment.topCenter,
child: open
? _SectionBody(child: body!)
: const SizedBox(width: double.infinity),
),
),
),
),
],
);
}
@@ -254,12 +272,11 @@ class _SectionBody extends StatelessWidget {
final Widget child;
static const padding = EdgeInsets.only(top: 12, bottom: 4);
@override
Widget build(BuildContext context) {
final content = Padding(
padding: const EdgeInsets.only(top: 12, bottom: 4),
child: child,
);
final content = Padding(padding: padding, child: child);
if (usesCupertinoHost(context)) {
return content;
}
+105
View File
@@ -0,0 +1,105 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
/// One minute clock shared by every relative-time label.
///
/// A list of rows used to run one timer per row; this clock runs a single
/// timer, aligned to the start of each wall-clock minute, only while some
/// label listens and the app is visible. Labels re-read [now] when it
/// notifies and rebuild only if their text changed.
class RelativeTimeClock extends ChangeNotifier with WidgetsBindingObserver {
RelativeTimeClock();
/// The clock the app's labels share.
static final RelativeTimeClock shared = RelativeTimeClock();
DateTime _now = DateTime.now();
Timer? _timer;
bool _observing = false;
bool _hidden = false;
/// The clock's current minute-resolution time. It advances by the elapsed
/// delay on each tick, which keeps it consistent under a fake clock.
DateTime get now => _now;
/// Whether a tick is scheduled (a label listens and the app is visible).
@visibleForTesting
bool get ticking => _timer != null;
@override
void addListener(VoidCallback listener) {
final first = !hasListeners;
super.addListener(listener);
if (!first) return;
_now = DateTime.now();
_hidden = switch (WidgetsBinding.instance.lifecycleState) {
AppLifecycleState.hidden ||
AppLifecycleState.paused ||
AppLifecycleState.detached => true,
_ => false,
};
if (!_observing) {
WidgetsBinding.instance.addObserver(this);
_observing = true;
}
_schedule();
}
@override
void removeListener(VoidCallback listener) {
super.removeListener(listener);
if (hasListeners) return;
_stop();
if (_observing) {
WidgetsBinding.instance.removeObserver(this);
_observing = false;
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_hidden = false;
_now = DateTime.now();
notifyListeners();
_schedule();
} else if (state == AppLifecycleState.hidden ||
// Not inactive: a desktop window that lost focus is still visible.
state == AppLifecycleState.paused ||
state == AppLifecycleState.detached) {
_hidden = true;
_stop();
}
}
void _schedule() {
_timer?.cancel();
_timer = null;
if (_hidden || !hasListeners) return;
final intoMinute = Duration(
seconds: _now.second,
milliseconds: _now.millisecond,
microseconds: _now.microsecond,
);
final delay = const Duration(minutes: 1) - intoMinute;
_timer = Timer(delay, () {
_timer = null;
_now = _now.add(delay);
notifyListeners();
_schedule();
});
}
void _stop() {
_timer?.cancel();
_timer = null;
}
@override
void dispose() {
_stop();
if (_observing) WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
}
+47 -62
View File
@@ -1,93 +1,79 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'relative_time.dart';
import 'relative_time_clock.dart';
/// A relative-time label that rebuilds only itself when its formatter can
/// change. It stops its timer while the app is backgrounded.
/// A relative-time label that rebuilds only itself, and only when its text
/// changes. Every label follows one shared minute [RelativeTimeClock] rather
/// than a timer of its own; a label whose tickers are muted (an offstage tab
/// or a covered route) skips the ticks and catches up when shown again.
class RelativeTimeLabel extends StatefulWidget {
const RelativeTimeLabel({super.key, required this.instant, this.now});
const RelativeTimeLabel({
super.key,
required this.instant,
this.now,
this.clock,
});
final DateTime? instant;
/// The time the label starts from; the shared clock advances it.
final DateTime? now;
/// The clock to follow; [RelativeTimeClock.shared] when null.
final RelativeTimeClock? clock;
@override
State<RelativeTimeLabel> createState() => _RelativeTimeLabelState();
}
class _RelativeTimeLabelState extends State<RelativeTimeLabel>
with WidgetsBindingObserver {
Timer? _timer;
DateTime _now = DateTime.now();
class _RelativeTimeLabelState extends State<RelativeTimeLabel> {
late RelativeTimeClock _clock;
late DateTime _now;
bool _shown = true;
bool _stale = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_schedule();
_now = widget.now ?? DateTime.now();
_clock = widget.clock ?? RelativeTimeClock.shared;
_clock.addListener(_tick);
}
@override
void didUpdateWidget(RelativeTimeLabel oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.instant != widget.instant) _schedule();
final clock = widget.clock ?? RelativeTimeClock.shared;
if (clock == _clock) return;
_clock.removeListener(_tick);
_clock = clock..addListener(_tick);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_now = DateTime.now();
if (mounted) setState(() {});
_schedule(current: _now);
} else if (state == AppLifecycleState.hidden ||
// Not inactive: a desktop window that lost focus is still visible.
state == AppLifecycleState.paused ||
state == AppLifecycleState.detached) {
_timer?.cancel();
_timer = null;
}
void didChangeDependencies() {
super.didChangeDependencies();
_shown = TickerMode.valuesOf(context).enabled;
if (_shown && _stale) _advance();
}
void _schedule({DateTime? current}) {
_timer?.cancel();
final instant = widget.instant;
if (instant == null) return;
final now = current ?? widget.now ?? DateTime.now();
_now = now;
final next = _nextBoundary(instant, now);
final delay = next.difference(now);
_timer = Timer(delay.isNegative ? Duration.zero : delay, () {
if (!mounted) return;
_now = _now.add(delay);
setState(() {});
_schedule(current: _now);
});
/// Moves to the clock's time; true when the text changed.
bool _advance() {
_stale = false;
final next = _clock.now;
if (!next.isAfter(_now)) return false;
final before = formatRelativeTime(widget.instant, now: _now);
_now = next;
return formatRelativeTime(widget.instant, now: _now) != before;
}
DateTime _nextBoundary(DateTime instant, DateTime now) {
final difference = now.difference(instant);
final age = difference.abs();
final unit = age < const Duration(hours: 1)
? const Duration(minutes: 1)
: age < const Duration(days: 1)
? const Duration(hours: 1)
: age < const Duration(days: 7)
? const Duration(days: 1)
: null;
if (unit != null) {
final units = age.inMilliseconds ~/ unit.inMilliseconds;
final boundary = difference.isNegative
// Future labels use a decreasing count. Add a second so an exact
// boundary does not immediately schedule another zero-delay timer.
? instant.subtract(unit * units).add(const Duration(seconds: 1))
: instant.add(unit * (units + 1));
if (boundary.isAfter(now)) return boundary;
void _tick() {
if (!mounted || widget.instant == null) return;
if (!_shown) {
_stale = true;
return;
}
final midnight = DateTime(now.year, now.month, now.day + 1);
return midnight.isAfter(now)
? midnight
: now.add(const Duration(minutes: 1));
if (_advance()) setState(() {});
}
@override
@@ -102,8 +88,7 @@ class _RelativeTimeLabelState extends State<RelativeTimeLabel>
@override
void dispose() {
_timer?.cancel();
WidgetsBinding.instance.removeObserver(this);
_clock.removeListener(_tick);
super.dispose();
}
}