Merge main into run token usage branch

This commit is contained in:
2026-11-03 22:21:38 +00:00
118 changed files with 4294 additions and 1483 deletions
@@ -0,0 +1,50 @@
/// What following one link inside a recorded HTML document does.
enum ArtifactHtmlLinkAction {
/// A place in the same document (`#section`): the view scrolls to it.
inDocument,
/// An `http`, `https` or `mailto` address: it opens outside the artifact
/// (a new browser tab on the web, the system's handler on a phone), never
/// inside the document's view.
external,
/// Anything else (`javascript:`, `file:`, `data:`, a relative path the
/// document has no base for): the link stays inert.
blocked,
}
const _externalSchemes = {'http', 'https', 'mailto'};
/// The documents the views load the recorded HTML as: a web view's
/// `about:blank` and an iframe's `about:srcdoc`.
const _documentUrls = {'about:blank', 'about:srcdoc'};
/// Decides what a link in a recorded HTML document does, from the raw `href`
/// (the web view rewrites anchors before showing the document) or the url a
/// mobile web view resolved it to.
///
/// The document is loaded from a string, so it has no address of its own: a
/// relative link cannot resolve to the artifact's neighbours and stays inert
/// rather than reaching the app's own origin.
ArtifactHtmlLinkAction artifactHtmlLinkAction(String href) {
final link = href.trim();
if (link.isEmpty) return ArtifactHtmlLinkAction.blocked;
if (link.startsWith('#')) return ArtifactHtmlLinkAction.inDocument;
final uri = Uri.tryParse(link);
if (uri == null || !uri.hasScheme) return ArtifactHtmlLinkAction.blocked;
final scheme = uri.scheme.toLowerCase();
if (_externalSchemes.contains(scheme)) {
// `http:foo` with no host is not an address anyone can open.
if (scheme != 'mailto' && uri.host.isEmpty) {
return ArtifactHtmlLinkAction.blocked;
}
return ArtifactHtmlLinkAction.external;
}
if (scheme == 'about') {
final document = link.split('#').first.toLowerCase();
if (_documentUrls.contains(document)) {
return ArtifactHtmlLinkAction.inDocument;
}
}
return ArtifactHtmlLinkAction.blocked;
}
@@ -0,0 +1,116 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
/// Open, Copy and the file actions float over the top of the content: shown
/// when the page opens and whenever the content is touched, hidden again after
/// a few seconds without use, so nothing needs scrolling to reach them.
class ArtifactControlsOverlay extends StatefulWidget {
const ArtifactControlsOverlay({
super.key,
required this.controls,
required this.child,
this.hideAfter = const Duration(seconds: 3),
});
final List<Widget> controls;
final Widget child;
final Duration hideAfter;
@override
State<ArtifactControlsOverlay> createState() =>
_ArtifactControlsOverlayState();
}
class _ArtifactControlsOverlayState extends State<ArtifactControlsOverlay> {
bool _shown = true;
Timer? _hide;
@override
void initState() {
super.initState();
_schedule();
}
@override
void dispose() {
_hide?.cancel();
super.dispose();
}
void _schedule() {
_hide?.cancel();
_hide = Timer(widget.hideAfter, () {
if (mounted) setState(() => _shown = false);
});
}
void _show() {
if (!_shown) setState(() => _shown = true);
_schedule();
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final surface = cupertino
? CupertinoColors.systemBackground
.resolveFrom(context)
.withValues(alpha: 0.92)
: Theme.of(
context,
).colorScheme.surfaceContainerHigh.withValues(alpha: 0.94);
return Stack(
children: [
// Any touch on the content brings the controls back.
Positioned.fill(
child: Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) => _show(),
child: widget.child,
),
),
Positioned(
left: 8,
right: 8,
top: 8,
child: IgnorePointer(
ignoring: !_shown,
child: AnimatedOpacity(
key: const Key('artifact-viewer-controls'),
opacity: _shown ? 1 : 0,
duration: const Duration(milliseconds: 200),
child: Listener(
// Using a control keeps the bar up.
onPointerDown: (_) => _schedule(),
child: DecoratedBox(
decoration: BoxDecoration(
color: surface,
borderRadius: BorderRadius.circular(12),
boxShadow: const [
BoxShadow(color: Color(0x22000000), blurRadius: 6),
],
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 2,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
children: widget.controls,
),
),
),
),
),
),
),
],
);
}
}
@@ -0,0 +1,116 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/segmented_bar_overflow.dart';
import '../actions/artifact_file_actions.dart';
/// Marks a subtree as the artifact viewer's full-screen view, where an HTML
/// document takes every gesture over it (scroll, pan, pinch) instead of
/// sharing them with the viewer's page swipe, and follows [htmlZoom].
class ArtifactFullscreenScope extends InheritedWidget {
const ArtifactFullscreenScope({
super.key,
required this.htmlZoom,
required super.child,
});
/// The HTML document's zoom factor (1 is the document's own size), set by
/// [ArtifactHtmlZoomActions].
final ValueListenable<double> htmlZoom;
static ArtifactFullscreenScope? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<ArtifactFullscreenScope>();
@override
bool updateShouldNotify(ArtifactFullscreenScope oldWidget) =>
htmlZoom != oldWidget.htmlZoom;
}
/// The full-screen view's route, pushed on the root navigator so it covers
/// the shell's bars and list pane. A full-screen dialog route: its bar shows
/// the platform's Close, and the system back gesture leaves it.
Route<void> artifactFullscreenRoute({
required bool cupertino,
required WidgetBuilder builder,
}) => cupertino
? CupertinoPageRoute<void>(fullscreenDialog: true, builder: builder)
: MaterialPageRoute<void>(fullscreenDialog: true, builder: builder);
/// The zoom factors Zoom in and Zoom out step through.
const List<double> artifactHtmlZoomSteps = [
0.5, 0.67, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, //
];
/// The next zoom step from [current] in [direction] (+1 in, -1 out), held at
/// both ends.
double artifactHtmlZoomStep(double current, int direction) {
if (direction > 0) {
return artifactHtmlZoomSteps.firstWhere(
(step) => step > current + 0.001,
orElse: () => artifactHtmlZoomSteps.last,
);
}
return artifactHtmlZoomSteps.lastWhere(
(step) => step < current - 0.001,
orElse: () => artifactHtmlZoomSteps.first,
);
}
const artifactZoomOutKey = ValueKey<String>('artifact-zoom-out');
const artifactZoomResetKey = ValueKey<String>('artifact-zoom-reset');
const artifactZoomInKey = ValueKey<String>('artifact-zoom-in');
/// Zoom out, actual size and zoom in for an HTML document, as top-bar
/// actions (a narrow bar moves them into its More menu). Used where the
/// document cannot be pinched (the web's sandboxed frame): the frame keeps
/// scrolling the live document at the chosen size.
List<Widget> artifactHtmlZoomActions(ValueNotifier<double> zoom) {
void step(int direction) =>
zoom.value = artifactHtmlZoomStep(zoom.value, direction);
final percent = '${(zoom.value * 100).round()}%';
Widget action(
Key key,
String label,
IconData icon,
IconData cupertinoIcon,
VoidCallback? onPressed,
) => SegmentedOverflowAction(
key: key,
overflowEntry: SegmentedOverflowEntry(
label: label,
icon: icon,
onPressed: onPressed,
),
child: ArtifactIconAction(
label: label,
icon: icon,
cupertinoIcon: cupertinoIcon,
onPressed: onPressed,
),
);
final value = zoom.value;
return [
action(
artifactZoomOutKey,
'Zoom out',
Icons.zoom_out,
CupertinoIcons.zoom_out,
value > artifactHtmlZoomSteps.first + 0.001 ? () => step(-1) : null,
),
action(
artifactZoomResetKey,
'Actual size ($percent)',
Icons.restart_alt,
CupertinoIcons.arrow_counterclockwise,
(value - 1).abs() > 0.001 ? () => zoom.value = 1 : null,
),
action(
artifactZoomInKey,
'Zoom in',
Icons.zoom_in,
CupertinoIcons.zoom_in,
value < artifactHtmlZoomSteps.last - 0.001 ? () => step(1) : null,
),
];
}
@@ -0,0 +1,58 @@
import 'package:flutter/widgets.dart';
import '../../../ui/adaptive/host.dart';
import 'artifact_fullscreen.dart';
/// Lets a viewer page open its own content as the full-screen view.
///
/// The full-screen route lives on the root navigator, outside the page's
/// subtree, yet draws from the page's state: [buildFrame] builds either
/// presentation, and every [setState] redraws the full-screen route too, so
/// paging, loading and status messages show in both.
mixin ArtifactFullscreenHost<T extends StatefulWidget> on State<T> {
final ValueNotifier<int> _revision = ValueNotifier<int>(0);
/// The full-screen view's HTML zoom; each full-screen visit starts at 1.
final ValueNotifier<double> htmlZoom = ValueNotifier<double>(1);
Route<void>? _fullscreen;
/// The page's scaffold, inline or as the full-screen view.
Widget buildFrame(BuildContext context, {required bool fullscreen});
@override
void setState(VoidCallback fn) {
super.setState(fn);
_revision.value++;
}
@override
void dispose() {
// The full-screen route closes with the page, once the tree unlocks.
final route = _fullscreen;
if (route != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (route.isActive) route.navigator?.removeRoute(route);
});
}
super.dispose();
}
/// Opens the full-screen view; it returns when the view closes.
Future<void> enterFullscreen() async {
if (_fullscreen != null) return;
htmlZoom.value = 1;
final route = artifactFullscreenRoute(
cupertino: usesCupertinoHost(context),
builder: (_) => ArtifactFullscreenScope(
htmlZoom: htmlZoom,
child: ListenableBuilder(
listenable: Listenable.merge([_revision, htmlZoom]),
builder: (context, _) => buildFrame(context, fullscreen: true),
),
),
);
_fullscreen = route;
await Navigator.of(context, rootNavigator: true).push(route);
_fullscreen = null;
}
}
@@ -370,7 +370,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () => _open(resolved, dialogContext),
child: const Text('Open'),
child: const Text('Open in browser'),
),
],
),
@@ -394,7 +394,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
if (resolved != null)
TextButton(
onPressed: () => _open(resolved, dialogContext),
child: const Text('Open'),
child: const Text('Open in browser'),
),
],
),
@@ -0,0 +1,52 @@
import 'dart:js_interop';
import 'package:web/web.dart' as web;
import '../domain/artifact_html_links.dart';
/// The iframe's sandbox: no script, no same-origin access, no forms and no
/// navigation of the app, but a link may open a new tab that is itself
/// unsandboxed (an ordinary website, as if typed into the address bar).
const String artifactHtmlSandbox =
'allow-popups allow-popups-to-escape-sandbox';
/// [html] with every link's behaviour fixed before the frame shows it
/// ([artifactHtmlLinkAction]): a `#place` stays in the frame and scrolls
/// there, an http(s)/mailto address opens a new tab (no opener, no
/// referrer), and every other link loses its `href`, so it is inert text.
/// A document's own `<base>` is dropped: the frame is not at the artifact's
/// address, and a relative link must not reach the app's origin.
///
/// The browser's `DOMParser` builds an inert document: nothing in it runs or
/// loads while it is rewritten.
String artifactHtmlWithInertLinks(String html) {
final doc = web.DOMParser().parseFromString(html.toJS, 'text/html');
final bases = doc.querySelectorAll('base');
for (var i = bases.length - 1; i >= 0; i--) {
(bases.item(i) as web.Element?)?.remove();
}
final links = doc.querySelectorAll('a[href], area[href]');
for (var i = 0; i < links.length; i++) {
final link = links.item(i) as web.Element?;
if (link == null) continue;
final href = link.getAttribute('href') ?? '';
switch (artifactHtmlLinkAction(href)) {
case ArtifactHtmlLinkAction.inDocument:
// A srcdoc document's base is the app page, so a bare `#place` would
// navigate the frame to the app; the document's own address keeps it
// a same-document jump.
final hash = href.indexOf('#');
final place = hash < 0 ? '' : href.substring(hash);
link.setAttribute('href', 'about:srcdoc$place');
link.setAttribute('target', '_self');
case ArtifactHtmlLinkAction.external:
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
case ArtifactHtmlLinkAction.blocked:
link.removeAttribute('href');
link.removeAttribute('target');
}
}
final doctype = doc.doctype == null ? '' : '<!DOCTYPE html>';
return '$doctype${doc.documentElement?.outerHTML ?? ''}';
}
@@ -1,5 +1,6 @@
import 'package:flutter/widgets.dart';
import 'artifact_fullscreen.dart';
import 'artifact_html_view_native.dart'
if (dart.library.js_interop) 'artifact_html_view_web.dart'
as impl;
@@ -9,6 +10,12 @@ import 'artifact_html_view_native.dart'
typedef ArtifactHtmlBuilder =
Widget Function(BuildContext context, String html);
/// Whether the full-screen view offers zoom buttons for HTML: on the web the
/// sandboxed frame cannot be pinched (the page's viewport is not scalable and
/// a frame's document has no pinch zoom of its own), so the buttons scale the
/// live frame. The mobile web views pinch natively and offer none.
const bool artifactHtmlZoomButtons = impl.inertHtmlZoomButtons;
/// Renders a recorded HTML document inertly: on the web in an iframe whose
/// empty `sandbox` blocks scripts, forms, popups and navigation; on Android and
/// iOS in a web view with JavaScript disabled and navigation refused. The
@@ -18,13 +25,22 @@ typedef ArtifactHtmlBuilder =
/// the web the iframe is a platform view that takes every click over its
/// area, even where a bar is drawn on top, which left the viewer's actions
/// and pager unclickable.
///
/// Inside an [ArtifactFullscreenScope] the document takes every gesture over
/// it and follows the scope's zoom; inline it shares them with the viewer's
/// page swipe.
Widget defaultArtifactHtml(BuildContext context, String html) {
final padding = MediaQuery.paddingOf(context);
final fullscreen = ArtifactFullscreenScope.maybeOf(context);
return Padding(
padding: EdgeInsets.only(top: padding.top, bottom: padding.bottom),
child: SizedBox.expand(
key: const Key('artifact-html-preview'),
child: impl.InertHtmlView(html: html),
child: impl.InertHtmlView(
html: html,
interactive: fullscreen != null,
zoom: fullscreen?.htmlZoom,
),
),
);
}
@@ -1,36 +1,105 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../domain/artifact_html_links.dart';
import 'artifact_external_open.dart';
/// The mobile web views pinch-zoom natively (Android's built-in zoom, which
/// the plugin turns on with its display controls hidden; WKWebView's own), so
/// the full-screen view needs no zoom buttons.
const bool inertHtmlZoomButtons = false;
/// A web view with JavaScript disabled that refuses every navigation after the
/// recorded document itself loads.
///
/// A platform view only receives the pointers of gestures that its
/// [WebViewWidget.gestureRecognizers] win in Flutter's gesture arena. With
/// none it got a drag only after every other recognizer gave up, which the
/// viewer's page swipe never does before the finger lifts: the document never
/// scrolled or pinched. Inline it claims vertical drags (scrolling the
/// document) and leaves horizontal ones to the page swipe; [interactive] (the
/// full-screen view) claims every pointer at once, so scroll, pan and pinch
/// all reach the document.
class InertHtmlView extends StatefulWidget {
const InertHtmlView({super.key, required this.html});
const InertHtmlView({
super.key,
required this.html,
this.interactive = false,
this.zoom,
this.openExternal = openArtifactExternally,
});
final String html;
/// Opens a link's http(s)/mailto address outside the artifact.
final ArtifactExternalOpen openExternal;
final bool interactive;
/// Unused: the mobile web views pinch instead ([inertHtmlZoomButtons]).
final ValueListenable<double>? zoom;
@override
State<InertHtmlView> createState() => _InertHtmlViewState();
}
final _inlineGestures = <Factory<OneSequenceGestureRecognizer>>{
Factory<VerticalDragGestureRecognizer>(VerticalDragGestureRecognizer.new),
};
final _allGestures = <Factory<OneSequenceGestureRecognizer>>{
Factory<EagerGestureRecognizer>(EagerGestureRecognizer.new),
};
class _InertHtmlViewState extends State<InertHtmlView> {
/// Until the recorded document finishes loading, the view may load it (an
/// `about:` or `data:` document); afterwards only links are followed.
bool _loaded = false;
late final WebViewController _controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.disabled)
..enableZoom(true)
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (request) =>
request.url.startsWith('about:') || request.url.startsWith('data:')
? NavigationDecision.navigate
: NavigationDecision.prevent,
onPageFinished: (_) => _loaded = true,
onNavigationRequest: _decide,
),
)
..loadHtmlString(widget.html);
@override
void didUpdateWidget(covariant InertHtmlView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.html != widget.html) _controller.loadHtmlString(widget.html);
/// Links: a place in the document scrolls there; an http(s)/mailto address
/// opens in the system's handler, never inside this view; anything else
/// (scripts, files, other schemes, relative paths) stays inert.
NavigationDecision _decide(NavigationRequest request) {
if (!_loaded &&
(request.url.startsWith('about:') || request.url.startsWith('data:'))) {
return NavigationDecision.navigate;
}
switch (artifactHtmlLinkAction(request.url)) {
case ArtifactHtmlLinkAction.inDocument:
return NavigationDecision.navigate;
case ArtifactHtmlLinkAction.external:
final uri = Uri.tryParse(request.url.trim());
if (uri != null) widget.openExternal(uri);
return NavigationDecision.prevent;
case ArtifactHtmlLinkAction.blocked:
return NavigationDecision.prevent;
}
}
@override
Widget build(BuildContext context) => WebViewWidget(controller: _controller);
void didUpdateWidget(covariant InertHtmlView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.html != widget.html) {
_loaded = false;
_controller.loadHtmlString(widget.html);
}
}
@override
Widget build(BuildContext context) => WebViewWidget(
controller: _controller,
gestureRecognizers: widget.interactive ? _allGestures : _inlineGestures,
);
}
@@ -1,28 +1,109 @@
import 'dart:js_interop';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:web/web.dart' as web;
/// A sandboxed iframe: the empty `sandbox` attribute applies every
/// restriction, so the document cannot run script or leave the frame.
class InertHtmlView extends StatelessWidget {
const InertHtmlView({super.key, required this.html});
import 'artifact_html_links_web.dart';
/// The frame's document cannot be pinched: a pinch over it is a page zoom,
/// which the app's viewport (`user-scalable=no`) refuses, and the sandbox
/// keeps the document out of the app's reach. The full-screen view zooms
/// the live frame with buttons instead.
const bool inertHtmlZoomButtons = true;
/// A sandboxed iframe ([artifactHtmlSandbox]): the document cannot run
/// script, reach the app's origin, submit forms or navigate the app. Its
/// links are fixed first ([artifactHtmlWithInertLinks]): a `#place` scrolls
/// the frame, a web or mail address opens a new tab, anything else is inert.
///
/// The frame scrolls its document itself, by wheel, trackpad and touch.
/// [zoom] scales the live frame as a browser's page zoom would: the frame is
/// laid out 1/zoom as wide and tall and scaled back to fill its box, so the
/// document reflows and still scrolls inside it. In the app, Chrome returns
/// the frame's document to its top when a zoom step resizes it.
///
/// While another route covers this one (a menu, a sheet) the frame stops
/// taking pointers: a platform view takes every click over its area, even
/// where Flutter draws that menu on top.
class InertHtmlView extends StatefulWidget {
const InertHtmlView({
super.key,
required this.html,
this.interactive = false,
this.zoom,
});
final String html;
/// The full-screen view's frame. Pointers already reach the frame directly
/// on the web, inline as in full screen.
final bool interactive;
final ValueListenable<double>? zoom;
@override
Widget build(BuildContext context) => HtmlElementView.fromTagName(
key: ValueKey<int>(html.hashCode),
tagName: 'iframe',
onElementCreated: (element) {
final frame = element as web.HTMLIFrameElement;
frame.setAttribute('sandbox', '');
frame.srcdoc = html.toJS;
frame.style
..border = 'none'
..width = '100%'
..height = '100%'
..backgroundColor = 'white';
},
);
State<InertHtmlView> createState() => _InertHtmlViewState();
}
class _InertHtmlViewState extends State<InertHtmlView> {
web.HTMLIFrameElement? _frame;
bool _covered = false;
@override
void initState() {
super.initState();
widget.zoom?.addListener(_style);
}
@override
void didUpdateWidget(covariant InertHtmlView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.zoom != widget.zoom) {
oldWidget.zoom?.removeListener(_style);
widget.zoom?.addListener(_style);
_style();
}
}
@override
void dispose() {
widget.zoom?.removeListener(_style);
super.dispose();
}
void _style() {
final frame = _frame;
if (frame == null) return;
final zoom = widget.zoom?.value ?? 1;
final size = '${100 / zoom}%';
frame.style
..width = size
..height = size
..transformOrigin = '0 0'
..transform = zoom == 1 ? '' : 'scale($zoom)'
..pointerEvents = _covered ? 'none' : '';
}
@override
Widget build(BuildContext context) {
final covered = !(ModalRoute.of(context)?.isCurrent ?? true);
if (covered != _covered) {
_covered = covered;
_style();
}
return HtmlElementView.fromTagName(
key: ValueKey<int>(widget.html.hashCode),
tagName: 'iframe',
onElementCreated: (element) {
final frame = element as web.HTMLIFrameElement;
frame.setAttribute('sandbox', artifactHtmlSandbox);
frame.srcdoc = artifactHtmlWithInertLinks(widget.html).toJS;
frame.style
..border = 'none'
..backgroundColor = 'white';
_frame = frame;
_style();
},
);
}
}
@@ -0,0 +1,158 @@
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/glass_bar.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/navigation/chevron_pager.dart';
import '../actions/artifact_file_actions.dart';
import '../actions/artifact_file_bridge.dart';
import '../domain/artifact_url.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_viewer_fetch.dart';
const artifactPreviousKey = ValueKey<String>('artifact-previous');
const artifactNextKey = ValueKey<String>('artifact-next');
const artifactFullscreenKey = ValueKey<String>('artifact-fullscreen');
/// The viewer's bottom controls: file transfer, Open, Copy link, Full screen
/// and the pager, in one glass bar above the bottom safe area.
///
/// The inline viewer and the full-screen view draw this same bar; in full
/// screen the Full screen control reads Exit full screen and leaves it.
class ArtifactViewerBar extends StatelessWidget {
const ArtifactViewerBar({
super.key,
required this.page,
required this.resolved,
required this.index,
required this.count,
required this.fetch,
required this.fileBridge,
required this.onOpen,
required this.onCopy,
required this.onPrevious,
required this.onNext,
this.fullscreen = false,
this.onFullscreen,
});
final PagedArtifact page;
final ResolvedArtifactUrl? resolved;
final int index;
final int count;
final ArtifactFetch fetch;
final ArtifactFileBridge fileBridge;
final VoidCallback onOpen;
final VoidCallback onCopy;
final VoidCallback onPrevious;
final VoidCallback onNext;
/// Whether this bar is the full-screen view's.
final bool fullscreen;
/// Enters (inline) or leaves (in full screen) the full-screen view; absent,
/// the control is not drawn.
final VoidCallback? onFullscreen;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final actions = _actions(resolved, onFullscreen);
final pagerMin = count > 1
? 2 * GlassBarMetrics.controlExtent(cupertino)
: 0.0;
final pager = ChevronPager(
index: index,
count: count,
previousLabel: 'Previous artifact',
nextLabel: 'Next artifact',
previousKey: artifactPreviousKey,
nextKey: artifactNextKey,
onPrevious: pagedIndex(index, -1, count) != index ? onPrevious : null,
onNext: pagedIndex(index, 1, count) != index ? onNext : null,
);
return SafeArea(
// The SafeArea already lifts the bar by the inherited bottom inset (a
// shell bar below the pane); adding that clearance again floated the
// bar far above it.
top: false,
minimum: const EdgeInsets.all(8),
// Without a pager the bar is as wide as its actions, so its last
// control keeps the same gap from the bar's end as the first.
child: Align(
alignment: AlignmentDirectional.centerStart,
heightFactor: 1,
child: GlassControlBar(
cupertino: cupertino,
child: LayoutBuilder(
builder: (context, constraints) => Row(
key: const Key('artifact-viewer-actions'),
mainAxisSize: count > 1 ? MainAxisSize.max : MainAxisSize.min,
children: [
// On a narrow window or at large text the actions scroll
// sideways, so the chevrons beside them stay whole.
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: math.max(0, constraints.maxWidth - pagerMin),
),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisSize: MainAxisSize.min,
children: actions,
),
),
),
if (count > 1) Expanded(child: pager),
],
),
),
),
),
);
}
List<Widget> _actions(ResolvedArtifactUrl? resolved, VoidCallback? toggle) =>
[
if (resolved != null && !resolved.external)
ArtifactFileActions(
key: ValueKey<String>(
'viewer-files-${page.group.stageKey}\u0000'
'${page.group.visit}\u0000${page.artifact.url}',
),
artifact: page.artifact,
resolved: resolved,
fetch: fetch,
bridge: fileBridge,
compact: true,
),
if (resolved != null) ...[
ArtifactIconAction(
key: const Key('artifact-open'),
label: 'Open in browser',
icon: Icons.open_in_new,
cupertinoIcon: CupertinoIcons.arrow_up_right_square,
onPressed: onOpen,
),
ArtifactIconAction(
key: const Key('artifact-copy-link'),
label: 'Copy link',
icon: Icons.link,
cupertinoIcon: CupertinoIcons.link,
onPressed: onCopy,
),
],
if (toggle != null)
ArtifactIconAction(
key: artifactFullscreenKey,
label: fullscreen ? 'Exit full screen' : 'Full screen',
icon: fullscreen ? Icons.fullscreen_exit : Icons.fullscreen,
cupertinoIcon: fullscreen
? CupertinoIcons.fullscreen_exit
: CupertinoIcons.fullscreen,
onPressed: toggle,
),
];
}
@@ -1,5 +1,3 @@
import 'dart:async';
import '../../../ui/navigation/chevron_pager.dart';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
@@ -7,15 +5,19 @@ import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/adaptive/floating_bar_layout.dart';
import '../../../ui/adaptive/glass_bar.dart';
import '../actions/artifact_file_actions.dart';
import '../actions/artifact_file_bridge.dart';
import '../domain/artifact_preview.dart';
import '../domain/artifact_url.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_html_view.dart';
import 'artifact_viewer_bar.dart';
import 'artifact_viewer_content.dart';
import 'artifact_viewer_fetch.dart';
export 'artifact_controls_overlay.dart';
export 'artifact_viewer_bar.dart'
show artifactFullscreenKey, artifactNextKey, artifactPreviousKey;
/// One viewer page: the recorded facts, position, live status, preview surface,
/// file transfer actions, external actions and paging controls.
///
@@ -42,8 +44,20 @@ class ArtifactViewerBody extends StatelessWidget {
this.error,
this.status,
this.onRetry,
this.htmlBuilder = defaultArtifactHtml,
this.fullscreen = false,
this.onFullscreen,
});
/// The inert HTML renderer; tests inject a plain stand-in.
final ArtifactHtmlBuilder htmlBuilder;
/// Whether this body is the full-screen view's ([ArtifactViewerBar]).
final bool fullscreen;
/// Enters or leaves the full-screen view.
final VoidCallback? onFullscreen;
/// Loads the current page's preview again after a failure.
final VoidCallback? onRetry;
@@ -79,6 +93,7 @@ class ArtifactViewerBody extends StatelessWidget {
bytes: bytes,
error: error,
onRetry: onRetry,
htmlBuilder: htmlBuilder,
),
),
],
@@ -116,233 +131,25 @@ class ArtifactViewerBody extends StatelessWidget {
// no empty glass bar, and no bottom clearance reserved for one.
if (resolved == null && count <= 1) return swipe;
return FloatingBarOverlay(
// The SafeArea already lifts the bar by the inherited bottom inset (a
// shell bar below the pane); adding that clearance again floated the
// bar far above it.
bar: SafeArea(
top: false,
minimum: const EdgeInsets.all(8),
// Without a pager the bar is as wide as its actions, so its last
// control keeps the same gap from the bar's end as the first.
child: Align(
alignment: AlignmentDirectional.centerStart,
heightFactor: 1,
child: GlassControlBar(
cupertino: usesCupertinoHost(context),
child: Row(
key: const Key('artifact-viewer-actions'),
mainAxisSize: count > 1 ? MainAxisSize.max : MainAxisSize.min,
children: [
if (resolved != null && !resolved.external)
ArtifactFileActions(
key: ValueKey<String>(
'viewer-files-${page.group.stageKey}\u0000'
'${page.group.visit}\u0000${page.artifact.url}',
),
artifact: page.artifact,
resolved: resolved,
fetch: fetch,
bridge: fileBridge,
compact: true,
),
if (resolved != null)
_Actions(resolved: resolved, onOpen: onOpen, onCopy: onCopy),
if (count > 1)
Expanded(
child: _Pager(
index: index,
count: count,
onPrevious: onPrevious,
onNext: onNext,
),
),
],
),
),
),
bar: ArtifactViewerBar(
page: page,
resolved: resolved,
index: index,
count: count,
fetch: fetch,
fileBridge: fileBridge,
onOpen: onOpen,
onCopy: onCopy,
onPrevious: onPrevious,
onNext: onNext,
fullscreen: fullscreen,
onFullscreen: onFullscreen,
),
child: swipe,
);
}
}
/// Open, Copy and the file actions float over the top of the content: shown
/// when the page opens and whenever the content is touched, hidden again after
/// a few seconds without use, so nothing needs scrolling to reach them.
class ArtifactControlsOverlay extends StatefulWidget {
const ArtifactControlsOverlay({
super.key,
required this.controls,
required this.child,
this.hideAfter = const Duration(seconds: 3),
});
final List<Widget> controls;
final Widget child;
final Duration hideAfter;
@override
State<ArtifactControlsOverlay> createState() =>
_ArtifactControlsOverlayState();
}
class _ArtifactControlsOverlayState extends State<ArtifactControlsOverlay> {
bool _shown = true;
Timer? _hide;
@override
void initState() {
super.initState();
_schedule();
}
@override
void dispose() {
_hide?.cancel();
super.dispose();
}
void _schedule() {
_hide?.cancel();
_hide = Timer(widget.hideAfter, () {
if (mounted) setState(() => _shown = false);
});
}
void _show() {
if (!_shown) setState(() => _shown = true);
_schedule();
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final surface = cupertino
? CupertinoColors.systemBackground
.resolveFrom(context)
.withValues(alpha: 0.92)
: Theme.of(
context,
).colorScheme.surfaceContainerHigh.withValues(alpha: 0.94);
return Stack(
children: [
// Any touch on the content brings the controls back.
Positioned.fill(
child: Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) => _show(),
child: widget.child,
),
),
Positioned(
left: 8,
right: 8,
top: 8,
child: IgnorePointer(
ignoring: !_shown,
child: AnimatedOpacity(
key: const Key('artifact-viewer-controls'),
opacity: _shown ? 1 : 0,
duration: const Duration(milliseconds: 200),
child: Listener(
// Using a control keeps the bar up.
onPointerDown: (_) => _schedule(),
child: DecoratedBox(
decoration: BoxDecoration(
color: surface,
borderRadius: BorderRadius.circular(12),
boxShadow: const [
BoxShadow(color: Color(0x22000000), blurRadius: 6),
],
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 2,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
children: widget.controls,
),
),
),
),
),
),
),
],
);
}
}
class _Actions extends StatelessWidget {
const _Actions({
required this.resolved,
required this.onOpen,
required this.onCopy,
});
final ResolvedArtifactUrl resolved;
final VoidCallback onOpen;
final VoidCallback onCopy;
@override
Widget build(BuildContext context) => Row(
mainAxisSize: MainAxisSize.min,
children: [
ArtifactIconAction(
key: const Key('artifact-open'),
label: 'Open',
icon: Icons.open_in_new,
cupertinoIcon: CupertinoIcons.arrow_up_right_square,
onPressed: onOpen,
),
ArtifactIconAction(
key: const Key('artifact-copy-link'),
label: 'Copy link',
icon: Icons.link,
cupertinoIcon: CupertinoIcons.link,
onPressed: onCopy,
),
],
);
}
const artifactPreviousKey = ValueKey<String>('artifact-previous');
const artifactNextKey = ValueKey<String>('artifact-next');
class _Pager extends StatelessWidget {
const _Pager({
required this.index,
required this.count,
required this.onPrevious,
required this.onNext,
});
final int index;
final int count;
final VoidCallback onPrevious;
final VoidCallback onNext;
@override
Widget build(BuildContext context) {
if (count <= 1) return const SizedBox.shrink();
final hasPrevious = pagedIndex(index, -1, count) != index;
final hasNext = pagedIndex(index, 1, count) != index;
return ChevronPager(
index: index,
count: count,
previousLabel: 'Previous artifact',
nextLabel: 'Next artifact',
previousKey: artifactPreviousKey,
nextKey: artifactNextKey,
onPrevious: hasPrevious ? onPrevious : null,
onNext: hasNext ? onNext : null,
);
}
}
/// The viewer's top edge: where this artifact sits in the list, and an
/// information button for its recorded facts.
class ArtifactViewerInfoAction extends StatelessWidget {
@@ -1,13 +1,9 @@
import '../../../ui/adaptive/segmented_bar.dart';
import '../../../ui/theme/app_theme.dart';
import '../../../ui/input/arrow_key_pager.dart';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/input/arrow_key_pager.dart';
import 'artifact_selection_facts.dart';
import '../actions/artifact_file_bridge.dart';
import '../domain/artifact_groups.dart';
@@ -16,9 +12,13 @@ import '../domain/artifact_preview_failure.dart';
import '../domain/artifact_url.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_external_open.dart';
import 'artifact_fullscreen.dart';
import 'artifact_fullscreen_host.dart';
import 'artifact_html_view.dart';
import 'artifact_viewer_body.dart';
import 'artifact_viewer_content.dart';
import 'artifact_viewer_fetch.dart';
import 'artifact_viewer_scaffold.dart';
import 'artifact_visit_list.dart';
/// The full-screen viewer's title, matching the web client's wording.
@@ -47,6 +47,7 @@ class ArtifactViewerPage extends StatefulWidget {
this.markdownBuilder = defaultArtifactMarkdown,
this.openExternal = openArtifactExternally,
this.fileBridge = const ArtifactFileBridge(),
this.htmlBuilder = defaultArtifactHtml,
});
final List<ArtifactGroup> groups;
@@ -64,6 +65,9 @@ class ArtifactViewerPage extends StatefulWidget {
final ArtifactExternalOpen openExternal;
final ArtifactFileBridge fileBridge;
/// The inert HTML renderer; tests inject a plain stand-in.
final ArtifactHtmlBuilder htmlBuilder;
@override
State<ArtifactViewerPage> createState() => _ArtifactViewerPageState();
}
@@ -75,7 +79,8 @@ class _FetchedPreview {
final Uint8List? bytes;
}
class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
class _ArtifactViewerPageState extends State<ArtifactViewerPage>
with ArtifactFullscreenHost<ArtifactViewerPage> {
late final List<PagedArtifact> _pages = pagedArtifacts(
widget.groups,
includeExternalDocuments: widget.includeExternalDocuments,
@@ -117,47 +122,31 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
void _beginLoad({bool initial = false}) {
final generation = ++_generation;
final plan = _plan;
// The first load runs in initState, before there is anything to redraw.
void update(VoidCallback change) => initial ? change() : setState(change);
if (plan == null || !plan.canFetch) {
void clear() {
update(() {
_loading = false;
_error = null;
_fetched = null;
}
if (initial) {
clear();
} else {
setState(clear);
}
});
return;
}
final key = plan.resolved!.url;
final cached = _cache[key];
if (cached != null) {
void apply() {
update(() {
_loading = false;
_error = null;
_fetched = cached;
}
if (initial) {
apply();
} else {
setState(apply);
}
});
return;
}
void start() {
update(() {
_loading = true;
_error = null;
_fetched = null;
}
if (initial) {
start();
} else {
setState(start);
}
});
widget
.fetch(plan.resolved!.uri)
.then(
@@ -226,7 +215,13 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
}
@override
Widget build(BuildContext context) {
Widget build(BuildContext context) => buildFrame(context, fullscreen: false);
/// The viewer's scaffold, inline or as the full-screen view: the same top
/// bar, preview and bottom actions; full screen adds HTML zoom on the web
/// and gives the preview every gesture over it.
@override
Widget buildFrame(BuildContext context, {required bool fullscreen}) {
final page = _page;
final plan = _plan;
final title = page == null
@@ -242,6 +237,11 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
final info = page == null || plan == null
? const <Widget>[]
: <Widget>[
if (fullscreen &&
artifactHtmlZoomButtons &&
plan.kind == ArtifactPreviewKind.html &&
_fetched?.text != null)
...artifactHtmlZoomActions(htmlZoom),
ArtifactViewerInfoAction(
facts: ArtifactSelectionFacts(
group: page.group,
@@ -251,7 +251,7 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
),
),
];
Widget body = page == null || plan == null
final body = page == null || plan == null
? const Center(child: Text('No previewable artifacts recorded.'))
: ArtifactViewerBody(
page: page,
@@ -272,36 +272,26 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
onRetry: _beginLoad,
onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!),
onCopy: plan.resolved == null ? () {} : () => _copy(plan.resolved!),
htmlBuilder: widget.htmlBuilder,
fullscreen: fullscreen,
onFullscreen: fullscreen
? () => Navigator.of(context).maybePop()
: enterFullscreen,
);
// Left/right arrows walk the same list as the Previous/Next buttons.
body = ArrowKeyPager(
// Left/right arrows walk the same list as the Previous/Next buttons,
// wherever focus is on the page, its top bar's controls included.
return ArrowKeyPager(
onPrevious: () => _step(-1),
onNext: () => _step(1),
// Escape closes the viewer, like the web's overlay.
// Escape closes the viewer (or leaves full screen), like the web's
// overlay.
onEscape: () => Navigator.of(context).maybePop(),
child: body,
);
if (usesCupertinoHost(context)) {
return CupertinoPageScaffold(
backgroundColor: AppColors.groupedBackground,
navigationBar: SegmentedBar(
cupertino: true,
title: title,
subtitle: subtitle,
actions: info,
),
child: body,
);
}
return Scaffold(
extendBodyBehindAppBar: true,
appBar: SegmentedBar(
cupertino: false,
child: ArtifactViewerScaffold(
title: title,
subtitle: subtitle,
actions: info,
body: body,
),
body: body,
);
}
}
@@ -0,0 +1,42 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/adaptive/segmented_bar.dart';
import '../../../ui/theme/app_theme.dart';
/// The viewer's page structure on either host: its [SegmentedBar] (the
/// platform's Back, or Close on the full-screen route) over [body].
class ArtifactViewerScaffold extends StatelessWidget {
const ArtifactViewerScaffold({
super.key,
required this.title,
required this.subtitle,
required this.actions,
required this.body,
});
final String title;
final String? subtitle;
final List<Widget> actions;
final Widget body;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final bar = SegmentedBar(
cupertino: cupertino,
title: title,
subtitle: subtitle,
actions: actions,
);
if (cupertino) {
return CupertinoPageScaffold(
backgroundColor: AppColors.groupedBackground,
navigationBar: bar,
child: body,
);
}
return Scaffold(extendBodyBehindAppBar: true, appBar: bar, body: body);
}
}
@@ -215,11 +215,7 @@ class _ChatQuestionCardState extends State<ChatQuestionCard> {
String _statusLine() {
if (_pending) return chatQuestionWaiting;
if (widget.form['cancelled'] == true) return chatQuestionExpired;
final answers = widget.form['answers'];
return answers is Map && answers.isNotEmpty
? chatQuestionAnswered
: chatQuestionClosed;
return chatQuestionSettledStatus(widget.form);
}
String get _submitLabel {
@@ -132,6 +132,15 @@ String chatQuestionOptionLabel(JsonMap option) {
bool chatFormPending(JsonMap form) =>
form['resolved'] != true && form['cancelled'] != true;
/// How a settled form ended: expired, answered, or closed without an answer.
String chatQuestionSettledStatus(JsonMap form) {
if (form['cancelled'] == true) return chatQuestionExpired;
final answers = form['answers'];
return answers is Map && answers.isNotEmpty
? chatQuestionAnswered
: chatQuestionClosed;
}
/// True when an external form URL is one this app can safely show. Mirrors the
/// web's `safeFormURL`: an absolute HTTP(S) URL with a real host and no spaces.
bool chatExternalUrlIsSafe(String raw) {
@@ -145,21 +154,34 @@ bool chatExternalUrlIsSafe(String raw) {
/// Fold one `form` frame into the retained forms, keyed by id. A resolved or
/// cancelled update keeps the recorded answers so the card can show them
/// read-only instead of dropping evidence.
///
/// [raisedIn] is recorded as [chatQuestionRaisedIn] only on the form's first
/// frame: a later resolution arrives during another message and must not move
/// the question.
Map<String, JsonMap> chatFoldQuestionFrame(
Map<String, JsonMap> current,
JsonMap? form,
) {
JsonMap? form, {
String? raisedIn,
}) {
if (form == null) return current;
final id = _text(form['id']);
if (id.isEmpty) return current;
final existing = current[id];
final next = <String, JsonMap>{...current};
final anchor = _text(raisedIn);
next[id] = existing == null
? Map<String, dynamic>.from(form)
? {
...Map<String, dynamic>.from(form),
if (anchor.isNotEmpty) chatQuestionRaisedIn: anchor,
}
: {...existing, ...Map<String, dynamic>.from(form)};
return next;
}
/// Client-only form key: the agent message id the question was raised during.
/// The server never sends it, so folding a frame never overwrites it.
const chatQuestionRaisedIn = 'raised_in_message_id';
/// A stable id for one confirmed answer action on a form. Reusing the same id
/// across a retry lets the send gate recognise a double tap.
String chatQuestionReplyId(String formId, {String action = ''}) =>
@@ -0,0 +1,211 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_turn_chip.dart';
import 'chat_card_styles.dart';
import 'chat_question_card_model.dart';
import 'chat_question_recorded_answers.dart';
/// The settled form of [row], a question card row; null while it still needs
/// the operator or its last answer was refused.
JsonMap? _settled(JsonMap row) {
if (row['kind'] != 'question') return null;
if ('${row['error'] ?? ''}'.trim().isNotEmpty) return null;
final form = row['form'];
if (form is! Map) return null;
final converted = Map<String, dynamic>.from(form);
return chatFormPending(converted) ? null : converted;
}
/// Folds answered and expired question cards out of the card list, the way a
/// turn's tool calls fold into one chip.
///
/// A settled question joins the agent turn it was raised during (the
/// [chatQuestionRaisedIn] message id) as that row's `questions`. Questions
/// naming no turn in view share one `questions` row where the first stood.
/// Pending questions, and ones whose answer was refused, stay full cards.
List<JsonMap> groupSettledQuestions(List<JsonMap> rows) {
final result = <JsonMap>[];
final attached = <int, List<JsonMap>>{};
final loose = <JsonMap>[];
int? looseAt;
for (final row in rows) {
final form = _settled(row);
if (form == null) {
result.add(row);
continue;
}
final turn = _turnOf(result, '${form[chatQuestionRaisedIn] ?? ''}'.trim());
if (turn != null) {
attached.putIfAbsent(turn, () => []).add(form);
} else {
looseAt ??= result.length;
loose.add(form);
}
}
for (final entry in attached.entries) {
result[entry.key] = {...result[entry.key], 'questions': entry.value};
}
if (looseAt != null) {
result.insert(looseAt, {
'kind': 'questions',
'key': 'chat-questions-${loose.first['id']}',
'questions': loose,
});
}
return result;
}
int? _turnOf(List<JsonMap> rows, String messageId) {
if (messageId.isEmpty) return null;
for (var index = rows.length - 1; index >= 0; index--) {
final row = rows[index];
final ids = row['messageIds'];
if (row['kind'] == 'assistant' && ids is List && ids.contains(messageId)) {
return index;
}
}
return null;
}
/// The settled forms a row carries (a turn's or a loose `questions` row's).
List<JsonMap> chatRowQuestions(JsonMap row) {
final questions = row['questions'];
if (questions is! List) return const [];
return [
for (final form in questions)
if (form is Map) Map<String, dynamic>.from(form),
];
}
/// The collapsed line for one settled question: the question and its outcome,
/// `Which database? · Postgres`, `… · +1 more` when several were answered.
String chatQuestionSummary(JsonMap form) {
final fields = chatFormFields(form);
final answers = form['answers'] is Map
? Map<String, dynamic>.from(form['answers'] as Map)
: <String, dynamic>{};
final title = '${form['title'] ?? ''}'.trim();
String question = title.isEmpty ? 'Question' : title;
if (fields.isNotEmpty) {
question = chatQuestionFieldLabel(
fields.first,
'${fields.first['key'] ?? ''}'.trim(),
);
}
if (form['cancelled'] == true) return '$question · Expired';
final answered = [
for (final field in fields)
if (answers.containsKey('${field['key'] ?? ''}'.trim())) field,
];
if (answered.isEmpty) {
return answers.isEmpty ? '$question · Closed' : '$question · Answered';
}
final first = answered.first;
final key = '${first['key'] ?? ''}'.trim();
final more = answers.length - 1;
return [
chatQuestionFieldLabel(first, key),
chatQuestionAnswerText(first, answers[key]),
if (more > 0) '+$more more',
].join(' · ');
}
/// One settled question as the quiet chip a turn's tools use. It opens a
/// native sheet with the full question and the recorded answers.
class ChatQuestionChip extends StatelessWidget {
const ChatQuestionChip({super.key, required this.form});
final JsonMap form;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final color = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final label = chatQuestionSummary(form);
return ChatTurnChip(
chipKey: ValueKey<String>('chat-question-chip-${form['id']}'),
leading: Icon(
cupertino ? CupertinoIcons.question_circle : Icons.help_outline,
size: 14,
color: color,
),
label: label,
color: color,
ellipsizeLabel: true,
semanticsLabel: 'Question: $label, expand for details',
sheet: _QuestionSheet(form: form),
);
}
}
/// The chips for [row]'s settled questions, one per question.
List<Widget> chatQuestionChips(JsonMap row) => [
for (final form in chatRowQuestions(row)) ChatQuestionChip(form: form),
];
/// A loose `questions` row: its chips on the agent's side.
class ChatQuestionsRow extends StatelessWidget {
const ChatQuestionsRow({super.key, required this.row});
final JsonMap row;
@override
Widget build(BuildContext context) => Align(
alignment: AlignmentDirectional.centerStart,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: chatQuestionChips(row),
),
);
}
class _QuestionSheet extends StatelessWidget {
const _QuestionSheet({required this.form});
final JsonMap form;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
final title = '${form['title'] ?? ''}'.trim();
return DefaultTextStyle.merge(
style: style,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.8,
),
child: ListView(
key: const Key('chat-question-sheet'),
shrinkWrap: true,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
children: [
Text(
title.isEmpty ? 'Question' : title,
style: chatCardTitleStyle(context, cupertino),
),
Text(
chatQuestionSettledStatus(form),
style: chatCardSecondaryStyle(context, cupertino),
),
...chatQuestionRecordedAnswers(
context: context,
form: form,
cupertino: cupertino,
),
],
),
),
);
}
}
@@ -24,8 +24,8 @@ List<Widget> chatQuestionRecordedAnswers({
widgets.add(
_recorded(
context,
_fieldLabel(field, key),
_answerText(field, answers[key]),
chatQuestionFieldLabel(field, key),
chatQuestionAnswerText(field, answers[key]),
cupertino,
),
);
@@ -33,7 +33,12 @@ List<Widget> chatQuestionRecordedAnswers({
for (final entry in answers.entries) {
if (shown.contains(entry.key)) continue;
widgets.add(
_recorded(context, entry.key, _answerText(null, entry.value), cupertino),
_recorded(
context,
entry.key,
chatQuestionAnswerText(null, entry.value),
cupertino,
),
);
}
if (widgets.isEmpty) {
@@ -49,7 +54,7 @@ List<Widget> chatQuestionRecordedAnswers({
/// The field's display label, falling back past blank recorded strings the same
/// way the pending field does.
String _fieldLabel(JsonMap field, String key) {
String chatQuestionFieldLabel(JsonMap field, String key) {
for (final candidate in [field['title'], field['description']]) {
final text = '${candidate ?? ''}'.trim();
if (text.isNotEmpty) return text;
@@ -74,7 +79,8 @@ Widget _recorded(
),
);
String _answerText(JsonMap? field, Object? value) {
/// A recorded answer as display text: option labels, Yes/No, list joined.
String chatQuestionAnswerText(JsonMap? field, Object? value) {
final values = value is List ? value : [value];
final boolean = field != null && '${field['type'] ?? ''}' == 'boolean';
return values
@@ -10,7 +10,8 @@ import 'chat_question_card_model.dart';
/// gates, so the controller itself stays about messages and live turn state.
///
/// The web drops an approval or form once it is resolved. This app keeps the
/// latest settled cards as read-only evidence, which is an intentional addition;
/// latest settled cards as read-only evidence, collapsed into their turn like
/// tool calls (see `chat_permission_group.dart`, `chat_question_group.dart`);
/// [settledLimit] bounds that history so a long session cannot grow without
/// limit while pending cards are never dropped.
class ChatThreadCards {
@@ -136,11 +137,12 @@ class ChatThreadCards {
}
/// Fold one `form` event. A folded update keeps a settled form's recorded
/// answers for the read-only card.
void foldForm(JsonMap form) {
/// answers for the collapsed row. [raisedIn] is the agent message the first
/// frame arrived during; it places the answered question in its turn.
void foldForm(JsonMap form, {String? raisedIn}) {
final id = '${form['id'] ?? ''}'.trim();
if (id.isEmpty) return;
final next = chatFoldQuestionFrame(_forms, form);
final next = chatFoldQuestionFrame(_forms, form, raisedIn: raisedIn);
if (identical(next, _forms)) return;
_forms
..clear()
@@ -369,7 +369,10 @@ class ChatThreadController extends ChangeNotifier {
if (body['kind'] == 'form') {
final form = body['form'];
if (form is! Map) return;
_cards.foldForm(Map<String, dynamic>.from(form));
_cards.foldForm(
Map<String, dynamic>.from(form),
raisedIn: _answeringMessageId(),
);
return;
}
final current = _thread;
@@ -415,6 +418,21 @@ class ChatThreadController extends ChangeNotifier {
].any((key) => usage[key] != null);
}
/// The agent message a question frame arrives during: the streamed reply,
/// else the last answer when it is the agent's. A question raised before the
/// reply starts names none rather than an older turn.
String? _answeringMessageId() {
final live = _liveAssistantMessageId;
if (live != null && live.isNotEmpty) return live;
for (final message in _messages.reversed) {
if (chatInjectedKind(message) != null) continue;
if (message['role'] != 'assistant') return null;
final id = '${message['id'] ?? ''}'.trim();
return id.isEmpty ? null : id;
}
return null;
}
/// The pushed envelope body, or null for another message type. The server
/// wraps `chat_event` in the typed envelope; domain code never sees the
/// transport fields.
@@ -52,6 +52,7 @@ import 'chat_transcript_cache.dart';
import 'chat_transcript_scroll_view.dart';
import 'chat_permission_card_model.dart';
import 'chat_permission_group.dart';
import 'chat_question_group.dart';
import 'chat_transcript_card.dart';
/// One read-only conversation: the controller's transcript in the order the
@@ -851,22 +852,25 @@ class _ChatThreadViewState extends State<ChatThreadView> {
permissionErrorFor: _controller.permissionErrorFor,
formErrorFor: _controller.questionErrorFor,
);
// Answered approvals fold into their turn's chips, like tool calls.
final allRows = groupSettledPermissions(
transcriptRows(
messages,
trailing: cards,
running:
_controller.running &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
awaitingResponse:
_controller.awaitingResponse &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
liveMessageId: _controller.liveAssistantMessageId,
// Answered approvals and questions fold into their turn's chips, like
// tool calls; only cards still waiting on the operator stay full cards.
final allRows = groupSettledQuestions(
groupSettledPermissions(
transcriptRows(
messages,
trailing: cards,
running:
_controller.running &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
awaitingResponse:
_controller.awaitingResponse &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
liveMessageId: _controller.liveAssistantMessageId,
),
),
);
// A transcript held from before a socket gap may still say a compaction is
@@ -1262,6 +1266,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
}
if (kind == 'system_notice') return ChatSystemNoticeLine(row: row);
if (kind == 'task_notices') return ChatTaskNoticesGroup(row: row);
if (kind == 'questions') return ChatQuestionsRow(row: row);
if (kind == 'permission' || kind == 'question') {
return ChatTranscriptCard(
row: row,
@@ -1273,6 +1278,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
final chips = [
if (permissions is List<ChatPermissionCardData> && permissions.isNotEmpty)
ChatPermissionsChip(permissions: permissions),
...chatQuestionChips(row),
];
if (kind == 'permissions') {
return Align(
@@ -0,0 +1,43 @@
import '../../../core/api_gateway.dart';
/// One chat's live activity as the server observes it: a turn in flight and
/// how many background tasks (shells, background commands, subagents) still
/// run. It rides on each `chat_sessions` row as `activity` and is pushed to
/// every connection as `chat_activity` on each change. [seq] orders one
/// chat's snapshots across the list and the pushes; the larger one is newer.
typedef ChatListActivity = ({
String sessionId,
bool turnRunning,
int backgroundTasks,
int seq,
});
/// Reads an `activity` row field or a `chat_activity` body. [sessionId] names
/// the row when the body omits it. Anything malformed is null, so an older
/// server (which sends neither) leaves the list exactly as before.
ChatListActivity? chatListActivityOf(Object? value, {String? sessionId}) {
if (value is! Map) return null;
final named = value['session_id'];
final id = sessionId ?? (named is String ? named : '');
if (id.isEmpty) return null;
final tasks = value['background_tasks'];
final seq = value['seq'];
return (
sessionId: id,
turnRunning: value['turn_running'] == true,
backgroundTasks: tasks is num && tasks > 0 ? tasks.toInt() : 0,
seq: seq is num ? seq.toInt() : 0,
);
}
/// The row keys the list controller derives from the activity.
JsonMap chatListActivityRowFields(ChatListActivity activity) => {
'running': activity.turnRunning,
'background_tasks': activity.backgroundTasks,
};
/// Running background tasks of a list row; 0 when unknown.
int chatSessionBackgroundTasks(JsonMap session) {
final tasks = session['background_tasks'];
return tasks is int && tasks > 0 ? tasks : 0;
}
@@ -8,6 +8,7 @@ import '../../../../core/servers/server_scope.dart';
import '../../../../core/transport/connection_state.dart';
import '../../../attention/runtime/attention_ack_sync.dart';
import '../../data/chat_repository.dart';
import '../../domain/chat_list_activity.dart';
import '../../domain/chat_sessions.dart';
import 'chat_session_local.dart';
import 'session_attention.dart';
@@ -65,6 +66,9 @@ class ChatSessionsController extends ChangeNotifier {
Future<void> _persistTail = Future<void>.value();
int _runningRevision = 0;
final Map<String, ({int revision, bool running})> _runningFrames = {};
// The newest server activity applied per chat (list row or push), so an
// older snapshot that arrives later never replaces it.
final Map<String, ChatListActivity> _activity = {};
StreamSubscription<JsonMap>? _frameSubscription;
String? activeSessionId;
@@ -75,6 +79,9 @@ class ChatSessionsController extends ChangeNotifier {
void _onFrame(JsonMap frame) {
if (frame['type'] == 'chat_session_changed') return _sessionChanged(frame);
if (frame['type'] == 'chat_activity') {
return _activityChanged(frame['chat_activity']);
}
final effect = chatSessionFrameEffect(frame);
if (effect == null) return;
final id = effect.sessionId;
@@ -130,6 +137,58 @@ class ChatSessionsController extends ChangeNotifier {
if (found) _notify();
}
/// The server pushed a chat's turn state and background-task count. It
/// reaches every connection, so every listed chat's spinner and
/// background-task badge follow it, not only the chat open here. A push
/// older than the snapshot already applied is ignored.
void _activityChanged(Object? body) {
final activity = chatListActivityOf(body);
if (activity == null || _disposed) return;
final id = activity.sessionId;
if (activity.seq <= (_activity[id]?.seq ?? 0)) return;
_activity[id] = activity;
_runningFrames[id] = (
revision: ++_runningRevision,
running: activity.turnRunning,
);
final fields = chatListActivityRowFields(activity);
var changed = false;
_sessions = [
for (final row in _sessions)
if ('${row['id'] ?? ''}' == id &&
(row['running'] != fields['running'] ||
row['background_tasks'] != fields['background_tasks']))
() {
changed = true;
return {...row, ...fields};
}()
else
row,
];
if (changed) _notify();
}
/// A listed row with the newest activity known for it: the row's own
/// `activity` unless a newer push was already applied, then a turn frame
/// this connection saw during the read. An older server sends no
/// `activity`, so only the turn frames apply, as before.
JsonMap _withActivity(JsonMap row, int runningRevision) {
final id = '${row['id'] ?? ''}';
var next = row;
final listed = chatListActivityOf(row['activity'], sessionId: id);
if (listed != null) {
final known = _activity[id];
final activity = known != null && known.seq > listed.seq ? known : listed;
_activity[id] = activity;
next = {...row, ...chatListActivityRowFields(activity)};
}
final frame = _runningFrames[id];
if ((frame?.revision ?? 0) > runningRevision) {
next = {...next, 'running': frame!.running};
}
return next;
}
void _bindAckSync(AttentionAckSync? sync) {
if (identical(sync, _ackSync)) return;
_ackSync?.removeListener(_ackChanged);
@@ -246,6 +305,7 @@ class ChatSessionsController extends ChangeNotifier {
if (identical(next.gateway, repository.gateway)) return;
repository = next;
_runningFrames.clear();
_activity.clear();
_listenFrames();
_bindAckSync(attentionAckSyncOf(next.gateway) ?? _ackSync);
refresh();
@@ -265,12 +325,7 @@ class ChatSessionsController extends ChangeNotifier {
final sessions = await repository.sessions();
if (generation != _generation) return;
_sessions = [
for (final row in sessions)
if ((_runningFrames['${row['id'] ?? ''}']?.revision ?? 0) >
runningRevision)
{...row, 'running': _runningFrames['${row['id'] ?? ''}']!.running}
else
row,
for (final row in sessions) _withActivity(row, runningRevision),
];
_seedLocal();
_loading = false;
@@ -0,0 +1,93 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// The corner badge a chat's avatar wears for its live activity: the
/// platform's activity indicator while a turn runs; otherwise, while
/// background tasks still run, a quiet muted glyph (never a second spinner).
/// Null when the chat is idle.
Widget? chatSessionActivityBadge({
required bool cupertino,
required bool running,
required int backgroundTasks,
}) {
if (running) {
return Semantics(
key: const Key('chat-row-working'),
label: 'Chat is working',
child: _WorkingBadge(cupertino: cupertino),
);
}
if (backgroundTasks <= 0) return null;
final label = 'Background tasks running ($backgroundTasks)';
// Hover shows the tooltip on a pointer device; a touch long press stays the
// row's own gesture.
return Tooltip(
key: const Key('chat-row-background'),
message: label,
triggerMode: TooltipTriggerMode.manual,
excludeFromSemantics: true,
child: Semantics(
label: label,
child: _BackgroundBadge(cupertino: cupertino),
),
);
}
/// The badge's own disc in the surface colour, so it reads over any avatar.
class _BadgeDisc extends StatelessWidget {
const _BadgeDisc({required this.cupertino, required this.child});
final bool cupertino;
final Widget child;
@override
Widget build(BuildContext context) {
final background = cupertino
? CupertinoColors.systemBackground.resolveFrom(context)
: Theme.of(context).colorScheme.surface;
return DecoratedBox(
decoration: BoxDecoration(color: background, shape: BoxShape.circle),
child: Padding(padding: const EdgeInsets.all(2), child: child),
);
}
}
class _WorkingBadge extends StatelessWidget {
const _WorkingBadge({required this.cupertino});
final bool cupertino;
@override
Widget build(BuildContext context) {
return _BadgeDisc(
cupertino: cupertino,
child: cupertino
? const CupertinoActivityIndicator(radius: 6)
: const SizedBox.square(
dimension: 12,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
}
class _BackgroundBadge extends StatelessWidget {
const _BackgroundBadge({required this.cupertino});
final bool cupertino;
@override
Widget build(BuildContext context) {
final color = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
return _BadgeDisc(
cupertino: cupertino,
child: Icon(
cupertino ? CupertinoIcons.ellipsis_circle_fill : Icons.pending,
size: 12,
color: color,
),
);
}
}
@@ -18,23 +18,20 @@ ChatSessionFrameEffect? chatSessionFrameEffect(JsonMap frame) {
if (event is! Map) return null;
id = event['session_id'] is String ? event['session_id'] as String : null;
final kind = event['kind'];
// A badge means content to read, not transport/activity churn: assistant
// text, another client's user message, a returned tool result, or a pending
// form. Reasoning, starts, steps, shells, compaction and usage are not unread.
// A badge means the agent said something to read or is waiting on the
// operator: visible assistant reply text or a pending form. Tool calls and
// their results, harness notices and agent reports (`message_kind`), the
// operator's own prompts from any device, reasoning, steps, shells,
// compaction and usage are turn activity, never unread.
if (kind == 'text') {
attention = '${event['delta'] ?? ''}'.isNotEmpty;
} else if (kind == 'user') {
attention = true;
attention =
'${event['delta'] ?? ''}'.trim().isNotEmpty &&
'${event['message_kind'] ?? ''}'.isEmpty;
} else if (kind == 'tool') {
final part = event['part'];
final state = part is Map ? part['state'] : null;
if (state is Map) {
final status = state['status'];
attention =
(status == 'completed' || status == 'error') &&
((state['content'] is List &&
(state['content'] as List).isNotEmpty) ||
state['error'] != null);
if (status == 'running' || status == 'streaming') running = true;
}
} else if (kind == 'form') {
@@ -6,10 +6,12 @@ import '../../../../ui/layout/app_list_avatar.dart';
import '../../../../ui/layout/app_list_row.dart';
import '../../../../ui/text/relative_time_label.dart';
import '../../domain/chat_colors.dart';
import '../../domain/chat_list_activity.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_color_palette.dart';
import 'session_actions.dart';
import 'session_activity_badge.dart';
import 'session_harness_icon.dart';
import 'session_row_style.dart';
@@ -68,6 +70,9 @@ class ChatSessionRow extends StatelessWidget {
leading: ChatSessionAvatar(
session: session,
running: session['running'] == true && !unseen,
backgroundTasks: session['running'] == true
? 0
: chatSessionBackgroundTasks(session),
selected: selected,
),
// The star rides in the title's own text, so a narrow row ellipsises
@@ -149,17 +154,20 @@ class _Star extends StatelessWidget {
/// The chat's harness mark in a filled circle, like a contact avatar. A
/// running chat carries a small activity badge on the avatar's corner instead
/// of a line of its own; a selected chat's avatar takes the accent fill.
/// of a line of its own, and an idle chat whose background tasks still run a
/// quieter one; a selected chat's avatar takes the accent fill.
class ChatSessionAvatar extends StatelessWidget {
const ChatSessionAvatar({
super.key,
required this.session,
this.running = false,
this.backgroundTasks = 0,
this.selected = false,
});
final JsonMap session;
final bool running;
final int backgroundTasks;
final bool selected;
@override
@@ -192,39 +200,12 @@ class ChatSessionAvatar extends StatelessWidget {
return AppListAvatar(
foreground: mark,
background: fill,
badge: running
? Semantics(
key: const Key('chat-row-working'),
label: 'Chat is working',
child: _WorkingBadge(cupertino: cupertino),
)
: null,
badge: chatSessionActivityBadge(
cupertino: cupertino,
running: running,
backgroundTasks: backgroundTasks,
),
child: SessionHarnessIcon(session: session, color: mark),
);
}
}
class _WorkingBadge extends StatelessWidget {
const _WorkingBadge({required this.cupertino});
final bool cupertino;
@override
Widget build(BuildContext context) {
final background = cupertino
? CupertinoColors.systemBackground.resolveFrom(context)
: Theme.of(context).colorScheme.surface;
return DecoratedBox(
decoration: BoxDecoration(color: background, shape: BoxShape.circle),
child: Padding(
padding: const EdgeInsets.all(2),
child: cupertino
? const CupertinoActivityIndicator(radius: 6)
: const SizedBox.square(
dimension: 12,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
);
}
}
@@ -7,6 +7,25 @@ import '../../../../ui/adaptive/host.dart';
import 'chat_link_browser_menu.dart';
import 'chat_links.dart';
/// A link's tap recognizer. A primary mouse press on a link belongs to the
/// link, as a press on a web page's anchor does: otherwise the selection area
/// claims the press as a selection drag once the pointer moves
/// [kPrecisePointerPanSlop] (2 px), so an ordinary click with a little hand or
/// trackpad movement opened nothing. The click still cancels past the tap
/// slop, and a selection drag that starts on plain text still crosses links.
/// Touch, stylus and secondary presses keep competing in the arena, so a long
/// press still selects and offers Copy link.
class _LinkTapRecognizer extends TapGestureRecognizer {
@override
void addAllowedPointer(PointerDownEvent event) {
super.addAllowedPointer(event);
if (event.kind == PointerDeviceKind.mouse &&
event.buttons == kPrimaryMouseButton) {
resolve(GestureDisposition.accepted);
}
}
}
/// The link spans of one selectable text block, and the selection area that
/// hosts them. A tap opens the link. A long press (or a native right-click)
/// shows the selection menu with "Copy link" added; on the web, where the
@@ -24,7 +43,7 @@ class ChatLinkSpans {
static bool? debugOwnsSecondaryClick;
final VoidCallback onChanged;
final Map<String, TapGestureRecognizer> _recognizers = {};
final Map<String, _LinkTapRecognizer> _recognizers = {};
final ContextMenuController _linkMenu = ContextMenuController();
String? _hovered;
String? _pressed;
@@ -45,7 +64,7 @@ class ChatLinkSpans {
final uri = chatLinkUri(target);
if (uri == null) return TextSpan(children: label);
final url = uri.toString();
final recognizer = _recognizers.putIfAbsent(url, TapGestureRecognizer.new)
final recognizer = _recognizers.putIfAbsent(url, _LinkTapRecognizer.new)
..onTapDown = (_) {
_pressed = url;
}
@@ -14,6 +14,7 @@ class ChatTurnChip extends StatelessWidget {
required this.color,
required this.semanticsLabel,
required this.sheet,
this.ellipsizeLabel = false,
});
final Key chipKey;
@@ -23,6 +24,10 @@ class ChatTurnChip extends StatelessWidget {
final String semanticsLabel;
final Widget sheet;
/// Shrink a long label to one ellipsized line. Only for a chip whose parent
/// bounds its width (a turn footer's Wrap, an aligned row).
final bool ellipsizeLabel;
@override
Widget build(BuildContext context) {
final cupertino =
@@ -32,7 +37,10 @@ class ChatTurnChip extends StatelessWidget {
children: [
leading,
const SizedBox(width: 6),
Text(label, style: TextStyle(color: color, fontSize: 13)),
if (ellipsizeLabel)
Flexible(child: _label(maxLines: 1, overflow: TextOverflow.ellipsis))
else
_label(),
Icon(
cupertino ? CupertinoIcons.chevron_up : Icons.expand_less,
size: 14,
@@ -73,6 +81,13 @@ class ChatTurnChip extends StatelessWidget {
);
}
Text _label({int? maxLines, TextOverflow? overflow}) => Text(
label,
maxLines: maxLines,
overflow: overflow,
style: TextStyle(color: color, fontSize: 13),
);
Future<void> _open(BuildContext context, bool cupertino) {
if (cupertino) {
return showCupertinoModalPopup<void>(
+11 -5
View File
@@ -17,9 +17,15 @@ const double kAppListRowMinimalWidth = 160;
/// The rows' horizontal inset and the gap after the avatar.
const double kAppListRowInset = 16;
const double _avatarGap = 12;
const double _avatarGap = 14;
const double _compactAvatarGap = 8;
/// The rows' vertical breathing room: the padding above and below the
/// content and the gap between the title and the lines under it. Rows stay
/// content-driven; these only space them out so they are easier to hit.
const double kAppListRowVerticalPadding = 13;
const double _lineGap = 4;
/// Keys on a row's highlight surface and inset divider, for tests.
const appListRowSurfaceKey = ValueKey<String>('app-list-row-surface');
const appListRowDividerKey = ValueKey<String>('app-list-row-divider');
@@ -135,8 +141,8 @@ class AppListRow extends StatelessWidget {
padding: EdgeInsetsDirectional.only(
start: start,
end: showMenu ? 4 : kAppListRowInset,
top: 10,
bottom: 10,
top: kAppListRowVerticalPadding,
bottom: kAppListRowVerticalPadding,
),
child: Row(
children: [
@@ -285,7 +291,7 @@ class AppListRow extends StatelessWidget {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [titleLine, const SizedBox(height: 2), timeLine],
children: [titleLine, const SizedBox(height: _lineGap), timeLine],
);
}
return Column(
@@ -293,7 +299,7 @@ class AppListRow extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
titleLine,
const SizedBox(height: 2),
const SizedBox(height: _lineGap),
Row(
children: [
if (subtitleLeading != null)