From 4534283f1d2618e798acebcc3a187575a0400c35 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 20:01:13 +0000 Subject: [PATCH 01/18] WIP compact --- .../changes/widgets/diff_search_bar.dart | 3 +- .../conversation/chat_bar_control_style.dart | 9 +- .../chat/conversation/chat_composer_bar.dart | 7 +- .../chat/conversation/chat_find_bar.dart | 3 +- .../shell/chat_shell_terminal_find_bar.dart | 3 +- .../chat/ui/sessions/chat_adaptive.dart | 3 +- .../ui/sessions/chat_compact_sidebar.dart | 3 +- .../chat/ui/sessions/session_row_content.dart | 3 +- .../ui/transcript/chat_automated_prompt.dart | 15 +- .../chat/ui/transcript/chat_code_hover.dart | 6 +- .../ui/transcript/chat_markdown_view.dart | 14 +- .../ui/transcript/chat_message_bubble.dart | 23 +- .../chat/ui/transcript/chat_message_view.dart | 10 +- .../transcript/chat_turn_activity_view.dart | 21 +- .../chat/ui/transcript/chat_turn_chip.dart | 4 +- .../graph/widgets/definition_graph_view.dart | 1 + .../graph/widgets/graph_canvas_style.dart | 21 ++ .../graph/widgets/graph_stage_node.dart | 27 ++- .../graph/widgets/run_graph_view.dart | 1 + .../runs/ui/run_check_output_view.dart | 3 +- .../runs/ui/run_detail_tab_bodies.dart | 3 +- .../features/runs/ui/run_detail_timeline.dart | 3 +- .../search/ui/search_result_view.dart | 7 +- .../settings/settings_design_section.dart | 14 +- app/lib/features/settings/settings_group.dart | 24 +- .../features/settings/settings_layout.dart | 13 + .../features/settings/settings_page_body.dart | 2 +- .../settings/settings_search_page.dart | 6 +- app/lib/shell/adaptive_shell.dart | 2 +- app/lib/shell/navigation_rail.dart | 87 ++++--- app/lib/shell/windows/window_frame.dart | 36 ++- app/lib/shell/windows/window_host.dart | 2 +- app/lib/shell/windows/window_navigator.dart | 10 +- app/lib/ui/adaptive/segmented_bar.dart | 2 +- app/lib/ui/adaptive/segmented_bar_pieces.dart | 22 +- app/lib/ui/input/app_search_field.dart | 7 +- app/lib/ui/layout/app_list_avatar.dart | 18 +- app/lib/ui/layout/app_list_row.dart | 83 ++++++- app/lib/ui/theme/app_design.dart | 17 +- app/lib/ui/theme/app_design_styles.dart | 7 + app/lib/ui/theme/app_design_tokens.dart | 13 + app/lib/ui/theme/compact_controls.dart | 220 +++++++++++++++++ app/lib/ui/theme/compact_theme.dart | 47 ++++ app/lib/ui/theme/compact_typography.dart | 36 +++ app/lib/ui/theme/design_density.dart | 119 +++++++++ .../settings_design_section_test.dart | 32 +++ app/test/ui/layout/app_list_row_test.dart | 1 + app/test/ui/theme/compact_design_test.dart | 174 ++++++++++++++ app/test/ui/theme/compact_rendering_test.dart | 225 ++++++++++++++++++ 49 files changed, 1282 insertions(+), 130 deletions(-) create mode 100644 app/lib/ui/theme/compact_controls.dart create mode 100644 app/lib/ui/theme/compact_theme.dart create mode 100644 app/lib/ui/theme/compact_typography.dart create mode 100644 app/lib/ui/theme/design_density.dart create mode 100644 app/test/ui/theme/compact_design_test.dart create mode 100644 app/test/ui/theme/compact_rendering_test.dart diff --git a/app/lib/features/changes/widgets/diff_search_bar.dart b/app/lib/features/changes/widgets/diff_search_bar.dart index 4aa57ca9..c1765780 100644 --- a/app/lib/features/changes/widgets/diff_search_bar.dart +++ b/app/lib/features/changes/widgets/diff_search_bar.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import '../../../ui/theme/app_design_tokens.dart'; /// The find-in-diff field `/` opens: the query, "3 of 12", previous and next /// match, and close. Enter goes to the next match, Shift+Enter to the @@ -37,7 +38,7 @@ class DiffSearchBar extends StatelessWidget { : '$position of $count'; return Material( elevation: 3, - borderRadius: BorderRadius.circular(28), + borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(28)), color: Theme.of(context).colorScheme.surfaceContainerHigh, child: Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 4, 4), diff --git a/app/lib/features/chat/conversation/chat_bar_control_style.dart b/app/lib/features/chat/conversation/chat_bar_control_style.dart index 5bd04969..3f108bfb 100644 --- a/app/lib/features/chat/conversation/chat_bar_control_style.dart +++ b/app/lib/features/chat/conversation/chat_bar_control_style.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; +import '../../../ui/theme/app_design_tokens.dart'; import 'chat_bar_tint.dart'; /// The conversation bar's model and mode controls read as the bar's other @@ -18,7 +19,13 @@ ButtonStyle chatBarTextButtonStyle( // The same 12 px each side as an icon button's glyph inside its 48 px // target, so text sits off its hover/press shape as it does top and bottom. padding: compact ? null : chatBarButtonPadding, - minimumSize: compact ? null : const Size.square(kMinInteractiveDimension), + minimumSize: compact + ? null + : Size.square( + AppDesignTokens.of(context).density.dense + ? 32 + : kMinInteractiveDimension, + ), ); /// Horizontal padding inside the bar's text buttons (model, mode). diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index 863ea02d..e5f91d64 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -1329,7 +1329,12 @@ class _ChatComposerBarState extends State { // The pill draws the field's surface; the field adds no border. border: InputBorder.none, isDense: true, - contentPadding: const EdgeInsets.symmetric(vertical: 12), + // A dense design's slim composer: one line in a 40px pill, as tall + // as its 32px controls (its compact density takes 4px off each of + // these 10). + contentPadding: EdgeInsets.symmetric( + vertical: AppDesignTokens.of(context).density.dense ? 10 : 12, + ), ), ); } diff --git a/app/lib/features/chat/conversation/chat_find_bar.dart b/app/lib/features/chat/conversation/chat_find_bar.dart index 4fbf3461..60836fb5 100644 --- a/app/lib/features/chat/conversation/chat_find_bar.dart +++ b/app/lib/features/chat/conversation/chat_find_bar.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'chat_find_controller.dart'; +import '../../../ui/theme/app_design_tokens.dart'; /// The chat's find bar, like the terminal's: the query field, the match /// count, Match case, the older/newer and close buttons. Matches count from @@ -68,7 +69,7 @@ class _ChatFindBarState extends State { child: Material( elevation: 3, color: scheme.surfaceContainerHigh, - borderRadius: BorderRadius.circular(8), + borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(8)), child: Padding( padding: const EdgeInsetsDirectional.only(start: 12, end: 4), child: ListenableBuilder( diff --git a/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart b/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart index 3096fb14..1327d887 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'chat_shell_terminal_find.dart'; +import '../../../ui/theme/app_design_tokens.dart'; /// The terminal's find bar: the query field (Enter finds the next match, /// Shift+Enter the previous, Esc closes), the match count, Match case and @@ -69,7 +70,7 @@ class _ChatShellTerminalFindBarState extends State { child: Material( elevation: 3, color: scheme.surfaceContainerHigh, - borderRadius: BorderRadius.circular(8), + borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(8)), child: Padding( padding: const EdgeInsetsDirectional.only(start: 12, end: 4), child: ListenableBuilder( diff --git a/app/lib/features/chat/ui/sessions/chat_adaptive.dart b/app/lib/features/chat/ui/sessions/chat_adaptive.dart index 6dcdc415..c875ff99 100644 --- a/app/lib/features/chat/ui/sessions/chat_adaptive.dart +++ b/app/lib/features/chat/ui/sessions/chat_adaptive.dart @@ -1,6 +1,7 @@ import '../../../../ui/adaptive/segmented_bar_overflow.dart'; import 'package:flutter/material.dart'; import '../../../../ui/status/app_spinner.dart'; +import '../../../../ui/theme/app_design_tokens.dart'; class ChatBarAction extends StatelessWidget implements SegmentedOverflowable { const ChatBarAction({ @@ -220,7 +221,7 @@ class ChatUndoBar extends StatelessWidget { ); return Material( elevation: 3, - borderRadius: BorderRadius.circular(8), + borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(8)), color: Theme.of(context).colorScheme.surfaceContainerHighest, child: content, ); diff --git a/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart b/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart index 53b2b3d4..152f817c 100644 --- a/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart +++ b/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart @@ -14,6 +14,7 @@ import 'session_row_style.dart'; import '../../domain/chat_list_activity.dart'; import 'chat_sessions_body.dart'; import 'chat_sessions_controller.dart'; +import '../../../../ui/theme/app_design_tokens.dart'; /// A small, scrollable device-local rail. Full titles remain accessible. class ChatCompactSidebar extends StatelessWidget { @@ -147,7 +148,7 @@ class ChatCompactSidebar extends StatelessWidget { data: row, feedback: Material( elevation: 4, - borderRadius: BorderRadius.circular(20), + borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(20)), child: Chip( avatar: ChatCompactAvatar( title: title, diff --git a/app/lib/features/chat/ui/sessions/session_row_content.dart b/app/lib/features/chat/ui/sessions/session_row_content.dart index be8aebb8..e0060fbc 100644 --- a/app/lib/features/chat/ui/sessions/session_row_content.dart +++ b/app/lib/features/chat/ui/sessions/session_row_content.dart @@ -18,6 +18,7 @@ import 'session_harness_icon.dart'; import 'session_pane_menu.dart'; import 'session_row_style.dart'; import 'chat_awaiting.dart'; +import '../../../../ui/theme/app_design_tokens.dart'; /// One chat in the list, in the app's shared row on both hosts: the harness /// avatar, the title with its recency, one muted line, and the actions menu. @@ -90,7 +91,7 @@ class ChatSessionRow extends StatelessWidget { data: session, feedback: Material( elevation: 4, - borderRadius: BorderRadius.circular(20), + borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(20)), child: Chip( avatar: ChatSessionAvatar(session: session), label: Text(chatSessionTitle(session)), diff --git a/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart b/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart index 23b89ad3..f7693c71 100644 --- a/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart +++ b/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart @@ -69,7 +69,9 @@ class ChatAutomatedPromptCard extends StatelessWidget { ], ), ); - final transcript = AppDesignTokens.of(context).transcript; + final tokens = AppDesignTokens.of(context); + final density = tokens.density; + final transcript = tokens.transcript; final card = transcript == TranscriptStyle.manuscript ? PaperEditorialNote( label: label, @@ -84,11 +86,18 @@ class ChatAutomatedPromptCard extends StatelessWidget { color: scheme.surfaceContainerLow, clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( - borderRadius: const BorderRadius.all(Radius.circular(16)), + borderRadius: tokens.corners( + const BorderRadius.all(Radius.circular(16)), + ), side: BorderSide(color: scheme.outlineVariant), ), child: Padding( - padding: const EdgeInsets.fromLTRB(14, 8, 14, 10), + padding: EdgeInsets.fromLTRB( + density.inset(14), + density.space(8), + density.inset(14), + density.space(10), + ), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, diff --git a/app/lib/features/chat/ui/transcript/chat_code_hover.dart b/app/lib/features/chat/ui/transcript/chat_code_hover.dart index b3c7ecfc..f5f1f761 100644 --- a/app/lib/features/chat/ui/transcript/chat_code_hover.dart +++ b/app/lib/features/chat/ui/transcript/chat_code_hover.dart @@ -166,7 +166,11 @@ class ChatCodeCopyRegion extends StatelessWidget { key: const Key('chat-code-header'), color: headerFill(context), child: Padding( - padding: const EdgeInsetsDirectional.only(start: 12, end: 4), + // Its label starts at the code's own inset (tighter when dense). + padding: EdgeInsetsDirectional.only( + start: AppDesignTokens.of(context).density.space(12), + end: 4, + ), child: Row( children: [ Expanded(child: label), diff --git a/app/lib/features/chat/ui/transcript/chat_markdown_view.dart b/app/lib/features/chat/ui/transcript/chat_markdown_view.dart index da8f254b..158c0112 100644 --- a/app/lib/features/chat/ui/transcript/chat_markdown_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_markdown_view.dart @@ -272,7 +272,9 @@ class _ChatMarkdownViewState extends State { code: code, label: Text(markdownCodeLabel(language), style: labelStyle), child: Padding( - padding: const EdgeInsets.all(12), + padding: EdgeInsets.all( + AppDesignTokens.of(context).density.space(12), + ), child: ChatTranscriptHorizontalScrollView( label: 'code block', child: Text.rich( @@ -570,9 +572,15 @@ class _ChatMarkdownViewState extends State { /// a tighter line, as a technical book does. TextStyle _codeStyle(BuildContext context) { const mono = TextStyle(fontFamily: appMonospaceFamily); - final reading = AppDesignTokens.of(context).reading; - if (reading.family == null) return mono; + final tokens = AppDesignTokens.of(context); + final reading = tokens.reading; final size = DefaultTextStyle.of(context).style.fontSize ?? 16; + // A dense design sets code at its body size (13 beside 14px prose): the + // monospace runs wider than the prose face. + if (reading.family == null && tokens.density.dense) { + return mono.copyWith(fontSize: size * 13 / 14, height: 1.4); + } + if (reading.family == null) return mono; return mono.copyWith( fontSize: size * 0.82, height: 1.45, diff --git a/app/lib/features/chat/ui/transcript/chat_message_bubble.dart b/app/lib/features/chat/ui/transcript/chat_message_bubble.dart index 464fba1f..c6340b70 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_bubble.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_bubble.dart @@ -55,15 +55,26 @@ class ChatUserBubble extends StatelessWidget { break; } // A Material surface (not a bare DecoratedBox) so a disclosure ListTile - // inside the bubble keeps its ink and background. + // inside the bubble keeps its ink and background. A dense design draws + // a tighter bubble in its own corners. + final tokens = AppDesignTokens.of(context); + final density = tokens.density; return Material( color: chatBubbleFill( context, Theme.of(context).colorScheme.surfaceContainerHighest, ), clipBehavior: Clip.antiAlias, - shape: const RoundedRectangleBorder(borderRadius: _radius), - child: Padding(padding: _padding, child: child), + shape: RoundedRectangleBorder(borderRadius: tokens.corners(_radius)), + child: Padding( + padding: density.dense + ? EdgeInsets.symmetric( + horizontal: density.inset(_padding.left), + vertical: density.space(_padding.top), + ) + : _padding, + child: child, + ), ); } } @@ -89,8 +100,10 @@ TextStyle? chatMessageTextStyle(BuildContext context) => AppDesignTokens.of( /// The empty-line gap between two paragraphs of a reply: about one line of /// body text at [fontSize] (else the ambient text size), scaled by the -/// operator's text scaling, so chunks read as separate paragraphs. +/// operator's text scaling, so chunks read as separate paragraphs. A design +/// may set a tighter gap ([ReadingType.paragraphGap]). double chatParagraphGap(BuildContext context, [double? fontSize]) { final size = fontSize ?? DefaultTextStyle.of(context).style.fontSize ?? 14; - return MediaQuery.textScalerOf(context).scale(size) * 0.9; + return MediaQuery.textScalerOf(context).scale(size) * + AppDesignTokens.of(context).reading.paragraphGap; } diff --git a/app/lib/features/chat/ui/transcript/chat_message_view.dart b/app/lib/features/chat/ui/transcript/chat_message_view.dart index e14c7062..21010681 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_view.dart @@ -83,7 +83,8 @@ class ChatMessageView extends StatelessWidget { // A terminal or manuscript transcript reads top to bottom: the // operator's prompt line or block quote starts at the same edge as the // answer and spans its column. - final transcript = AppDesignTokens.of(context).transcript; + final tokens = AppDesignTokens.of(context); + final transcript = tokens.transcript; final trailingUser = user && !automated && transcript == TranscriptStyle.bubbles; // No visible role label: side and surface say who spoke and the row's @@ -104,9 +105,12 @@ class ChatMessageView extends StatelessWidget { label: '$role message', child: Padding( // A manuscript leaves a little more air between turns, as a page - // spaces its paragraphs, since no bubble sets them apart. + // spaces its paragraphs, since no bubble sets them apart; a dense + // design a little less. padding: EdgeInsets.symmetric( - vertical: transcript == TranscriptStyle.manuscript ? 12 : 6, + vertical: transcript == TranscriptStyle.manuscript + ? 12 + : tokens.density.space(6), ), child: LayoutBuilder( builder: (context, constraints) => Align( diff --git a/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart b/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart index 0f0ff06f..98dbfcc7 100644 --- a/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; @@ -123,7 +124,8 @@ class _ChatTurnActivityViewState extends State { : DateTime.now().difference(started); final seconds = duration.inSeconds.clamp(0, 2147483647); final label = '${data.label}${widget.streaming ? ' ${seconds}s' : ''}'; - switch (AppDesignTokens.of(context).transcript) { + final tokens = AppDesignTokens.of(context); + switch (tokens.transcript) { case TranscriptStyle.prompt: return TerminalActivityRows( data: data, @@ -145,8 +147,12 @@ class _ChatTurnActivityViewState extends State { } // Desktop hover hugs the label; phones keep the full-width touch row. final compact = prefersCompactHitTargets(context); + // A dense design draws the line slimmer on a pointer device; a touch + // device keeps a 40px target. + final density = tokens.density; + final dense = density.dense; final content = ConstrainedBox( - constraints: const BoxConstraints(minHeight: 32), + constraints: BoxConstraints(minHeight: dense ? 20 : 32), child: Row( mainAxisSize: compact ? MainAxisSize.min : MainAxisSize.max, children: [ @@ -157,7 +163,7 @@ class _ChatTurnActivityViewState extends State { child: const ChatResponsePending(), ), ), - const SizedBox(width: 8), + SizedBox(width: density.space(8)), ], Flexible( child: Text( @@ -179,8 +185,13 @@ class _ChatTurnActivityViewState extends State { final button = TextButton( key: const Key('chat-turn-activity'), style: TextButton.styleFrom( - minimumSize: const Size(0, 48), - padding: const EdgeInsets.all(chatAgentContentInset), + minimumSize: Size(0, dense ? math.max(28, density.minTouchRow) : 48), + padding: dense + ? const EdgeInsets.symmetric( + horizontal: chatAgentContentInset, + vertical: 4, + ) + : const EdgeInsets.all(chatAgentContentInset), tapTargetSize: MaterialTapTargetSize.shrinkWrap, alignment: AlignmentDirectional.centerStart, ), diff --git a/app/lib/features/chat/ui/transcript/chat_turn_chip.dart b/app/lib/features/chat/ui/transcript/chat_turn_chip.dart index 98e5b244..af2c94ee 100644 --- a/app/lib/features/chat/ui/transcript/chat_turn_chip.dart +++ b/app/lib/features/chat/ui/transcript/chat_turn_chip.dart @@ -109,9 +109,9 @@ class _ChatTurnChipState extends State { ).corners(BorderRadius.circular(8)), onTap: _show, child: Padding( - padding: const EdgeInsets.symmetric( + padding: EdgeInsets.symmetric( horizontal: chatAgentContentInset, - vertical: 6, + vertical: AppDesignTokens.of(context).density.space(6), ), child: content, ), diff --git a/app/lib/features/graph/widgets/definition_graph_view.dart b/app/lib/features/graph/widgets/definition_graph_view.dart index 7eed93ee..77a3722b 100644 --- a/app/lib/features/graph/widgets/definition_graph_view.dart +++ b/app/lib/features/graph/widgets/definition_graph_view.dart @@ -107,6 +107,7 @@ class _DefinitionGraphViewState extends State { edges: edges, extents: extents, labelExtents: labelExtents, + metrics: graphMetricsOf(context), ); return (layout, routing); } diff --git a/app/lib/features/graph/widgets/graph_canvas_style.dart b/app/lib/features/graph/widgets/graph_canvas_style.dart index 03347dce..ace7b433 100644 --- a/app/lib/features/graph/widgets/graph_canvas_style.dart +++ b/app/lib/features/graph/widgets/graph_canvas_style.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; +import '../../../ui/theme/app_design_tokens.dart'; import '../layout/layout_models.dart'; +import '../layout/linear_graph_layout.dart'; import '../routing/route_models.dart'; /// Centralized graph spacing, not component dimensions. Rank separation follows @@ -27,6 +29,25 @@ RoutingConfig graphCanvasRoutingConfig() => RoutingConfig( boundsPadding: 12, ); +/// The drawing's spacings under the design at [context]: the web's metrics, +/// or a dense design's tighter gaps, lanes and padding (Compact), so its +/// smaller nodes are not left adrift in a comfortable layout. +LinearGraphMetrics graphMetricsOf(BuildContext context) => + AppDesignTokens.of(context).density.dense + ? _denseGraphMetrics + : const LinearGraphMetrics(); + +const LinearGraphMetrics _denseGraphMetrics = LinearGraphMetrics( + hGap: 32, + pad: 16, + laneSpacing: 20, + terminalGap: 16, + trackStep: 16, + portSpacing: 8, + labelPadding: 6, + labelGap: 2, +); + /// The native theme roles one definition graph canvas needs. /// /// No palette, font family or size is defined here: every value comes from the diff --git a/app/lib/features/graph/widgets/graph_stage_node.dart b/app/lib/features/graph/widgets/graph_stage_node.dart index e33ecc11..ee446ef0 100644 --- a/app/lib/features/graph/widgets/graph_stage_node.dart +++ b/app/lib/features/graph/widgets/graph_stage_node.dart @@ -1,6 +1,9 @@ +import 'dart:math' as math; + import 'package:flutter/material.dart'; import '../../../ui/status/run_status_icon.dart'; +import '../../../ui/theme/app_design_tokens.dart'; import '../domain/graph_definition.dart'; /// One content-sized stage node as an ordinary native control. @@ -56,7 +59,7 @@ class GraphStageNode extends StatelessWidget { button: true, selected: selected, label: _label, - child: _materialCard(onPressed, content), + child: _materialCard(context, onPressed, content), ), ); return active ? StageActivityHalo(child: control) : control; @@ -66,13 +69,29 @@ class GraphStageNode extends StatelessWidget { /// which assumes one line and cuts into a wrapped label's first and last /// line. A card keeps the rounded-rectangle surface the web node uses, and /// [selected] only chooses between two stock emphasis levels. - Widget _materialCard(VoidCallback onPressed, Widget content) { + Widget _materialCard( + BuildContext context, + VoidCallback onPressed, + Widget content, + ) { + // A dense design draws a smaller node: half the inset and a 32px + // least height on a pointer device (40px on touch). + final density = AppDesignTokens.of(context).density; final body = InkWell( onTap: onPressed, child: ConstrainedBox( - constraints: const BoxConstraints(minHeight: kMinInteractiveDimension), + constraints: BoxConstraints( + minHeight: density.dense + ? math.max(32, density.minTouchRow) + : kMinInteractiveDimension, + ), child: Padding( - padding: _contentPadding, + padding: density.dense + ? EdgeInsets.symmetric( + horizontal: density.space(_contentPadding.left) + 4, + vertical: density.space(_contentPadding.top), + ) + : _contentPadding, child: Align( // A terminal box widens to give each incoming route its own port; // its label stays centred in it. diff --git a/app/lib/features/graph/widgets/run_graph_view.dart b/app/lib/features/graph/widgets/run_graph_view.dart index c87c577b..f03be1ed 100644 --- a/app/lib/features/graph/widgets/run_graph_view.dart +++ b/app/lib/features/graph/widgets/run_graph_view.dart @@ -140,6 +140,7 @@ class _RunGraphViewState extends State { edges: edges, extents: extents, labelExtents: labelExtents, + metrics: graphMetricsOf(context), ); return (layout, routing); } diff --git a/app/lib/features/runs/ui/run_check_output_view.dart b/app/lib/features/runs/ui/run_check_output_view.dart index 123fcf56..5a48eed2 100644 --- a/app/lib/features/runs/ui/run_check_output_view.dart +++ b/app/lib/features/runs/ui/run_check_output_view.dart @@ -4,6 +4,7 @@ import '../../../ui/status/run_status_icon.dart'; import '../../../ui/text/monospace.dart'; import '../../chat/ui/transcript/chat_markdown_view.dart'; import '../domain/check_step_output.dart'; +import '../../../ui/theme/app_design_tokens.dart'; /// The note under a command whose recorded output the server cut short. const String checkOutputTruncated = @@ -99,7 +100,7 @@ class RunCheckCommandRow extends StatelessWidget { DecoratedBox( decoration: BoxDecoration( color: theme.colorScheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(8), + borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(8)), ), child: Padding( padding: const EdgeInsets.all(12), diff --git a/app/lib/features/runs/ui/run_detail_tab_bodies.dart b/app/lib/features/runs/ui/run_detail_tab_bodies.dart index d898c106..2e0e768b 100644 --- a/app/lib/features/runs/ui/run_detail_tab_bodies.dart +++ b/app/lib/features/runs/ui/run_detail_tab_bodies.dart @@ -12,6 +12,7 @@ import '../../../ui/layout/sticky_section.dart'; import '../../../ui/text/live_elapsed_builder.dart'; import '../../../ui/text/monospace.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../../../ui/theme/app_design_tokens.dart'; /// The Summary tab: the run's identity, the recorded facts as one grid, /// the stored original prompt with its copy control and the collapsible Input @@ -231,7 +232,7 @@ Widget _materialBlock(BuildContext context, DetailSummaryRow row) { padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: theme.colorScheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(8), + borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(8)), ), child: SelectableText( row.value, diff --git a/app/lib/features/runs/ui/run_detail_timeline.dart b/app/lib/features/runs/ui/run_detail_timeline.dart index 9da7b78c..b2bbbfd1 100644 --- a/app/lib/features/runs/ui/run_detail_timeline.dart +++ b/app/lib/features/runs/ui/run_detail_timeline.dart @@ -9,6 +9,7 @@ import '../../../ui/text/live_elapsed_builder.dart'; import '../../pipelines/pipeline_format.dart' show formatDuration; import '../domain/run_models.dart'; import 'run_detail_content.dart'; +import '../../../ui/theme/app_design_tokens.dart'; /// The Timeline tab's recorded visits, one shared list row per visit. /// @@ -116,7 +117,7 @@ class RunTimelineRow extends StatelessWidget { padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration( color: color.withValues(alpha: 0.14), - borderRadius: BorderRadius.circular(10), + borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(10)), ), child: Text( label, diff --git a/app/lib/features/search/ui/search_result_view.dart b/app/lib/features/search/ui/search_result_view.dart index 4658a658..8d8da89d 100644 --- a/app/lib/features/search/ui/search_result_view.dart +++ b/app/lib/features/search/ui/search_result_view.dart @@ -5,6 +5,7 @@ import '../../../core/transport/pipelines_client.dart' show configuredGatewayEndpoint; import '../../../ui/layout/app_list_avatar.dart'; import '../../../ui/layout/app_overflow_menu.dart'; +import '../../../ui/theme/app_design_tokens.dart'; import '../../artifacts/domain/artifact_kind.dart'; import '../../artifacts/domain/artifact_record.dart'; import '../../artifacts/ui/artifact_tile.dart'; @@ -48,9 +49,11 @@ Widget? searchArtifactThumbnail(BuildContext context, JsonMap hit) { return null; } return ClipRRect( - borderRadius: BorderRadius.circular(8), + borderRadius: AppDesignTokens.of( + context, + ).denseCorners(BorderRadius.circular(8)), child: SizedBox.square( - dimension: kAppListAvatarSize, + dimension: appListAvatarSize(context), child: ArtifactThumbnail( key: ValueKey('search.thumbnail.${hit['target']}'), artifact: record, diff --git a/app/lib/features/settings/settings_design_section.dart b/app/lib/features/settings/settings_design_section.dart index 4e8c5c6e..b6618dc9 100644 --- a/app/lib/features/settings/settings_design_section.dart +++ b/app/lib/features/settings/settings_design_section.dart @@ -56,6 +56,7 @@ class SettingsDesignSection extends StatelessWidget { subtitle: Text(design.description), secondary: DesignSwatchPreview( swatch: design.swatch(Theme.of(context).brightness), + lines: design.swatchLines, ), ), ], @@ -64,12 +65,14 @@ class SettingsDesignSection extends StatelessWidget { ); } -/// A design's small preview in the picker: its page with a line of its ink -/// and a dot of its accent, framed by a hairline. +/// A design's small preview in the picker: its page with [lines] lines of +/// its ink (the last one short) and a dot of its accent, framed by a +/// hairline. A dense design draws more, tighter lines in the same page. class DesignSwatchPreview extends StatelessWidget { - const DesignSwatchPreview({super.key, required this.swatch}); + const DesignSwatchPreview({super.key, required this.swatch, this.lines = 2}); final DesignSwatch swatch; + final int lines; @override Widget build(BuildContext context) => ExcludeSemantics( @@ -89,10 +92,11 @@ class DesignSwatchPreview extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Container(height: 2, color: swatch.ink), + for (var line = 1; line < lines; line += 1) + Container(height: lines > 2 ? 1 : 2, color: swatch.ink), FractionallySizedBox( widthFactor: 0.6, - child: Container(height: 2, color: swatch.ink), + child: Container(height: lines > 2 ? 1 : 2, color: swatch.ink), ), ], ), diff --git a/app/lib/features/settings/settings_group.dart b/app/lib/features/settings/settings_group.dart index 1923aa04..e618e7d3 100644 --- a/app/lib/features/settings/settings_group.dart +++ b/app/lib/features/settings/settings_group.dart @@ -33,16 +33,17 @@ class SettingsGroup extends StatelessWidget { final footer = this.footer; final theme = Theme.of(context); final tokens = AppDesignTokens.of(context); + final inset = settingsRowInsetOf(context); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (title != null) Padding( - padding: const EdgeInsetsDirectional.fromSTEB( - settingsRowInset, + padding: EdgeInsetsDirectional.fromSTEB( + inset, 0, - settingsRowInset, - settingsTitleGap, + inset, + tokens.density.space(settingsTitleGap), ), child: Semantics( header: true, @@ -74,7 +75,7 @@ class SettingsGroup extends StatelessWidget { Divider( height: 1, thickness: 1, - indent: settingsRowInset, + indent: inset, color: theme.colorScheme.outlineVariant, ), child, @@ -92,11 +93,12 @@ class SettingsGroup extends StatelessWidget { color: Theme.of(context).colorScheme.onSurfaceVariant, ); final text = DefaultTextStyle.merge(style: style, child: footer); + final inset = settingsRowInsetOf(context); return Padding( - padding: const EdgeInsetsDirectional.fromSTEB( - settingsRowInset, - settingsFieldGap + 2, - settingsRowInset, + padding: EdgeInsetsDirectional.fromSTEB( + inset, + AppDesignTokens.of(context).density.space(settingsFieldGap + 2), + inset, 0, ), child: text, @@ -124,8 +126,8 @@ class SettingsGroupItem extends StatelessWidget { width: double.infinity, child: Padding( padding: EdgeInsetsDirectional.symmetric( - horizontal: settingsRowInset, - vertical: 12, + horizontal: settingsRowInsetOf(context), + vertical: AppDesignTokens.of(context).density.space(12), ), child: child, ), diff --git a/app/lib/features/settings/settings_layout.dart b/app/lib/features/settings/settings_layout.dart index 5eb7cade..92ec6dd2 100644 --- a/app/lib/features/settings/settings_layout.dart +++ b/app/lib/features/settings/settings_layout.dart @@ -9,6 +9,10 @@ /// at a reading width beside the section index. library; +import 'package:flutter/widgets.dart'; + +import '../../ui/theme/app_design_tokens.dart'; + /// The widest the column of groups grows on a wide window. const double settingsContentMaxWidth = 720; @@ -50,3 +54,12 @@ const double settingsPreloadViewports = 1; /// How long a changing endpoint must settle before a server section reloads. const Duration settingsEndpointDebounce = Duration(milliseconds: 600); + +/// [settingsSectionGap] under the design at [context] (tighter when dense). +double settingsSectionGapOf(BuildContext context) => + AppDesignTokens.of(context).density.space(settingsSectionGap); + +/// [settingsRowInset] under the design at [context]: a dense design's rows +/// (its ListTiles' 12px padding) and their headers keep the same edge. +double settingsRowInsetOf(BuildContext context) => + AppDesignTokens.of(context).density.inset(settingsRowInset); diff --git a/app/lib/features/settings/settings_page_body.dart b/app/lib/features/settings/settings_page_body.dart index 1b66eaaf..b3008169 100644 --- a/app/lib/features/settings/settings_page_body.dart +++ b/app/lib/features/settings/settings_page_body.dart @@ -34,7 +34,7 @@ class SettingsPageBody extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ for (final (index, child) in children.indexed) ...[ - if (index > 0) const SizedBox(height: settingsSectionGap), + if (index > 0) SizedBox(height: settingsSectionGapOf(context)), child, ], ], diff --git a/app/lib/features/settings/settings_search_page.dart b/app/lib/features/settings/settings_search_page.dart index a3c3234e..19f799d6 100644 --- a/app/lib/features/settings/settings_search_page.dart +++ b/app/lib/features/settings/settings_search_page.dart @@ -171,7 +171,7 @@ class _SettingsSearchPageState extends State { ), ], ), - const SizedBox(height: settingsSectionGap), + SizedBox(height: settingsSectionGapOf(context)), Expanded(child: _list(visible, insets)), ], ), @@ -201,7 +201,7 @@ class _SettingsSearchPageState extends State { Widget _list(List visible, EdgeInsets insets) { if (visible.isEmpty) { return Padding( - padding: const EdgeInsets.all(settingsRowInset), + padding: EdgeInsets.all(settingsRowInsetOf(context)), child: Text('No settings match "${_search.text.trim()}".'), ); } @@ -222,7 +222,7 @@ class _SettingsSearchPageState extends State { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ for (final (index, section) in visible.indexed) ...[ - if (index > 0) const SizedBox(height: settingsSectionGap), + if (index > 0) SizedBox(height: settingsSectionGapOf(context)), KeyedSubtree( key: _keyFor(section.id), child: _isActive(section) diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index 8bef446f..274d8ca5 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -347,7 +347,7 @@ class _AdaptiveShellState extends State { child: ShellRailScope( shown: rail, bodyWidth: rail - ? media.size.width - kNavigationRailSpace + ? media.size.width - navigationRailSpaceOf(context) : null, child: scaffold, ), diff --git a/app/lib/shell/navigation_rail.dart b/app/lib/shell/navigation_rail.dart index 376378f6..d19c226c 100644 --- a/app/lib/shell/navigation_rail.dart +++ b/app/lib/shell/navigation_rail.dart @@ -10,6 +10,15 @@ const double kNavigationRailWidth = 96; /// The rail with its divider: what the rail takes from a wide window's width. const double kNavigationRailSpace = kNavigationRailWidth + 1; +/// The rail's width under the design at [context]: [kNavigationRailWidth], +/// or a dense design's narrower, icon-only rail. +double navigationRailWidthOf(BuildContext context) => + AppDesignTokens.of(context).density.railWidth; + +/// The rail with its divider under the design at [context]. +double navigationRailSpaceOf(BuildContext context) => + navigationRailWidthOf(context) + 1; + /// The narrowest window that shows the destination rail: the list-detail /// minimum for the body beside it, plus the rail and its divider (the space the /// shell takes from the window). Narrower windows keep the floating destination @@ -66,6 +75,7 @@ class ShellNavigationRail extends StatelessWidget { Widget build(BuildContext context) { final index = shellTabDestinations.indexOf(selected); final surface = Theme.of(context).colorScheme.surface; + final density = AppDesignTokens.of(context).density; // The surface runs under the top inset too: the padding only moves the // rail's content below the system's top, so no unpainted strip shows above // the rail's background. @@ -75,11 +85,12 @@ class ShellNavigationRail extends StatelessWidget { child: Padding( padding: padding, child: SizedBox( - width: kNavigationRailWidth, + width: density.railWidth, child: LayoutBuilder( builder: (context, constraints) => _rail( index, surface, + density, pinSettings: constraints.maxHeight >= kNavigationRailPinnedSettingsMinHeight, @@ -90,12 +101,19 @@ class ShellNavigationRail extends StatelessWidget { ); } - Widget _rail(int index, Color surface, {required bool pinSettings}) => - NavigationRail( + Widget _rail( + int index, + Color surface, + DesignDensity density, { + required bool pinSettings, + }) => NavigationRail( key: const ValueKey('shell.navigation-rail'), backgroundColor: surface, - minWidth: kNavigationRailWidth, - labelType: NavigationRailLabelType.all, + minWidth: density.railWidth, + // An icon-only rail names each tab in its tooltip alone. + labelType: density.railLabels + ? NavigationRailLabelType.all + : NavigationRailLabelType.none, selectedIndex: index < 0 ? null : index, onDestinationSelected: (value) => onSelected(shellTabDestinations[value]), @@ -119,6 +137,7 @@ class ShellNavigationRail extends StatelessWidget { scrollable: true, trailingAtBottom: pinSettings, trailing: _SettingsRailItem( + density: density, selected: selected == AppDestination.settings, onTap: () => onSelected(AppDestination.settings), ), @@ -130,8 +149,13 @@ class ShellNavigationRail extends StatelessWidget { /// It is not a [NavigationRailDestination] itself because the rail's /// destination list is the tabs, and `trailing` is what the rail pins. class _SettingsRailItem extends StatelessWidget { - const _SettingsRailItem({required this.selected, required this.onTap}); + const _SettingsRailItem({ + required this.density, + required this.selected, + required this.onTap, + }); + final DesignDensity density; final bool selected; final VoidCallback onTap; @@ -146,6 +170,33 @@ class _SettingsRailItem extends StatelessWidget { color: foreground, fontWeight: selected ? FontWeight.w600 : FontWeight.w500, ); + final indicator = Container( + width: 56, + height: 32, + alignment: Alignment.center, + decoration: ShapeDecoration( + shape: AppDesignTokens.of(context).shape(const StadiumBorder()), + color: selected ? scheme.secondaryContainer : null, + ), + child: Icon(item.icon, color: foreground), + ); + final Widget mark = density.railLabels + ? Column( + mainAxisSize: MainAxisSize.min, + children: [ + indicator, + const SizedBox(height: 4), + Text(item.label, style: textStyle), + ], + ) + // An icon-only rail names Settings in a tooltip, as its tabs. + : Center( + child: Tooltip( + message: item.label, + excludeFromSemantics: true, + child: indicator, + ), + ); return Semantics( button: true, selected: selected, @@ -155,28 +206,10 @@ class _SettingsRailItem extends StatelessWidget { key: const ValueKey('shell.destination.settings'), onTap: onTap, child: SizedBox( - width: kNavigationRailWidth, + width: density.railWidth, child: Padding( - padding: const EdgeInsets.symmetric(vertical: 12), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - width: 56, - height: 32, - alignment: Alignment.center, - decoration: ShapeDecoration( - shape: AppDesignTokens.of( - context, - ).shape(const StadiumBorder()), - color: selected ? scheme.secondaryContainer : null, - ), - child: Icon(item.icon, color: foreground), - ), - const SizedBox(height: 4), - Text(item.label, style: textStyle), - ], - ), + padding: EdgeInsets.symmetric(vertical: density.space(12)), + child: mark, ), ), ), diff --git a/app/lib/shell/windows/window_frame.dart b/app/lib/shell/windows/window_frame.dart index 74a5f9de..dd82247d 100644 --- a/app/lib/shell/windows/window_frame.dart +++ b/app/lib/shell/windows/window_frame.dart @@ -1,14 +1,25 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import '../../ui/theme/app_design_tokens.dart'; import 'window_kind.dart'; const double windowCornerRadius = 12; +/// A floating window's corners under the design at [context]: +/// [windowCornerRadius], or a dense design's own corners. +BorderRadius windowCorners(BuildContext context) => AppDesignTokens.of( + context, +).denseCorners(const BorderRadius.all(Radius.circular(windowCornerRadius))); + /// The height of a window's title bar: a compact row of icon buttons, taller -/// with larger text. -double windowTitleBarHeight(BuildContext context) => - MediaQuery.textScalerOf(context).scale(40).clamp(40.0, 64.0); +/// with larger text (a dense design's slimmer bar grows the same way). +double windowTitleBarHeight(BuildContext context) { + final height = AppDesignTokens.of(context).density.titleBarHeight; + return MediaQuery.textScalerOf( + context, + ).scale(height).clamp(height, height + 24); +} /// A floating window's card and title bar: the title (drag to move, double /// click to maximise), the kind's actions, then Maximise and the X. The X @@ -45,10 +56,11 @@ class WindowFrame extends StatelessWidget { Widget build(BuildContext context) { final theme = Theme.of(context); final colors = theme.colorScheme; + final dense = AppDesignTokens.of(context).density.dense; return Material( elevation: 8, clipBehavior: Clip.antiAlias, - borderRadius: BorderRadius.circular(windowCornerRadius), + borderRadius: windowCorners(context), color: colors.surfaceContainer, child: Align( alignment: Alignment.topCenter, @@ -63,7 +75,7 @@ class WindowFrame extends StatelessWidget { ), child: Row( children: [ - Expanded(child: _title(theme)), + Expanded(child: _title(theme, dense)), for (final action in actions) IconButton( tooltip: action.label, @@ -91,7 +103,7 @@ class WindowFrame extends StatelessWidget { ); } - Widget _title(ThemeData theme) => MouseRegion( + Widget _title(ThemeData theme, bool dense) => MouseRegion( cursor: maximized ? SystemMouseCursors.basic : SystemMouseCursors.move, child: GestureDetector( key: const ValueKey('window-title'), @@ -104,11 +116,15 @@ class WindowFrame extends StatelessWidget { onPanEnd: maximized ? null : (_) => onMoveEnd(), onDoubleTap: onToggleMaximized, child: Padding( - padding: const EdgeInsetsDirectional.only(start: 12, end: 8), + padding: EdgeInsetsDirectional.only(start: dense ? 8 : 12, end: 8), child: Row( children: [ - Icon(icon, size: 18, color: theme.colorScheme.onSurfaceVariant), - const SizedBox(width: 8), + Icon( + icon, + size: dense ? 16 : 18, + color: theme.colorScheme.onSurfaceVariant, + ), + SizedBox(width: dense ? 6 : 8), Expanded( child: Text( title, @@ -137,7 +153,7 @@ class WindowOutline extends StatelessWidget { child: DecoratedBox( decoration: BoxDecoration( border: Border.all(color: colors.outlineVariant), - borderRadius: BorderRadius.circular(windowCornerRadius), + borderRadius: windowCorners(context), ), child: const SizedBox.expand(), ), diff --git a/app/lib/shell/windows/window_host.dart b/app/lib/shell/windows/window_host.dart index 682d9b4b..e48b33e9 100644 --- a/app/lib/shell/windows/window_host.dart +++ b/app/lib/shell/windows/window_host.dart @@ -133,7 +133,7 @@ class _WindowHostState extends State { // right, so they never sit under the rail. // The shell takes the rail and its divider (kNavigationRailSpace). final leading = widget.reservesRail && showsNavigationRail(context) - ? kNavigationRailSpace + ? navigationRailSpaceOf(context) : 0.0; final bounds = Size( constraints.maxWidth - leading, diff --git a/app/lib/shell/windows/window_navigator.dart b/app/lib/shell/windows/window_navigator.dart index f395517d..87aa3725 100644 --- a/app/lib/shell/windows/window_navigator.dart +++ b/app/lib/shell/windows/window_navigator.dart @@ -5,7 +5,7 @@ import 'window_frame.dart' show WindowOutline, WindowResizeGrip, - windowCornerRadius, + windowCorners, windowTitleBarHeight; import 'window_scope.dart'; @@ -122,15 +122,15 @@ class WindowPageBox extends StatelessWidget { Widget build(BuildContext context) { final body = WindowBodyScope.maybeOf(context); if (body == null) return child; - const radius = Radius.circular(windowCornerRadius); + final corners = windowCorners(context); return Stack( children: [ Positioned.fromRect( rect: body, child: ClipRRect( - borderRadius: const BorderRadius.only( - bottomLeft: radius, - bottomRight: radius, + borderRadius: BorderRadius.only( + bottomLeft: corners.bottomLeft, + bottomRight: corners.bottomRight, ), child: MediaQuery( data: MediaQuery.of(context).copyWith( diff --git a/app/lib/ui/adaptive/segmented_bar.dart b/app/lib/ui/adaptive/segmented_bar.dart index 82742723..a31d1d16 100644 --- a/app/lib/ui/adaptive/segmented_bar.dart +++ b/app/lib/ui/adaptive/segmented_bar.dart @@ -423,7 +423,7 @@ class _SegmentedBarState extends State { titleShare ?? (widget.separateActionIslands ? .10 : SegmentedBar.minTitleShare); final besideTitle = - width - (leading == null ? 0 : segmentedPieceHeight() + 8) - 8; + width - (leading == null ? 0 : segmentedPieceHeight(context) + 8) - 8; // Actions that cannot move (a model picker) may take the room down // to the title's minimum share; the rest leave for the More menu // before the title goes under its own width. diff --git a/app/lib/ui/adaptive/segmented_bar_pieces.dart b/app/lib/ui/adaptive/segmented_bar_pieces.dart index 9e6952af..939e1dcd 100644 --- a/app/lib/ui/adaptive/segmented_bar_pieces.dart +++ b/app/lib/ui/adaptive/segmented_bar_pieces.dart @@ -1,11 +1,17 @@ import 'package:flutter/material.dart'; +import '../theme/app_design_tokens.dart'; import 'glass_pill.dart'; import 'segmented_bar_motion.dart'; /// The smallest height of every piece of a [SegmentedBar]: the platform's -/// minimum touch target, so a round Back is a circle. -double segmentedPieceHeight() => kMinInteractiveDimension; +/// minimum touch target, so a round Back is a circle. Under a dense design +/// at [context] the pieces are 40px: its 32px controls with a 4px edge, still +/// a comfortable touch target. +double segmentedPieceHeight([BuildContext? context]) => + context != null && AppDesignTokens.of(context).density.dense + ? 40 + : kMinInteractiveDimension; /// One rounded piece of a segmented bar: a [GlassPill] at least the /// platform's touch-target size. @@ -19,7 +25,7 @@ class SegmentedPill extends StatelessWidget { @override Widget build(BuildContext context) { - final height = segmentedPieceHeight(); + final height = segmentedPieceHeight(context); // A stadium whose content is as wide as it is tall is a circle. return GlassPill( fill: fill, @@ -75,6 +81,10 @@ Widget? impliedSegmentedLeading(BuildContext context) { /// The title pill's horizontal padding on each side. const double segmentedTitlePadding = 16; +/// [segmentedTitlePadding] under the design at [context] (12px when dense). +double segmentedTitlePaddingOf(BuildContext context) => + AppDesignTokens.of(context).density.inset(segmentedTitlePadding); + /// The width the title pill needs to show [title] and [subtitle] whole (at /// the text scale at [context]). double segmentedTitleWidth( @@ -113,7 +123,7 @@ double segmentedTitleWidth( measure(' ', subtitleStyle)); final text = measure(title, titleStyle); return (text > subWidth ? text : subWidth).ceilToDouble() + - segmentedTitlePadding * 2; + segmentedTitlePaddingOf(context) * 2; } /// The title, with an optional one-line subtitle, in one pill; pressing it @@ -156,8 +166,8 @@ class SegmentedTitlePill extends StatelessWidget { ); final subtitle = this.subtitle ?? ''; final content = Padding( - padding: const EdgeInsets.symmetric( - horizontal: segmentedTitlePadding, + padding: EdgeInsets.symmetric( + horizontal: segmentedTitlePaddingOf(context), vertical: 4, ), child: Row( diff --git a/app/lib/ui/input/app_search_field.dart b/app/lib/ui/input/app_search_field.dart index 8755d70e..7a714192 100644 --- a/app/lib/ui/input/app_search_field.dart +++ b/app/lib/ui/input/app_search_field.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import '../theme/app_design_tokens.dart'; /// The app's one search field. /// @@ -53,8 +54,10 @@ class AppSearchField extends StatelessWidget { @override Widget build(BuildContext context) { final scheme = Theme.of(context).colorScheme; - const radius = BorderRadius.all(Radius.circular(28)); - const stadium = OutlineInputBorder( + final radius = AppDesignTokens.of( + context, + ).denseCorners(const BorderRadius.all(Radius.circular(28))); + final stadium = OutlineInputBorder( borderRadius: radius, borderSide: BorderSide.none, ); diff --git a/app/lib/ui/layout/app_list_avatar.dart b/app/lib/ui/layout/app_list_avatar.dart index e24474df..9cf4189e 100644 --- a/app/lib/ui/layout/app_list_avatar.dart +++ b/app/lib/ui/layout/app_list_avatar.dart @@ -5,6 +5,11 @@ import '../theme/app_design_tokens.dart'; /// avatar ([CircleAvatar]'s default). const double kAppListAvatarSize = 40; +/// The leading avatar's size under the design at [context]: +/// [kAppListAvatarSize], or a dense design's smaller one. +double appListAvatarSize(BuildContext context) => + AppDesignTokens.of(context).density.avatarSize; + /// A list row's leading identity: an icon or an initial on a tinted circle, /// with an optional corner badge (a chat's activity indicator). /// @@ -52,16 +57,19 @@ class AppListAvatar extends StatelessWidget { (foreground == null ? Theme.of(context).colorScheme.surfaceContainerHighest : mark.withValues(alpha: 0.14)); + // The mark keeps the same proportion of the circle at every density. + final tokens = AppDesignTokens.of(context); + final size = tokens.density.avatarSize; + final scale = size / kAppListAvatarSize; final initialStyle = (Theme.of(context).textTheme.titleMedium ?? const TextStyle()).copyWith( color: mark, - fontSize: 18, + fontSize: 18 * scale, fontWeight: FontWeight.w700, height: 1, ); // A flat design (Terminal) frames the mark in a square box instead of a // tinted circle. - final tokens = AppDesignTokens.of(context); final decoration = tokens.flat ? BoxDecoration( border: Border.all(color: mark.withValues(alpha: 0.55)), @@ -69,18 +77,18 @@ class AppListAvatar extends StatelessWidget { ) : BoxDecoration(color: fill, shape: BoxShape.circle); final circle = SizedBox.square( - dimension: kAppListAvatarSize, + dimension: size, child: DecoratedBox( decoration: decoration, child: Center( // The glyph is identity, not reading text: it scales down to stay // inside the circle under large text instead of overflowing it. child: Padding( - padding: const EdgeInsets.all(8), + padding: EdgeInsets.all(8 * scale), child: FittedBox( fit: BoxFit.scaleDown, child: IconTheme.merge( - data: IconThemeData(color: mark, size: 22), + data: IconThemeData(color: mark, size: 22 * scale), child: DefaultTextStyle(style: initialStyle, child: child), ), ), diff --git a/app/lib/ui/layout/app_list_row.dart b/app/lib/ui/layout/app_list_row.dart index 3dfadb1a..3798bef7 100644 --- a/app/lib/ui/layout/app_list_row.dart +++ b/app/lib/ui/layout/app_list_row.dart @@ -156,6 +156,7 @@ class AppListRow extends StatelessWidget { selected: selected, emphasized: emphasized, ); + final metrics = _RowMetrics.of(context); return Semantics( container: true, selected: selected, @@ -166,14 +167,16 @@ class AppListRow extends StatelessWidget { final minimal = constraints.maxWidth < kAppListRowMinimalWidth; final showLeading = leading != null && !minimal; final showMenu = menu != null && !minimal; - final start = compact ? 12.0 : kAppListRowInset; - final avatarGap = compact ? _compactAvatarGap : _avatarGap; + final start = compact ? metrics.compactInset : metrics.inset; + final avatarGap = compact + ? metrics.compactAvatarGap + : metrics.avatarGap; final content = Padding( padding: EdgeInsetsDirectional.only( start: start, - end: showMenu ? 4 : kAppListRowInset, - top: kAppListRowVerticalPadding, - bottom: kAppListRowVerticalPadding, + end: showMenu ? 4 : metrics.inset, + top: metrics.vertical, + bottom: metrics.vertical, ), child: Row( children: [ @@ -187,7 +190,7 @@ class AppListRow extends StatelessWidget { padding: EdgeInsetsDirectional.only(end: avatarGap), child: leading, ), - Expanded(child: _text(styles, compact)), + Expanded(child: _text(styles, metrics, compact)), if (showMenu) Padding( padding: const EdgeInsetsDirectional.only(start: 4), @@ -227,7 +230,12 @@ class AppListRow extends StatelessWidget { key: tapKey, onTap: onTap, onLongPress: onLongPress, - child: content, + child: metrics.minHeight > 0 + ? ConstrainedBox( + constraints: BoxConstraints(minHeight: metrics.minHeight), + child: Center(widthFactor: 1, child: content), + ) + : content, ), ); // The colour bar runs the row's whole height, divider included, and @@ -261,7 +269,7 @@ class AppListRow extends StatelessWidget { // not known here, so a selectable row's divider starts at the inset. final textStart = selectionControl != null ? start - : start + (showLeading ? kAppListAvatarSize + avatarGap : 0); + : start + (showLeading ? metrics.avatar + avatarGap : 0); final line = Padding( padding: EdgeInsetsDirectional.only(start: textStart), child: SizedBox( @@ -306,7 +314,7 @@ class AppListRow extends StatelessWidget { ); } - Widget _text(_RowStyles styles, bool compact) { + Widget _text(_RowStyles styles, _RowMetrics metrics, bool compact) { final line = compact ? (compactSubtitle ?? subtitle) : subtitle; final time = _time(styles); final titleLine = LayoutBuilder( @@ -339,7 +347,7 @@ class AppListRow extends StatelessWidget { final detailLine = detail == null || (compact && !compactDetail) ? null : Padding( - padding: const EdgeInsets.only(top: _lineGap), + padding: EdgeInsets.only(top: metrics.lineGap), child: DefaultTextStyle( style: styles.subtitle, maxLines: 1, @@ -354,7 +362,7 @@ class AppListRow extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ titleLine, - const SizedBox(height: _lineGap), + SizedBox(height: metrics.lineGap), timeLine, ], ); @@ -364,7 +372,7 @@ class AppListRow extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ titleLine, - const SizedBox(height: _lineGap), + SizedBox(height: metrics.lineGap), Row( children: [ if (subtitleLeading != null) @@ -394,6 +402,57 @@ class AppListRow extends StatelessWidget { } } +/// The row's spacing under the design's density: the comfortable constants, +/// or a dense design's tighter ones (a 36px single-line row and a ~52px +/// two-line row on a pointer device; at least 40px on touch). +class _RowMetrics { + const _RowMetrics({ + required this.inset, + required this.compactInset, + required this.avatarGap, + required this.compactAvatarGap, + required this.vertical, + required this.lineGap, + required this.avatar, + required this.minHeight, + }); + + factory _RowMetrics.of(BuildContext context) { + final density = AppDesignTokens.of(context).density; + if (!density.dense) return _comfortable; + return _RowMetrics( + inset: density.inset(kAppListRowInset), + compactInset: density.inset(12), + avatarGap: density.space(_avatarGap), + compactAvatarGap: density.space(_compactAvatarGap), + vertical: density.space(kAppListRowVerticalPadding), + lineGap: 0, + avatar: density.avatarSize, + minHeight: density.minTouchRow, + ); + } + + static const _comfortable = _RowMetrics( + inset: kAppListRowInset, + compactInset: 12, + avatarGap: _avatarGap, + compactAvatarGap: _compactAvatarGap, + vertical: kAppListRowVerticalPadding, + lineGap: _lineGap, + avatar: kAppListAvatarSize, + minHeight: 0, + ); + + final double inset; + final double compactInset; + final double avatarGap; + final double compactAvatarGap; + final double vertical; + final double lineGap; + final double avatar; + final double minHeight; +} + /// The row's text styles, from the host's own type scale. class _RowStyles { const _RowStyles(this.title, this.subtitle, this.time, this.divider); diff --git a/app/lib/ui/theme/app_design.dart b/app/lib/ui/theme/app_design.dart index df538afe..14096214 100644 --- a/app/lib/ui/theme/app_design.dart +++ b/app/lib/ui/theme/app_design.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'app_design_tokens.dart'; import 'app_theme.dart'; +import 'compact_theme.dart'; import 'paper_theme.dart'; import 'terminal_theme.dart'; @@ -40,6 +41,14 @@ enum AppDesign { 'paper', 'Paper', 'Warm paper, serif reading text and ink colours; calm for long reads.', + ), + + /// The Default look packed tight for a big monitor: smaller type, thin + /// rows, 18px icons, an icon-only rail and modest corners. + compact( + 'compact', + 'Compact', + 'Default’s Material look, dense: small type, thin rows, more on screen.', ); const AppDesign(this.id, this.label, this.description); @@ -67,6 +76,7 @@ enum AppDesign { standard => appLightTheme(fontFamily: fontFamily), terminal => terminalTheme(Brightness.light), paper => paperTheme(Brightness.light, fontFamily: fontFamily), + compact => compactTheme(Brightness.light, fontFamily: fontFamily), }; /// The design's dark theme; see [light]. @@ -74,6 +84,7 @@ enum AppDesign { standard => appDarkTheme(fontFamily: fontFamily), terminal => terminalTheme(Brightness.dark), paper => paperTheme(Brightness.dark, fontFamily: fontFamily), + compact => compactTheme(Brightness.dark, fontFamily: fontFamily), }; /// Whether the device's interface font applies under this design (Paper @@ -85,7 +96,7 @@ enum AppDesign { DesignSwatch swatch(Brightness brightness) { final dark = brightness == Brightness.dark; return switch (this) { - standard => + standard || compact => dark ? const DesignSwatch( Color(0xFF141416), @@ -123,6 +134,10 @@ enum AppDesign { ), }; } + + /// How many lines of ink the picker's preview draws: Compact's packs more + /// into the same page. + int get swatchLines => this == compact ? 4 : 2; } /// A design's three defining colours, for the picker's small preview. diff --git a/app/lib/ui/theme/app_design_styles.dart b/app/lib/ui/theme/app_design_styles.dart index 0e757293..cb5f790f 100644 --- a/app/lib/ui/theme/app_design_styles.dart +++ b/app/lib/ui/theme/app_design_styles.dart @@ -1,6 +1,8 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; +export 'design_density.dart'; + /// How the chat transcript draws a conversation. Each design picks one; the /// transcript widgets branch on it, never on the design itself. enum TranscriptStyle { @@ -54,6 +56,7 @@ class ReadingType { this.measure, this.scale = 1, this.figureWidth = 0.5, + this.paragraphGap = 0.9, }); /// The reading face; null keeps the theme's body face. @@ -73,6 +76,10 @@ class ReadingType { /// [measure] is worth (half an em for Source Serif's figures). final double figureWidth; + /// The gap between two paragraphs of an answer, in lines of reading text + /// (before text scaling): about a line by default, less for a dense design. + final double paragraphGap; + /// [base] in the reading face, size and line height. TextStyle? apply(TextStyle? base) { if (base == null) return null; diff --git a/app/lib/ui/theme/app_design_tokens.dart b/app/lib/ui/theme/app_design_tokens.dart index 42598535..5a42fd8b 100644 --- a/app/lib/ui/theme/app_design_tokens.dart +++ b/app/lib/ui/theme/app_design_tokens.dart @@ -52,6 +52,7 @@ class AppDesignTokens extends ThemeExtension { this.selectedRow = SelectedRowStyle.tonal, this.reading = const ReadingType(), this.chatColorSaturation = 1, + this.density = DesignDensity.comfortable, }); /// The Default design: every widget keeps its own shapes. @@ -98,6 +99,10 @@ class AppDesignTokens extends ThemeExtension { /// palette as is, lower to quieten it towards ink. final double chatColorSaturation; + /// How tightly the interface is packed: spacing, icon and avatar sizes, + /// the rail and the window title bar ([DesignDensity.compact] for Compact). + final DesignDensity density; + /// Whether the transcript draws prompt and tool lines rather than bubbles. bool get terminal => transcript == TranscriptStyle.prompt; @@ -119,6 +124,12 @@ class AppDesignTokens extends ThemeExtension { return r == null ? designed : BorderRadius.circular(r); } + /// [designed] corners, or [radius] corners under a dense design: for the + /// surfaces whose own corners the comfortable designs keep (floating + /// windows, search thumbnails), so only a dense design rounds them alike. + BorderRadius denseCorners(BorderRadius designed) => + density.dense ? corners(designed) : designed; + /// [designed] (a widget's own fill) or, under a flat design, its [panel]. Color panelFill(ColorScheme scheme, Color designed) => flat ? panel ?? scheme.surfaceContainerLow : designed; @@ -143,6 +154,7 @@ class AppDesignTokens extends ThemeExtension { SelectedRowStyle? selectedRow, ReadingType? reading, double? chatColorSaturation, + DesignDensity? density, }) => AppDesignTokens( design: design ?? this.design, radius: radius ?? this.radius, @@ -156,6 +168,7 @@ class AppDesignTokens extends ThemeExtension { selectedRow: selectedRow ?? this.selectedRow, reading: reading ?? this.reading, chatColorSaturation: chatColorSaturation ?? this.chatColorSaturation, + density: density ?? this.density, ); /// Designs switch whole: a theme animation snaps halfway rather than diff --git a/app/lib/ui/theme/compact_controls.dart b/app/lib/ui/theme/compact_controls.dart new file mode 100644 index 00000000..fc3eef75 --- /dev/null +++ b/app/lib/ui/theme/compact_controls.dart @@ -0,0 +1,220 @@ +import 'package:flutter/material.dart'; + +import 'compact_theme.dart'; + +const BorderRadius _corners = BorderRadius.all(Radius.circular(compactRadius)); +const RoundedRectangleBorder _rounded = RoundedRectangleBorder( + borderRadius: _corners, +); + +/// [base] with Compact's controls: Default's Material components at dense +/// heights, in [compactRadius] corners, with 4px-grid paddings. Floating +/// surfaces (menus, dialogs, sheets, tooltips, snack bars) keep Material's +/// elevation and fills; only their corners and insets change. +ThemeData compactControls(ThemeData base) { + final scheme = base.colorScheme; + final text = base.textTheme; + const icon = 18.0; + // Buttons: 32px tall under compact density, 12px side padding, 18px icons. + ButtonStyle buttons() => const ButtonStyle( + shape: WidgetStatePropertyAll(_rounded), + padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 12)), + iconSize: WidgetStatePropertyAll(icon), + ); + final menu = MenuStyle( + shape: const WidgetStatePropertyAll(_rounded), + padding: const WidgetStatePropertyAll(EdgeInsets.symmetric(vertical: 4)), + visualDensity: VisualDensity.compact, + ); + return base.copyWith( + filledButtonTheme: FilledButtonThemeData(style: buttons()), + elevatedButtonTheme: ElevatedButtonThemeData(style: buttons()), + outlinedButtonTheme: OutlinedButtonThemeData(style: buttons()), + textButtonTheme: TextButtonThemeData( + style: buttons().copyWith( + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 8), + ), + ), + ), + // Material 3's icon button ignores the theme's density unless its own + // style sets one: 32px drawn, its target padded to 40px on touch. + iconButtonTheme: const IconButtonThemeData( + style: ButtonStyle( + visualDensity: VisualDensity.compact, + iconSize: WidgetStatePropertyAll(icon), + // A square 32px button around its 18px icon. + padding: WidgetStatePropertyAll(EdgeInsets.all(7)), + shape: WidgetStatePropertyAll(_rounded), + ), + ), + segmentedButtonTheme: SegmentedButtonThemeData( + style: buttons().copyWith( + visualDensity: VisualDensity.compact, + textStyle: WidgetStatePropertyAll(text.labelLarge), + ), + ), + // A 40px action (Material's small FAB) and a 40px extended one. + floatingActionButtonTheme: FloatingActionButtonThemeData( + shape: _rounded, + iconSize: icon, + sizeConstraints: const BoxConstraints.tightFor(width: 40, height: 40), + // Only a least height: a larger text scale still grows the label. + extendedSizeConstraints: const BoxConstraints( + minHeight: 40, + minWidth: 64, + ), + extendedPadding: const EdgeInsetsDirectional.only(start: 12, end: 16), + extendedIconLabelSpacing: 8, + extendedTextStyle: text.labelLarge, + ), + menuTheme: MenuThemeData(style: menu), + dropdownMenuTheme: DropdownMenuThemeData( + menuStyle: menu, + textStyle: text.bodyMedium, + inputDecorationTheme: const InputDecorationTheme(isDense: true), + ), + menuButtonTheme: MenuButtonThemeData( + style: MenuItemButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 12), + minimumSize: const Size(0, 32), + textStyle: text.bodyMedium, + iconSize: icon, + ), + ), + popupMenuTheme: PopupMenuThemeData( + shape: _rounded, + menuPadding: const EdgeInsets.symmetric(vertical: 4), + labelTextStyle: WidgetStatePropertyAll(text.bodyMedium), + textStyle: text.bodyMedium, + ), + dialogTheme: DialogThemeData( + shape: _rounded, + titleTextStyle: text.titleLarge?.copyWith(color: scheme.onSurface), + contentTextStyle: text.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), + actionsPadding: const EdgeInsets.fromLTRB(16, 0, 16, 12), + ), + bottomSheetTheme: const BottomSheetThemeData( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.vertical( + top: Radius.circular(compactRadius), + ), + ), + ), + snackBarTheme: SnackBarThemeData( + shape: _rounded, + contentTextStyle: text.bodyMedium?.copyWith( + color: scheme.onInverseSurface, + ), + insetPadding: const EdgeInsets.fromLTRB(12, 4, 12, 12), + ), + tooltipTheme: TooltipThemeData( + decoration: BoxDecoration( + color: scheme.inverseSurface, + borderRadius: _corners, + ), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + textStyle: text.bodySmall?.copyWith(color: scheme.onInverseSurface), + waitDuration: const Duration(milliseconds: 400), + ), + // A hairline on every card variant: the theme's shape replaces each + // variant's own, so an outlined card (a graph node) keeps its outline. + cardTheme: CardThemeData( + shape: RoundedRectangleBorder( + borderRadius: _corners, + side: BorderSide(color: scheme.outlineVariant), + ), + margin: const EdgeInsets.all(4), + ), + chipTheme: ChipThemeData( + shape: _rounded, + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + labelPadding: const EdgeInsets.symmetric(horizontal: 4), + labelStyle: text.labelLarge, + iconTheme: const IconThemeData(size: 16), + ), + inputDecorationTheme: const InputDecorationTheme( + isDense: true, + contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ), + searchBarTheme: SearchBarThemeData( + shape: const WidgetStatePropertyAll(_rounded), + constraints: const BoxConstraints(minWidth: 240, minHeight: 36), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 12), + ), + textStyle: WidgetStatePropertyAll(text.bodyMedium), + hintStyle: WidgetStatePropertyAll( + text.bodyMedium?.copyWith(color: scheme.onSurfaceVariant), + ), + ), + listTileTheme: const ListTileThemeData( + dense: true, + visualDensity: VisualDensity.compact, + contentPadding: EdgeInsets.symmetric(horizontal: 12), + horizontalTitleGap: 12, + minLeadingWidth: 20, + minVerticalPadding: 6, + shape: _rounded, + ), + expansionTileTheme: const ExpansionTileThemeData( + tilePadding: EdgeInsets.symmetric(horizontal: 12), + childrenPadding: EdgeInsets.symmetric(horizontal: 12), + shape: Border(), + collapsedShape: Border(), + ), + navigationRailTheme: NavigationRailThemeData( + minWidth: 64, + labelType: NavigationRailLabelType.none, + indicatorShape: _rounded, + indicatorColor: scheme.secondaryContainer, + selectedIconTheme: IconThemeData( + size: icon, + color: scheme.onSecondaryContainer, + ), + unselectedIconTheme: IconThemeData( + size: icon, + color: scheme.onSurfaceVariant, + ), + groupAlignment: -1, + ), + navigationBarTheme: NavigationBarThemeData( + height: 64, + indicatorShape: _rounded, + labelTextStyle: WidgetStatePropertyAll(text.labelMedium), + iconTheme: const WidgetStatePropertyAll(IconThemeData(size: icon)), + ), + tabBarTheme: TabBarThemeData( + labelStyle: text.labelLarge, + unselectedLabelStyle: text.labelLarge, + labelPadding: const EdgeInsets.symmetric(horizontal: 12), + ), + dividerTheme: const DividerThemeData(space: 8, thickness: 1), + badgeTheme: BadgeThemeData( + smallSize: 6, + largeSize: 14, + textStyle: text.labelSmall?.copyWith(fontSize: 10), + padding: const EdgeInsets.symmetric(horizontal: 4), + ), + checkboxTheme: const CheckboxThemeData( + visualDensity: VisualDensity.compact, + ), + radioTheme: const RadioThemeData(visualDensity: VisualDensity.compact), + scrollbarTheme: const ScrollbarThemeData( + radius: Radius.circular(3), + thickness: WidgetStatePropertyAll(6), + ), + drawerTheme: const DrawerThemeData( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.horizontal( + right: Radius.circular(compactRadius), + ), + ), + ), + datePickerTheme: const DatePickerThemeData(shape: _rounded), + timePickerTheme: const TimePickerThemeData(shape: _rounded), + ); +} diff --git a/app/lib/ui/theme/compact_theme.dart b/app/lib/ui/theme/compact_theme.dart new file mode 100644 index 00000000..1771db87 --- /dev/null +++ b/app/lib/ui/theme/compact_theme.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; + +import 'app_design.dart'; +import 'app_design_tokens.dart'; +import 'app_theme.dart'; +import 'compact_controls.dart'; +import 'compact_typography.dart'; + +/// Compact's corner radius: every card, field, button, chip, menu, dialog, +/// sheet, tooltip, snack bar, bubble and window takes it. +const double compactRadius = 6; + +/// The Compact design's theme: Default's Material 3 colours and surfaces, +/// packed for a big monitor and long runs and chats. A smaller type scale +/// ([compactTextTheme]), Material's compact visual density, 18px icons, and +/// [compactRadius] corners on every surface. On a touch device controls keep +/// a 40px tap target (Material's padded target under compact density); on a +/// pointer device they shrink to their drawn size. +ThemeData compactTheme(Brightness brightness, {String? fontFamily}) { + final standard = brightness == Brightness.dark + ? appDarkTheme(fontFamily: fontFamily) + : appLightTheme(fontFamily: fontFamily); + final textTheme = compactTextTheme(standard.textTheme); + final themed = standard.copyWith( + visualDensity: VisualDensity.compact, + materialTapTargetSize: DesignDensity.pointerPlatform + ? MaterialTapTargetSize.shrinkWrap + : MaterialTapTargetSize.padded, + textTheme: textTheme, + primaryTextTheme: compactTextTheme(standard.primaryTextTheme), + iconTheme: standard.iconTheme.copyWith( + size: DesignDensity.compact.iconSize, + ), + primaryIconTheme: standard.primaryIconTheme.copyWith( + size: DesignDensity.compact.iconSize, + ), + extensions: const [ + AppDesignTokens( + design: AppDesign.compact, + radius: compactRadius, + reading: compactReading, + density: DesignDensity.compact, + ), + ], + ); + return compactControls(themed); +} diff --git a/app/lib/ui/theme/compact_typography.dart b/app/lib/ui/theme/compact_typography.dart new file mode 100644 index 00000000..d485f140 --- /dev/null +++ b/app/lib/ui/theme/compact_typography.dart @@ -0,0 +1,36 @@ +import 'package:flutter/material.dart'; + +import 'app_design_styles.dart'; + +/// Compact's reading type: the interface face at the dense body size +/// (`bodyLarge`, 14px), a little more line height than the role's so long +/// answers stay easy to follow, and about two thirds of a line between +/// paragraphs. +const ReadingType compactReading = ReadingType(height: 1.5, paragraphGap: 0.6); + +/// [base] (Material 3's type scale, in the device's interface face) at +/// Compact's sizes: body 13px, labels 11-12px, list and dialog titles 14 and +/// 18px. Line heights sit on a 2px step so rows of mixed roles still line up +/// on the 4px grid. Weights, colours, families and tracking stay Material's; +/// text scaling still applies on top. +TextTheme compactTextTheme(TextTheme base) { + TextStyle? sized(TextStyle? style, double size, double line) => + style?.copyWith(fontSize: size, height: line / size); + return base.copyWith( + displayLarge: sized(base.displayLarge, 44, 52), + displayMedium: sized(base.displayMedium, 36, 44), + displaySmall: sized(base.displaySmall, 28, 36), + headlineLarge: sized(base.headlineLarge, 26, 32), + headlineMedium: sized(base.headlineMedium, 22, 28), + headlineSmall: sized(base.headlineSmall, 20, 26), + titleLarge: sized(base.titleLarge, 18, 24), + titleMedium: sized(base.titleMedium, 14, 20), + titleSmall: sized(base.titleSmall, 13, 18), + bodyLarge: sized(base.bodyLarge, 14, 20), + bodyMedium: sized(base.bodyMedium, 13, 18), + bodySmall: sized(base.bodySmall, 11.5, 16), + labelLarge: sized(base.labelLarge, 13, 18), + labelMedium: sized(base.labelMedium, 12, 16), + labelSmall: sized(base.labelSmall, 11, 14), + ); +} diff --git a/app/lib/ui/theme/design_density.dart b/app/lib/ui/theme/design_density.dart new file mode 100644 index 00000000..3e978bb0 --- /dev/null +++ b/app/lib/ui/theme/design_density.dart @@ -0,0 +1,119 @@ +import 'package:flutter/foundation.dart'; + +/// How tightly a design packs the interface: the spacing inside and between +/// components, icon and avatar sizes, the navigation rail's width and labels +/// and the floating window title bar. [comfortable] is the Default look; +/// every widget that reads a density keeps its own value under it, so the +/// comfortable designs draw exactly as before. +/// +/// A dense design sets [spacing] below 1: [space] then scales a widget's own +/// spacing and snaps it to the 4px grid, so every component tightens by the +/// same proportion instead of each picking its own number. +@immutable +class DesignDensity { + const DesignDensity({ + this.spacing = 1, + this.iconSize, + this.avatarSize = 40, + this.railWidth = 96, + this.railLabels = true, + this.titleBarHeight = 40, + }); + + /// The Default density. + static const DesignDensity comfortable = DesignDensity(); + + /// The Compact density: spacing at 60% on the 4px grid, 18px icons, 28px + /// avatars, an icon-only 64px rail and a 32px window title bar. + static const DesignDensity compact = DesignDensity( + spacing: 0.6, + iconSize: 18, + avatarSize: 28, + railWidth: 64, + railLabels: false, + titleBarHeight: 32, + ); + + /// The proportion of a widget's own spacing this density keeps. + final double spacing; + + /// The interface's icon size; null keeps Material's 24. + final double? iconSize; + + /// A list row's leading avatar. + final double avatarSize; + + /// The destination rail's width on a wide window. + final double railWidth; + + /// Whether the rail labels its destinations under their icons; without + /// them the rail shows icons with tooltips. + final bool railLabels; + + /// A floating window's title bar height, before text scaling. + final double titleBarHeight; + + /// Whether this density is tighter than [comfortable]. + bool get dense => spacing < 1; + + /// [comfortable] spacing under this density: unchanged at [spacing] 1, + /// otherwise scaled and snapped to the 4px grid (a gap under 4px keeps a + /// 2px step, so a hairline gap never collapses to nothing). + double space(double comfortable) { + if (spacing == 1 || comfortable <= 0) return comfortable; + final scaled = comfortable * spacing; + if (scaled < 4) return scaled < 3 ? 2 : 4; + return (scaled / 4).round() * 4.0; + } + + /// [comfortable] edge inset (a row's or a panel's side padding) under this + /// density: halfway between [space] and the comfortable value, on the 4px + /// grid, so a dense row's text still keeps clear of the pane's edge + /// (16px becomes 12px at Compact). + double inset(double comfortable) { + if (spacing == 1 || comfortable <= 0) return comfortable; + final scaled = comfortable * (1 + spacing) / 2; + return scaled < 4 ? 4 : (scaled / 4).round() * 4.0; + } + + /// The least height a tappable row keeps under this density: nothing + /// beyond its content when comfortable (its own padding already gives + /// room) or on a pointer device, and 40px on a touch device, so a dense + /// row stays easy to hit with a finger. + double get minTouchRow { + if (!dense) return 0; + return pointerPlatform ? 0 : 40; + } + + /// Whether the device drives the app with a pointer (desktop, including a + /// desktop browser). Reads the device's platform, not the theme's: web + /// themes are pinned to Android. + static bool get pointerPlatform => switch (defaultTargetPlatform) { + TargetPlatform.macOS || + TargetPlatform.linux || + TargetPlatform.windows => true, + TargetPlatform.android || + TargetPlatform.iOS || + TargetPlatform.fuchsia => false, + }; + + @override + bool operator ==(Object other) => + other is DesignDensity && + other.spacing == spacing && + other.iconSize == iconSize && + other.avatarSize == avatarSize && + other.railWidth == railWidth && + other.railLabels == railLabels && + other.titleBarHeight == titleBarHeight; + + @override + int get hashCode => Object.hash( + spacing, + iconSize, + avatarSize, + railWidth, + railLabels, + titleBarHeight, + ); +} diff --git a/app/test/features/settings/settings_design_section_test.dart b/app/test/features/settings/settings_design_section_test.dart index 6b2185ae..2ca10305 100644 --- a/app/test/features/settings/settings_design_section_test.dart +++ b/app/test/features/settings/settings_design_section_test.dart @@ -114,4 +114,36 @@ void main() { await next.restore(); expect(next.design, AppDesign.paper); }); + + testWidgets('choosing Compact stores it, densifies the page live, draws ' + 'a denser swatch and is restored on the next launch', (tester) async { + final store = MemoryAppDesignStore(); + final designs = AppDesignController(store: store); + await _pump(tester, designs); + + final swatch = tester.widget( + find.descendant( + of: find.byKey(settingsDesignKey(AppDesign.compact)), + matching: find.byType(DesignSwatchPreview), + ), + ); + expect(swatch.lines, greaterThan(2)); + expect(find.text(AppDesign.compact.description), findsOneWidget); + final before = tester.getSize(find.byKey(settingsDesignKey(AppDesign.paper))); + + await tester.tap(find.text(AppDesign.compact.label)); + await tester.pumpAndSettle(); + expect(store.id, 'compact'); + expect(designs.design, AppDesign.compact); + final tokens = _tokens(tester); + expect(tokens.density.dense, isTrue); + expect(tokens.transcript, TranscriptStyle.bubbles); + // The rows themselves tighten at once. + final after = tester.getSize(find.byKey(settingsDesignKey(AppDesign.paper))); + expect(after.height, lessThan(before.height)); + + final next = AppDesignController(store: MemoryAppDesignStore(store.id)); + await next.restore(); + expect(next.design, AppDesign.compact); + }); } diff --git a/app/test/ui/layout/app_list_row_test.dart b/app/test/ui/layout/app_list_row_test.dart index 57447ee3..f1375fe4 100644 --- a/app/test/ui/layout/app_list_row_test.dart +++ b/app/test/ui/layout/app_list_row_test.dart @@ -265,6 +265,7 @@ void main() { (AppDesign.standard, false, true), (AppDesign.terminal, true, false), (AppDesign.paper, false, false), + (AppDesign.compact, false, true), ]) { testWidgets('${design.label}: the open row is clearly marked', ( tester, diff --git a/app/test/ui/theme/compact_design_test.dart b/app/test/ui/theme/compact_design_test.dart new file mode 100644 index 00000000..a135f72e --- /dev/null +++ b/app/test/ui/theme/compact_design_test.dart @@ -0,0 +1,174 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; +import 'package:pipelines_app/ui/theme/app_design_tokens.dart'; +import 'package:pipelines_app/ui/theme/app_theme.dart'; + +ThemeData _theme(AppDesign design, Brightness brightness, {String? font}) => + brightness == Brightness.dark + ? design.dark(fontFamily: font) + : design.light(fontFamily: font); + +BorderRadius? _radiusOf(ShapeBorder? shape) => + (shape as RoundedRectangleBorder?)?.borderRadius as BorderRadius?; + +void main() { + const six = BorderRadius.all(Radius.circular(6)); + + test('Compact is listed with a stable id, a label and one line', () { + expect(AppDesign.fromId('compact'), AppDesign.compact); + expect(AppDesign.compact.label, 'Compact'); + expect(AppDesign.compact.description, isNot(contains('\n'))); + expect(AppDesign.compact.usesInterfaceFont, isTrue); + expect(AppDesign.compact.swatchLines, greaterThan(2)); + for (final design in AppDesign.values) { + if (design != AppDesign.compact) expect(design.swatchLines, 2); + } + }); + + test('Compact tokens: Default chat and composer, tonal rows, 6px corners, ' + 'the compact density and tighter paragraphs', () { + for (final brightness in Brightness.values) { + final tokens = _theme( + AppDesign.compact, + brightness, + ).extension()!; + expect(tokens.design, AppDesign.compact); + expect(tokens.radius, 6); + expect(tokens.flat, isFalse); + expect(tokens.frame, isNull); + expect(tokens.transcript, TranscriptStyle.bubbles); + expect(tokens.composer, ComposerStyle.pill); + expect(tokens.selectedRow, SelectedRowStyle.tonal); + expect(tokens.density, DesignDensity.compact); + expect(tokens.density.dense, isTrue); + expect(tokens.density.iconSize, 18); + expect(tokens.density.railLabels, isFalse); + expect(tokens.density.railWidth, lessThan(96)); + expect(tokens.reading.family, isNull); + expect(tokens.reading.paragraphGap, lessThan(0.9)); + expect(tokens.denseCorners(BorderRadius.circular(12)), six); + } + }); + + test('the comfortable designs keep the comfortable density', () { + for (final design in [AppDesign.terminal, AppDesign.paper]) { + final tokens = design.light().extension()!; + expect(tokens.density, DesignDensity.comfortable); + expect(tokens.reading.paragraphGap, 0.9); + final twelve = BorderRadius.circular(12); + expect(tokens.denseCorners(twelve), twelve); + } + expect(AppDesignTokens.standard.density, DesignDensity.comfortable); + // Default still builds its exact themes, with no tokens at all. + expect(AppDesign.standard.light(), appLightTheme()); + expect(AppDesign.standard.dark(), appDarkTheme()); + }); + + test('density spacing: unchanged when comfortable, 4px grid when dense', () { + const comfortable = DesignDensity.comfortable; + for (final value in [2.0, 4.0, 6.0, 10.0, 13.0, 16.0, 24.0]) { + expect(comfortable.space(value), value); + expect(comfortable.inset(value), value); + } + expect(comfortable.minTouchRow, 0); + const compact = DesignDensity.compact; + expect(compact.space(16), 8); + expect(compact.space(13), 8); + expect(compact.space(12), 8); + expect(compact.space(8), 4); + expect(compact.space(6), 4); + expect(compact.space(4), 2); + expect(compact.space(24), 16); + expect(compact.inset(16), 12); + expect(compact.inset(12), 8); + for (final value in [8.0, 12.0, 16.0, 24.0, 32.0]) { + expect(compact.space(value) % 4, 0, reason: 'on the 4px grid'); + expect(compact.space(value), lessThan(value)); + } + }); + + test('Compact keeps Default colours and packs type, icons and density', () { + for (final brightness in Brightness.values) { + final theme = _theme(AppDesign.compact, brightness, font: 'Inter'); + final standard = _theme(AppDesign.standard, brightness, font: 'Inter'); + expect(theme.colorScheme, standard.colorScheme); + expect(theme.scaffoldBackgroundColor, standard.scaffoldBackgroundColor); + final text = theme.textTheme; + expect(text.bodyMedium?.fontSize, 13); + expect(text.bodyLarge?.fontSize, 14); + expect(text.labelMedium?.fontSize, 12); + expect(text.labelSmall?.fontSize, 11); + expect(text.titleMedium?.fontSize, 14); + for (final style in [text.bodyMedium, text.titleLarge, text.labelLarge]) { + // The device's interface font still applies. + expect(style?.fontFamily, 'Inter'); + expect(style?.fontSize, lessThan(20)); + // Line heights on a 2px step. + expect((style!.fontSize! * style.height!) % 2, closeTo(0, 0.01)); + } + expect(theme.visualDensity, VisualDensity.compact); + expect(theme.iconTheme.size, 18); + expect( + theme.iconButtonTheme.style?.visualDensity, + VisualDensity.compact, + reason: 'Material 3 icon buttons ignore the theme density otherwise', + ); + } + }); + + test('every floating and framed surface takes the same 6px corners', () { + final theme = AppDesign.compact.light(); + expect(_radiusOf(theme.dialogTheme.shape), six); + expect(_radiusOf(theme.popupMenuTheme.shape), six); + expect(_radiusOf(theme.snackBarTheme.shape), six); + expect(_radiusOf(theme.cardTheme.shape), six); + expect(_radiusOf(theme.chipTheme.shape), six); + expect(_radiusOf(theme.floatingActionButtonTheme.shape), six); + expect(_radiusOf(theme.listTileTheme.shape), six); + expect(_radiusOf(theme.navigationRailTheme.indicatorShape), six); + expect( + _radiusOf(theme.menuTheme.style?.shape?.resolve(const {})), + six, + ); + expect( + _radiusOf(theme.filledButtonTheme.style?.shape?.resolve(const {})), + six, + ); + expect( + _radiusOf(theme.iconButtonTheme.style?.shape?.resolve(const {})), + six, + ); + expect( + (theme.tooltipTheme.decoration as BoxDecoration?)?.borderRadius, + six, + ); + final sheet = _radiusOf(theme.bottomSheetTheme.shape)!; + expect(sheet.topLeft, const Radius.circular(6)); + expect(sheet.bottomLeft, Radius.zero); + // A card keeps its outline under the theme's shape (outlined graph + // nodes would otherwise lose it). + final card = theme.cardTheme.shape! as RoundedRectangleBorder; + expect(card.side.color, theme.colorScheme.outlineVariant); + }); + + test('pointer devices shrink targets; touch devices keep 40px', () { + for (final (platform, pointer) in [ + (TargetPlatform.linux, true), + (TargetPlatform.macOS, true), + (TargetPlatform.windows, true), + (TargetPlatform.android, false), + (TargetPlatform.iOS, false), + ]) { + debugDefaultTargetPlatformOverride = platform; + final theme = AppDesign.compact.light(); + expect( + theme.materialTapTargetSize, + pointer ? MaterialTapTargetSize.shrinkWrap : MaterialTapTargetSize.padded, + ); + expect(DesignDensity.compact.minTouchRow, pointer ? 0 : 40); + } + debugDefaultTargetPlatformOverride = null; + }); +} diff --git a/app/test/ui/theme/compact_rendering_test.dart b/app/test/ui/theme/compact_rendering_test.dart new file mode 100644 index 00000000..aa1e15f1 --- /dev/null +++ b/app/test/ui/theme/compact_rendering_test.dart @@ -0,0 +1,225 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_bubble.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/navigation_rail.dart'; +import 'package:pipelines_app/shell/windows/window_frame.dart'; +import 'package:pipelines_app/ui/layout/app_list_avatar.dart'; +import 'package:pipelines_app/ui/layout/app_list_row.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; + +/// Compact as drawn: thin rows, a narrow icon-only rail, 32px icon buttons +/// (40px targets on touch), tight bubbles, a slim window title bar, and no +/// clipping at a large text scale. +void main() { + Future pump( + WidgetTester tester, + Widget child, { + AppDesign design = AppDesign.compact, + double textScale = 1, + double width = 560, + }) async { + tester.view.physicalSize = Size(width, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MaterialApp( + theme: design.light(), + home: MediaQuery( + data: MediaQueryData( + size: Size(width, 900), + textScaler: TextScaler.linear(textScale), + ), + child: Scaffold(body: child), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Widget rows() => ListView( + children: [ + AppListRow( + key: const Key('one'), + title: const Text('Release train'), + time: '09:12', + onTap: () {}, + ), + AppListRow( + key: const Key('two'), + leading: AppListAvatar.initial('Release', color: Colors.teal), + title: const Text('Release notes'), + subtitle: const Text('claude-opus · /workspace/demo'), + time: '10m', + selected: true, + onTap: () {}, + ), + ], + ); + + testWidgets('pointer: a 36px single-line row and a ~52px two-line row', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + await pump(tester, rows()); + // Each row includes its 1px divider. + expect(tester.getSize(find.byKey(const Key('one'))).height, 37); + final two = tester.getSize(find.byKey(const Key('two'))).height; + expect(two, inInclusiveRange(50, 56)); + expect( + tester.getSize(find.byType(AppListAvatar)).height, + DesignDensity.compact.avatarSize, + ); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('touch: rows keep a 40px target', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + await pump(tester, rows()); + expect( + tester.getSize(find.byKey(const Key('one'))).height, + greaterThanOrEqualTo(41), + ); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('Default rows keep their comfortable size', (tester) async { + await pump(tester, rows(), design: AppDesign.standard); + expect( + tester.getSize(find.byKey(const Key('one'))).height, + greaterThan(48), + ); + expect( + tester.getSize(find.byType(AppListAvatar)).height, + kAppListAvatarSize, + ); + }); + + testWidgets('rows and bubbles do not clip at 2x text', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + await pump( + tester, + Column( + children: [ + SizedBox(height: 300, child: rows()), + const ChatUserBubble(child: Text('Summarise the release notes.')), + ], + ), + textScale: 2, + width: 360, + ); + expect(tester.takeException(), isNull); + final one = tester.getSize(find.byKey(const Key('one'))).height; + expect(one, greaterThan(37), reason: 'the row grows with its text'); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('icon buttons: 32px on a pointer device, 40px target on touch', ( + tester, + ) async { + Widget button() => IconButton( + key: const Key('b'), + onPressed: () {}, + icon: const Icon(Icons.add), + ); + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + await pump(tester, Center(child: button())); + expect(tester.getSize(find.byKey(const Key('b'))), const Size(32, 32)); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + await pump(tester, Center(child: button())); + expect(tester.getSize(find.byKey(const Key('b'))), const Size(40, 40)); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('the rail is narrow and icon-only, each icon with a tooltip', ( + tester, + ) async { + await pump( + tester, + Row( + children: [ + ShellNavigationRail( + selected: AppDestination.runs, + icon: (d) => Icon(destinationDetails(d).icon), + onSelected: (_) {}, + ), + const Expanded(child: SizedBox()), + ], + ), + width: 1200, + ); + final rail = find.byKey(const ValueKey('shell.navigation-rail.surface')); + expect(tester.getSize(rail).width, DesignDensity.compact.railWidth); + expect( + tester.widget(find.byType(NavigationRail)).labelType, + NavigationRailLabelType.none, + ); + for (final destination in shellTabDestinations) { + expect( + find.byTooltip(destinationDetails(destination).label), + findsOneWidget, + ); + } + expect(find.byTooltip('Settings'), findsOneWidget); + // Settings' indicator matches the tabs' 56x32 rather than the rail. + final indicator = find.descendant( + of: find.byKey(const ValueKey('shell.destination.settings')), + matching: find.byType(Container), + ); + expect(tester.getSize(indicator.first), const Size(56, 32)); + }); + + testWidgets('the operator bubble is tight, in the design corners', ( + tester, + ) async { + await pump(tester, const ChatUserBubble(child: Text('Ship it'))); + final material = tester.widget( + find.descendant( + of: find.byType(ChatUserBubble), + matching: find.byType(Material), + ), + ); + final shape = material.shape! as RoundedRectangleBorder; + expect(shape.borderRadius, BorderRadius.circular(6)); + final padding = tester.widget( + find.descendant( + of: find.byType(ChatUserBubble), + matching: find.byType(Padding), + ), + ); + expect(padding.padding, const EdgeInsets.symmetric(horizontal: 12, vertical: 8)); + final gap = chatParagraphGap(tester.element(find.text('Ship it')), 14); + expect(gap, closeTo(14 * 0.6, 0.01)); + }); + + testWidgets('a floating window has a 32px title bar and 6px corners', ( + tester, + ) async { + late BuildContext context; + await pump( + tester, + Builder( + builder: (c) { + context = c; + return const SizedBox(); + }, + ), + ); + expect(windowTitleBarHeight(context), 32); + expect(windowCorners(context), BorderRadius.circular(6)); + await pump( + tester, + Builder( + builder: (c) { + context = c; + return const SizedBox(); + }, + ), + design: AppDesign.paper, + ); + expect(windowTitleBarHeight(context), 40); + expect(windowCorners(context), BorderRadius.circular(windowCornerRadius)); + }); +} From f8e4d78466468ab5f96a7bb3cf906ca718da01ac Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 20:47:17 +0000 Subject: [PATCH 02/18] Chat: a phone layout tiles floating chats; a wide one floats them again At phone width (Quick switch or Chat stack) floating windows are hidden, so a floating chat could not be opened from the list, the stack or the peek. The phone now holds each floating chat as an ordinary pane while the server set keeps it floating; widening floats it again. Co-Authored-By: Claude Opus 5.5 --- app/lib/features/chat/chat_screen_float.dart | 93 +++++- .../features/chat/chat_screen_workspace.dart | 34 ++- app/lib/features/chat/screen.dart | 1 + .../chat/chat_floating_phone_test.dart | 287 ++++++++++++++++++ 4 files changed, 410 insertions(+), 5 deletions(-) create mode 100644 app/test/features/chat/chat_floating_phone_test.dart diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart index afc224e3..d2ae80a5 100644 --- a/app/lib/features/chat/chat_screen_float.dart +++ b/app/lib/features/chat/chat_screen_float.dart @@ -8,7 +8,8 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { void _bindWindows() { final windows = widget.windows; if (windows == null) return; - _workspace.showOutside = windows.show; + _workspace.showOutside = _showOutside; + windows.manager.addListener(_windowsChanged); windows.tiling = _tiling = ChatTiling( holds: _workspace.holdsSession, dock: _dockSession, @@ -35,9 +36,99 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { if (windows != null && identical(windows.tiling, _tiling)) { windows.tiling = null; } + windows?.manager.removeListener(_windowsChanged); _workspace.showOutside = null; } + /// A chat out in a window comes to the top on a wide layout. A phone + /// ignores floating: the chat leaves its (hidden) window and opens as a + /// pane, still floating in the server's set. + bool _showOutside(String sessionId) { + final windows = widget.windows; + if (windows == null) return false; + if (!_phoneIgnoresFloat) return windows.show(sessionId); + _holdForPhone(windows, sessionId); + return false; + } + + /// Takes [sessionId] out of its window, to be tiled on this phone layout. + void _holdForPhone(ChatWindows windows, String sessionId) { + final window = windows.windows + .where((window) => window.contentId == sessionId) + .firstOrNull; + if (window == null) return; + _phoneDocked.add(sessionId); + windows.manager.close(window.id); + } + + /// Whether the last build was a phone's layout, which tiles floating chats. + bool? _builtPhoneFloat; + bool _followingFloat = false; + + /// Called from build: a change between a phone and a wide layout moves + /// the floating chats between panes and windows after the frame. + void _trackFloatLayout() { + if (widget.windows == null) return; + final phone = _phoneIgnoresFloat; + if (phone == _builtPhoneFloat) return; + _builtPhoneFloat = phone; + _followFloatLayoutSoon(); + } + + void _windowsChanged() { + if (_builtPhoneFloat == true && + (widget.windows?.windows.isNotEmpty ?? false)) { + _followFloatLayoutSoon(); + } + } + + void _followFloatLayoutSoon() { + if (_followingFloat) return; + _followingFloat = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _followingFloat = false; + if (mounted) _followFloatLayout(); + }); + } + + /// On a phone every floating chat becomes a pane (the chat on screen + /// stays); on a wide layout the chats held that way float again. + void _followFloatLayout() { + final windows = widget.windows; + if (windows == null) return; + final phone = _phoneIgnoresFloat; + final ids = phone + ? windows.floatingSessionIds.toList() + : _phoneDocked.toList(); + if (ids.isEmpty) return; + // One write for the whole move: the chats stay floating in the set. + _applyingServerWorkspace = true; + try { + if (phone) { + final active = _workspace.activePaneId; + for (final id in ids) { + _holdForPhone(windows, id); + _workspace.dock(id); + } + if (active != null) _workspace.activate(active); + } else { + for (final id in ids) { + final pane = _workspace.panes + .where((pane) => pane.sessionId == id) + .firstOrNull; + if (pane == null) continue; + _workspace.detach(pane.id); + windows.float(id); + } + _phoneDocked.clear(); + } + } finally { + _applyingServerWorkspace = false; + } + _syncOpenWorkspace(); + if (!phone && _workspace.paneCount == 0) _back(); + } + /// Panes float only on a wide layout, beside the chat list. bool get _floatsHere => widget.windows != null && !_pageOpen && showsListBesideDetail(context); diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 16cbbc7a..6bff87db 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -113,9 +113,18 @@ mixin _ChatScreenWorkspace on State { ChatWorkspaceBinding? _workspaceBinding; String? _workspaceScope; + /// Chats that float in windows on a wide layout, held as ordinary panes + /// while the layout is a phone's (see `_ChatScreenFloat`). They stay + /// floating in the server's set, so a wide layout floats them again. + final Set _phoneDocked = {}; + + /// Whether this layout ignores floating: a phone's, where windows are + /// hidden and the chats are navigated one at a time. + bool get _phoneIgnoresFloat => + mounted && widget.windows != null && !showsListBesideDetail(context); + Iterable _serverWorkspaceEntries() sync* { - final floating = - widget.windows?.floatingSessionIds.toSet() ?? const {}; + final floating = {...?widget.windows?.floatingSessionIds, ..._phoneDocked}; for (final pane in _workspace.panes) { yield ChatOpenWorkspaceEntry( pane.sessionId, @@ -231,9 +240,24 @@ mixin _ChatScreenWorkspace on State { ]); } _applyingServerWorkspace = true; + final phone = _phoneIgnoresFloat; try { final windows = widget.windows; - if (windows != null) { + for (final entry in snapshot.entries) { + if (!entry.floating) _phoneDocked.remove(entry.sessionId); + } + if (windows != null && phone) { + // A phone tiles the floating chats too; they float again when the + // layout is wide. + for (final entry in snapshot.entries.where((e) => e.floating)) { + _phoneDocked.add(entry.sessionId); + final window = windows.windows + .where((window) => window.contentId == entry.sessionId) + .firstOrNull; + if (window != null) windows.manager.close(window.id); + } + } + if (windows != null && !phone) { final entriesBySession = { for (final entry in snapshot.entries) entry.sessionId: entry, }; @@ -259,7 +283,7 @@ mixin _ChatScreenWorkspace on State { } _workspace.reconcileSessions( snapshot.entries - .where((entry) => !entry.floating) + .where((entry) => phone || !entry.floating) .map((entry) => entry.sessionId), ); if (keepInitial) { @@ -364,6 +388,8 @@ mixin _ChatScreenWorkspace on State { '${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}'; if (_workspaceSignature == signature) return; _workspaceSignature = signature; + // A phone-held floating chat the operator closed is no longer open. + _phoneDocked.removeWhere((id) => !_workspace.holdsSession(id)); _syncOpenWorkspace(); _touchActiveChat(); void update() { diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index b41c0cee..6599be8b 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -550,6 +550,7 @@ class _ChatScreenState extends State (_) => _publishWorkspaceRoute(), ); } + _trackFloatLayout(); _offeredNext = selected != null && _nextAfter(selected) != null; // A phone opens a chat as a real Navigator page with stock Back. A wide // window keeps the destination rail and the chat list beside the open diff --git a/app/test/features/chat/chat_floating_phone_test.dart b/app/test/features/chat/chat_floating_phone_test.dart new file mode 100644 index 00000000..2bcd43bf --- /dev/null +++ b/app/test/features/chat/chat_floating_phone_test.dart @@ -0,0 +1,287 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/chat_runtime.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; +import 'package:pipelines_app/features/chat/windows/chat_windows.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/shell/windows/window_host.dart'; +import 'package:pipelines_app/shell/windows/window_kind.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; +import 'package:pipelines_app/shell/windows/window_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +/// A chat server with an open-chat set whose entries may float. +class _Server extends FakeChatGateway { + _Server(this.open, this.floating); + List open; + Set floating; + int revision = 1; + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b', 'c']) + {'id': id, 'title': 'Chat $id', 'directory': '/home/$id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + if (type == 'chat_open_workspace') { + final request = fields['chat_open_workspace_request'] as Map?; + var rejected = false; + if (request != null && request['seed'] != true) { + if (request['base_revision'] != revision) { + rejected = true; + } else { + final entries = (request['entries'] as List).cast(); + open = [for (final e in entries) '${e['session_id']}']; + floating = { + for (final e in entries) + if (e['floating'] == true) '${e['session_id']}', + }; + revision++; + } + } + return Future.value({ + 'type': 'chat_open_workspace', + 'chat_open_workspace': _body(rejected), + }); + } + return super.call(type, fields); + } + + JsonMap _body([bool rejected = false]) => { + 'revision': revision, + 'entries': [ + for (final id in open) + {'session_id': id, if (floating.contains(id)) 'floating': true}, + ], + if (rejected) 'rejected': true, + }; + + void change(List ids, Set floats) { + open = ids; + floating = floats; + revision++; + emitRaw({ + 'type': 'chat_open_workspace_changed', + 'chat_open_workspace': _body(), + }); + } +} + +class _Store implements WindowStore { + String? value; + @override + Future read() async => value; + @override + Future write(String record) async { + value = record; + return true; + } +} + +const _wide = Size(1800, 1000); +const _phone = Size(390, 844); + +class _App { + late final _Server server; + late final ChatRuntime runtime; + late final WindowManager manager; + late final ChatWindows windows; + + Future start(WidgetTester tester, {Size size = _wide}) async { + SharedPreferences.setMockInitialValues({}); + _resize(tester, size); + addTearDown(tester.view.reset); + server = _Server(['a', 'b'], {'b'})..history = (_) async => chatPage([]); + bindServerIdentity(server, 'server-a'); + runtime = ChatRuntime(gateway: server, serverKey: 'server-a'); + manager = WindowManager( + kinds: WindowKinds(), + store: _Store(), + server: 'server-a', + ); + windows = ChatWindows( + manager: manager, + runtime: runtime, + openInChat: (_) {}, + )..start(); + await manager.restore(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Stack( + fit: StackFit.expand, + children: [ + ChatScreen( + gateway: server, + persistWorkspace: true, + runtime: runtime, + windows: windows, + ), + Positioned.fill(child: WindowHost(manager: manager)), + ], + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future stop(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + windows.dispose(); + runtime.dispose(); + manager.dispose(); + server.close(); + } + + List get floatingWindows => [ + for (final w in windows.windows) w.contentId, + ]; +} + +void _resize(WidgetTester tester, Size size) { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; +} + +List _panes(WidgetTester tester) { + final workspace = find.byType(ChatWorkspace, skipOffstage: false); + if (workspace.evaluate().isEmpty) return const []; + return tester + .widget(workspace) + .controller + .panes + .map((pane) => pane.sessionId) + .toList(); +} + +Finder _shownThread(String id) => find + .byWidgetPredicate((w) => w is ChatThreadView && w.sessionId == id) + .hitTestable(); + +void main() { + final navigation = MobileChatNavigationController.instance; + tearDown(() { + unawaited(navigation.setValue(MobileChatNavigation.quickSwitch)); + }); + + testWidgets('a phone tiles a floating chat; a wide layout floats it again', ( + tester, + ) async { + final app = _App(); + await app.start(tester); + expect(app.floatingWindows, ['b']); + + _resize(tester, _phone); + await tester.pumpAndSettle(); + // No window at phone width: the chat is an open chat like the others, + // and the server still has it floating. + expect(app.floatingWindows, isEmpty); + expect(app.server.floating, {'b'}); + + // The list opens it full screen. + await tester.tap(find.byKey(const Key('chat-row-b'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + expect(_panes(tester), ['a', 'b']); + + _resize(tester, _wide); + await tester.pumpAndSettle(); + expect(app.floatingWindows, ['b']); + expect(_panes(tester), ['a']); + expect(_shownThread('a'), findsOneWidget); + expect(app.server.floating, {'b'}); + expect(app.server.open, ['a', 'b']); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('a floating chat opens from the list on a phone from the start', ( + tester, + ) async { + final app = _App(); + await app.start(tester, size: _phone); + expect(app.floatingWindows, isEmpty); + await tester.tap(find.byKey(const Key('chat-row-b'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + expect(_panes(tester), ['a', 'b']); + expect(app.server.floating, {'b'}); + await app.stop(tester); + }); + + testWidgets('quick switch reaches a floating chat on a phone', ( + tester, + ) async { + final app = _App(); + await app.start(tester, size: _phone); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + expect(_shownThread('a'), findsOneWidget); + final controller = tester + .widget(find.byType(ChatWorkspace)) + .controller; + final b = controller.panes.firstWhere((pane) => pane.sessionId == 'b'); + await tester.tap(find.byKey(ValueKey('chat-peek-${b.id}'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + expect(app.floatingWindows, isEmpty); + await app.stop(tester); + }); + + testWidgets('the chat stack reaches a floating chat on a phone', ( + tester, + ) async { + unawaited(navigation.setValue(MobileChatNavigation.chatStack)); + final app = _App(); + await app.start(tester, size: _phone); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-stack'))); + await tester.pumpAndSettle(); + final controller = tester + .widget(find.byType(ChatWorkspace)) + .controller; + final b = controller.panes.firstWhere((pane) => pane.sessionId == 'b'); + await tester.tap(find.byKey(ValueKey('chat-stack-button-${b.id}'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + await app.stop(tester); + }); + + testWidgets('a chat another device floats stays tiled on a phone', ( + tester, + ) async { + final app = _App(); + await app.start(tester, size: _phone); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + app.server.change(['a', 'b', 'c'], {'b', 'c'}); + await tester.pumpAndSettle(); + expect(app.floatingWindows, isEmpty); + expect(_panes(tester), ['a', 'b', 'c']); + + // Removing a held chat on the phone drops it from the open chats. + final controller = tester + .widget(find.byType(ChatWorkspace, skipOffstage: false)) + .controller; + controller.close(controller.panes.last.id); + await tester.pumpAndSettle(); + expect(app.server.open, ['a', 'b']); + expect(app.server.floating, {'b'}); + await app.stop(tester); + }); +} From fba3b924f1804b4f4c438f6e8bd08cd4091815dd Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 21:17:51 +0000 Subject: [PATCH 03/18] Chat stack: hold and drag to reorder the open chats, or onto x to remove A 300 ms hold lifts a chat in the open column; dragging opens a gap and dropping commits through ChatWorkspaceController.movePane, the pane order the server syncs. An x comes in at the bottom while dragging; dropping on it removes the chat with Undo, which restores its place. Escape, a cancelled pointer or a drop away from the column put it back. Move up, Move down and Remove are semantic actions. Repaint-only motion; reduced motion swaps at once. Also keep floating-layout tracking out of initState, and let the capture kit hold a press before a drag. Co-Authored-By: Claude Opus 5.5 --- app/lib/features/chat/chat_screen_float.dart | 1 + app/lib/features/chat/chat_screen_stack.dart | 13 +- .../features/chat/chat_screen_workspace.dart | 7 +- .../chat/stack/chat_stack_column.dart | 343 ++++++++---------- .../chat/stack/chat_stack_column_items.dart | 230 ++++++++++++ .../features/chat/stack/chat_stack_disc.dart | 91 ++++- .../features/chat/stack/chat_stack_drag.dart | 320 ++++++++++++++++ .../chat/stack/chat_stack_drag_shift.dart | 145 ++++++++ .../features/chat/stack/chat_stack_fab.dart | 6 + .../chat/stack/chat_stack_handles.dart | 95 +++++ .../chat/stack/chat_stack_remove_target.dart | 106 ++++++ .../workspace/chat_workspace_controller.dart | 18 + app/notes/chat-stack.md | 50 ++- .../chat/stack/chat_stack_drag_test.dart | 323 +++++++++++++++++ .../chat/stack/chat_stack_fab_test.dart | 13 +- .../chat/stack/chat_stack_screen_test.dart | 25 -- app/tool/capture/README.md | 2 +- app/tool/capture/capture.mjs | 6 +- app/tool/capture/page.mjs | 6 +- app/tool/capture/touch.mjs | 27 +- 20 files changed, 1573 insertions(+), 254 deletions(-) create mode 100644 app/lib/features/chat/stack/chat_stack_column_items.dart create mode 100644 app/lib/features/chat/stack/chat_stack_drag.dart create mode 100644 app/lib/features/chat/stack/chat_stack_drag_shift.dart create mode 100644 app/lib/features/chat/stack/chat_stack_handles.dart create mode 100644 app/lib/features/chat/stack/chat_stack_remove_target.dart create mode 100644 app/test/features/chat/stack/chat_stack_drag_test.dart diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart index d2ae80a5..ec2102e3 100644 --- a/app/lib/features/chat/chat_screen_float.dart +++ b/app/lib/features/chat/chat_screen_float.dart @@ -68,6 +68,7 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { /// Called from build: a change between a phone and a wide layout moves /// the floating chats between panes and windows after the frame. void _trackFloatLayout() { + _phoneLayout = !showsListBesideDetail(context); if (widget.windows == null) return; final phone = _phoneIgnoresFloat; if (phone == _builtPhoneFloat) return; diff --git a/app/lib/features/chat/chat_screen_stack.dart b/app/lib/features/chat/chat_screen_stack.dart index 37b067cd..9597a65e 100644 --- a/app/lib/features/chat/chat_screen_stack.dart +++ b/app/lib/features/chat/chat_screen_stack.dart @@ -59,6 +59,7 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace { onOpen: (entry) => _openBySelection(entry.session), onAdd: (context) => _addPane(context, title: ChatStackColumn.addLabel), onRemove: _removeFromStack, + onReorder: (entry, index) => _workspace.movePane(entry.paneId, index), ), ), ); @@ -66,6 +67,7 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace { void _removeFromStack(ChatStackEntry entry) { final messenger = ScaffoldMessenger.maybeOf(context); final wasActive = _workspace.activePaneId; + final index = _workspace.panes.indexWhere((p) => p.id == entry.paneId); _closePane(entry.paneId); if (messenger == null) return; messenger @@ -75,16 +77,23 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace { content: Text('Removed ${entry.title} from open chats'), action: SnackBarAction( label: 'Undo', - onPressed: () => _restoreToStack(entry, wasActive), + onPressed: () => _restoreToStack(entry, wasActive, index), ), ), ); } - void _restoreToStack(ChatStackEntry entry, String? wasActive) { + /// Undo: the chat comes back at its old place in the open-chat order. + void _restoreToStack(ChatStackEntry entry, String? wasActive, int index) { if (!mounted || _workspace.holdsSession(entry.sessionId)) return; _openedSessions[entry.sessionId] = entry.session; _workspace.splitActive(entry.sessionId, ChatSplitAxis.horizontal); + final restored = _workspace.panes + .where((pane) => pane.sessionId == entry.sessionId) + .firstOrNull; + if (restored != null && index >= 0) { + _workspace.movePane(restored.id, index); + } // The chat on screen stays on screen unless it was the one removed. if (wasActive != null && wasActive != entry.paneId) { final kept = _workspace.panes diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 6bff87db..5e2646ba 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -118,10 +118,13 @@ mixin _ChatScreenWorkspace on State { /// floating in the server's set, so a wide layout floats them again. final Set _phoneDocked = {}; + /// Whether the last build laid out for a phone (set in build, so it is + /// safe to read from callbacks and initState). + bool _phoneLayout = false; + /// Whether this layout ignores floating: a phone's, where windows are /// hidden and the chats are navigated one at a time. - bool get _phoneIgnoresFloat => - mounted && widget.windows != null && !showsListBesideDetail(context); + bool get _phoneIgnoresFloat => widget.windows != null && _phoneLayout; Iterable _serverWorkspaceEntries() sync* { final floating = {...?widget.windows?.floatingSessionIds, ..._phoneDocked}; diff --git a/app/lib/features/chat/stack/chat_stack_column.dart b/app/lib/features/chat/stack/chat_stack_column.dart index 908c9eb9..1b70ddf4 100644 --- a/app/lib/features/chat/stack/chat_stack_column.dart +++ b/app/lib/features/chat/stack/chat_stack_column.dart @@ -1,12 +1,15 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/semantics.dart'; import 'package:flutter/services.dart'; -import '../../../ui/theme/app_design_tokens.dart'; +import 'chat_stack_column_items.dart'; import 'chat_stack_disc.dart'; +import 'chat_stack_drag.dart'; import 'chat_stack_entry.dart'; import 'chat_stack_motion.dart'; -import 'chat_stack_pose.dart'; +import 'chat_stack_remove_target.dart'; /// The chat stack fanned out: a scrim over the screen and the open chats in /// a column rising from the stack's own slot, each avatar with its name in a @@ -19,10 +22,16 @@ import 'chat_stack_pose.dart'; /// bottom slots go to the frequent action (switching), and the rarer one /// ends the list where the operator reads "and more". /// +/// A short hold lifts a chat ([ChatStackDrag]): dragged up or down it +/// reorders the open chats, the others sliding aside to open its slot; +/// dropped on the "×" that comes in at the bottom it leaves them. Add chat +/// stays put. The same moves are semantic actions on each chat. +/// /// Nothing here rebuilds per frame: every item moves through -/// [ChatStackPoseTransition] and fades through [FadeTransition], both -/// repaint-only. -class ChatStackColumn extends StatelessWidget { +/// `ChatStackPoseTransition` and `ChatStackDragShift` and fades through +/// [FadeTransition], all repaint-only; a drag rebuilds the column only as it +/// starts and ends. +class ChatStackColumn extends StatefulWidget { const ChatStackColumn({ super.key, required this.motion, @@ -34,6 +43,7 @@ class ChatStackColumn extends StatelessWidget { required this.onAdd, required this.onDismiss, this.onRemove, + this.onReorder, }); final ChatStackMotion motion; @@ -52,23 +62,112 @@ class ChatStackColumn extends StatelessWidget { final VoidCallback onAdd; final VoidCallback onDismiss; - /// Long press removes a chat from the open chats; null when it cannot - /// (the only open chat). + /// Removes a chat from the open chats (dropped on the "×"); null when it + /// cannot (the only open chat). final ValueChanged? onRemove; + /// Moves a chat to an index of the open-chat order; null when the chats + /// cannot be reordered. + final void Function(ChatStackEntry entry, int index)? onReorder; + static const removeLabel = 'Remove from open chats'; + static const moveUpLabel = 'Move up'; + static const moveDownLabel = 'Move down'; static const addLabel = 'Add chat'; + @override + State createState() => _ChatStackColumnState(); +} + +class _ChatStackColumnState extends State + with TickerProviderStateMixin { + late final ChatStackDrag _drag = ChatStackDrag( + vsync: this, + pitch: kChatStackPitch, + )..addListener(_dragChanged); + + /// The remove target's centre in this column's box, from the last layout. + Offset? _removeCenter; + + List get _entries => widget.entries; + List get _ids => [for (final entry in _entries) entry.paneId]; + + /// A hold lifts a chat when there is something to do with it. + bool get _draggable => + widget.interactive && + ((widget.onReorder != null && _entries.length > 1) || + widget.onRemove != null); + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _drag.reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + } + + @override + void didUpdateWidget(covariant ChatStackColumn oldWidget) { + super.didUpdateWidget(oldWidget); + // Folding, or the open chats changing under the finger (another + // device), puts the dragged chat back. + if (!widget.interactive || + (_drag.dragging && !listEquals(_ids, _drag.order))) { + _drag.cancel(); + } + } + + @override + void dispose() { + _drag.dispose(); + super.dispose(); + } + + void _dragChanged() { + if (mounted) setState(() {}); + } + + void _start(ChatStackEntry entry) { + if (_draggable) _drag.start(entry.paneId, _ids); + } + + void _move(LongPressMoveUpdateDetails details) { + if (!_drag.dragging) return; + final box = context.findRenderObject() as RenderBox?; + final center = _removeCenter; + final over = + widget.onRemove != null && + box != null && + center != null && + (box.globalToLocal(details.globalPosition) - center).distance <= + kChatStackRemoveReach; + _drag.move(details.offsetFromOrigin, overRemove: over); + } + + void _end(ChatStackEntry entry) { + if (!_drag.dragging) return; + switch (_drag.end()) { + case ChatStackDropMove(:final index): + widget.onReorder?.call(entry, index); + case ChatStackDropRemove(): + widget.onRemove?.call(entry); + case ChatStackDropBack(): + break; + } + } + + void _escape() => _drag.dragging ? _drag.cancel() : widget.onDismiss(); + @override Widget build(BuildContext context) { final media = MediaQuery.of(context); final scheme = Theme.of(context).colorScheme; final dark = Theme.of(context).brightness == Brightness.dark; final rtl = Directionality.of(context) == TextDirection.rtl; + final anchor = widget.anchor; + final depths = widget.depths; return LayoutBuilder( builder: (context, constraints) { final size = constraints.biggest; - final count = motion.count; + final count = widget.motion.count; final height = (count - 1) * kChatStackPitch + kChatStackSlot; final top = media.padding.top + 8; final available = anchor.bottom - top; @@ -80,39 +179,70 @@ class ChatStackColumn extends StatelessWidget { final width = size.width - endInset - margin; final labelMax = width - kChatStackSlot - kChatStackLabelGap; // Paint the pile's order while it opens: hidden layers first, the - // top of the pile last. + // top of the pile last; a lifted chat above them all. final order = [for (var i = 0; i < count; i++) i] ..sort((a, b) => (depths[b] ?? 99).compareTo(depths[a] ?? 99)); - final items = Stack( - clipBehavior: Clip.none, - children: [ - for (final i in order) ...[ - _label(context, i, labelMax), - _item(context, i), - ], - ], + final lifted = _entries.indexWhere((e) => e.paneId == _drag.lifted); + if (lifted >= 0) order.add(order.removeAt(order.indexOf(lifted))); + // The remove target: centred in the band below the stack's slot + // (over the composer), clear of the safe area. + const r = kChatStackRemoveSize / 2; + final floor = size.height - media.padding.bottom; + final removeCenter = Offset( + size.width / 2, + math.max( + anchor.bottom + 4, + math.min((anchor.bottom + floor) / 2, floor - r - 8), + ), + ); + _removeCenter = removeCenter; + final items = ChatStackColumnItems( + motion: widget.motion, + entries: _entries, + order: order, + labelMax: labelMax, + drag: _drag, + draggable: _draggable, + onOpen: widget.onOpen, + onAdd: widget.onAdd, + onRemove: widget.onRemove, + onReorder: widget.onReorder, + onDragStart: _start, + onDragMove: _move, + onDragEnd: _end, ); return CallbackShortcuts( - bindings: { - const SingleActivator(LogicalKeyboardKey.escape): onDismiss, - }, + bindings: {const SingleActivator(LogicalKeyboardKey.escape): _escape}, child: FocusScope( autofocus: true, child: IgnorePointer( - ignoring: !interactive, + ignoring: !widget.interactive, child: Stack( children: [ Positioned.fill( child: FadeTransition( - opacity: motion.scrim, + opacity: widget.motion.scrim, child: ModalBarrier( color: scheme.scrim.withValues(alpha: dark ? .5 : .32), dismissible: true, - onDismiss: onDismiss, + onDismiss: widget.onDismiss, semanticsLabel: 'Close chats', ), ), ), + // Under the column: a chat dragged onto it is drawn over it. + if (widget.onRemove != null) + Positioned( + left: removeCenter.dx - r, + top: removeCenter.dy - r, + width: kChatStackRemoveSize, + height: kChatStackRemoveSize, + child: ChatStackRemoveTarget( + shown: _drag.removeShown, + hover: _drag.hover, + reduced: _drag.reduced, + ), + ), PositionedDirectional( end: endInset, bottom: size.height - anchor.bottom, @@ -144,169 +274,4 @@ class ChatStackColumn extends StatelessWidget { }, ); } - - Widget _item(BuildContext context, int i) { - final entry = i < entries.length ? entries[i] : null; - return PositionedDirectional( - key: ValueKey('chat-stack-item-${entry?.paneId ?? 'add'}'), - end: 0, - bottom: 0, - // The transform is outermost: the boxes under it sit at the stack's - // slot, and only a transform passes hits on to where it paints them. - child: ChatStackPoseTransition( - progress: motion.move[i], - from: motion.from[i], - to: motion.target[i], - child: FadeTransition( - opacity: motion.fade[i], - child: KeyedSubtree( - key: ValueKey('chat-stack-button-${entry?.paneId ?? 'add'}'), - child: entry == null ? _addButton(context) : _chatButton(entry), - ), - ), - ), - ); - } - - Widget _label(BuildContext context, int i, double maxWidth) { - final entry = i < entries.length ? entries[i] : null; - return PositionedDirectional( - key: ValueKey('chat-stack-label-${entry?.paneId ?? 'add'}'), - end: kChatStackSlot + kChatStackLabelGap, - bottom: 0, - height: kChatStackSlot, - child: ChatStackPoseTransition( - progress: motion.label[i], - from: motion.labelFrom[i], - to: motion.target[i], - child: ExcludeSemantics( - child: FadeTransition( - opacity: motion.label[i], - child: Align( - alignment: AlignmentDirectional.centerEnd, - widthFactor: 1, - child: ConstrainedBox( - constraints: BoxConstraints(maxWidth: maxWidth), - child: GestureDetector( - onTap: entry == null ? onAdd : () => onOpen(entry), - onLongPress: entry == null || onRemove == null - ? null - : () => onRemove!(entry), - child: ChatStackLabel( - text: entry?.title ?? addLabel, - color: entry?.color(context), - emphasized: entry?.current ?? false, - ), - ), - ), - ), - ), - ), - ), - ); - } - - Widget _chatButton(ChatStackEntry entry) => Builder( - builder: (context) { - final remove = onRemove; - final ring = entry.current - ? entry.color(context) ?? Theme.of(context).colorScheme.primary - : null; - return Semantics( - container: true, - button: true, - selected: entry.current, - label: entry.title, - hint: entry.current ? 'Open now' : null, - onTap: () => onOpen(entry), - customSemanticsActions: remove == null - ? null - : { - const CustomSemanticsAction(label: removeLabel): () => - remove(entry), - }, - child: _Tappable( - autofocus: entry.current, - onTap: () => onOpen(entry), - onLongPress: remove == null ? null : () => remove(entry), - child: ChatStackDisc(ring: ring, child: chatStackAvatar(entry)), - ), - ); - }, - ); - - Widget _addButton(BuildContext context) { - final scheme = Theme.of(context).colorScheme; - final tokens = AppDesignTokens.of(context); - return Semantics( - container: true, - button: true, - label: addLabel, - onTap: onAdd, - child: _Tappable( - onTap: onAdd, - child: ChatStackDisc( - child: DecoratedBox( - decoration: ShapeDecoration( - color: tokens.flat ? null : scheme.primaryContainer, - shape: chatStackShape(tokens).copyWith( - side: tokens.flat - ? BorderSide(color: scheme.primary.withValues(alpha: .55)) - : BorderSide.none, - ), - ), - child: Icon( - Icons.add, - color: tokens.flat ? scheme.primary : scheme.onPrimaryContainer, - ), - ), - ), - ), - ); - } -} - -/// A disc's ink and focus: the splash is drawn over the disc (the disc is -/// opaque, so ink under it would never show), in the design's shape. -class _Tappable extends StatelessWidget { - const _Tappable({ - required this.child, - required this.onTap, - this.onLongPress, - this.autofocus = false, - }); - - final Widget child; - final VoidCallback onTap; - final VoidCallback? onLongPress; - final bool autofocus; - - @override - Widget build(BuildContext context) { - final shape = chatStackShape(AppDesignTokens.of(context)); - return Stack( - children: [ - child, - Positioned.fill( - child: Padding( - padding: const EdgeInsets.all( - (kChatStackSlot - kChatStackDisc) / 2, - ), - child: Material( - type: MaterialType.transparency, - shape: shape, - clipBehavior: Clip.antiAlias, - child: InkWell( - autofocus: autofocus, - excludeFromSemantics: true, - customBorder: shape, - onTap: onTap, - onLongPress: onLongPress, - ), - ), - ), - ), - ], - ); - } } diff --git a/app/lib/features/chat/stack/chat_stack_column_items.dart b/app/lib/features/chat/stack/chat_stack_column_items.dart new file mode 100644 index 00000000..8389216e --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_column_items.dart @@ -0,0 +1,230 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/semantics.dart'; + +import '../../../ui/theme/app_design_tokens.dart'; +import 'chat_stack_column.dart'; +import 'chat_stack_disc.dart'; +import 'chat_stack_drag.dart'; +import 'chat_stack_drag_shift.dart'; +import 'chat_stack_entry.dart'; +import 'chat_stack_handles.dart'; +import 'chat_stack_motion.dart'; +import 'chat_stack_pose.dart'; + +/// The open column's avatars and name pills, each placed at the stack's +/// slot and moved by the open motion ([ChatStackPoseTransition]) and by a +/// drag ([ChatStackDragShift]), painted in [order]. +class ChatStackColumnItems extends StatelessWidget { + const ChatStackColumnItems({ + super.key, + required this.motion, + required this.entries, + required this.order, + required this.labelMax, + required this.drag, + required this.draggable, + required this.onOpen, + required this.onAdd, + required this.onDragStart, + required this.onDragMove, + required this.onDragEnd, + this.onRemove, + this.onReorder, + }); + + final ChatStackMotion motion; + final List entries; + + /// Item indices in paint order, the last on top. + final List order; + final double labelMax; + final ChatStackDrag drag; + + /// Whether a hold lifts a chat. + final bool draggable; + final ValueChanged onOpen; + final VoidCallback onAdd; + final ValueChanged onDragStart; + final ValueChanged onDragMove; + final ValueChanged onDragEnd; + final ValueChanged? onRemove; + final void Function(ChatStackEntry entry, int index)? onReorder; + + @override + Widget build(BuildContext context) => Stack( + clipBehavior: Clip.none, + children: [ + for (final i in order) ...[_label(context, i), _item(context, i)], + ], + ); + + ChatStackEntry? _entry(int i) => i < entries.length ? entries[i] : null; + + /// [child] lifted by a hold when [entry] can be dragged. + Widget _handle(ChatStackEntry? entry, Widget child) => ChatStackDragHandle( + onStart: entry == null || !draggable ? null : () => onDragStart(entry), + onMove: onDragMove, + onEnd: entry == null ? null : () => onDragEnd(entry), + onCancel: drag.cancel, + child: child, + ); + + /// [child] where the drag paints [entry]'s item; Add chat never moves. + Widget _shift(ChatStackEntry? entry, Widget child, {bool scales = true}) => + entry == null + ? child + : ChatStackDragShift( + item: drag.item(entry.paneId), + scales: scales, + child: child, + ); + + Animation? _lift(ChatStackEntry? entry) => + entry != null && entry.paneId == drag.lifted ? drag.lift : null; + + Widget _item(BuildContext context, int i) { + final entry = _entry(i); + return PositionedDirectional( + key: ValueKey('chat-stack-item-${entry?.paneId ?? 'add'}'), + end: 0, + bottom: 0, + // The transforms are outermost: the boxes under them sit at the + // stack's slot, and only a transform passes hits on to where it paints + // them. + child: ChatStackPoseTransition( + progress: motion.move[i], + from: motion.from[i], + to: motion.target[i], + child: _shift( + entry, + FadeTransition( + opacity: motion.fade[i], + child: KeyedSubtree( + key: ValueKey('chat-stack-button-${entry?.paneId ?? 'add'}'), + child: entry == null + ? _addButton(context) + : _chatButton(context, entry, i), + ), + ), + ), + ), + ); + } + + Widget _label(BuildContext context, int i) { + final entry = _entry(i); + return PositionedDirectional( + key: ValueKey('chat-stack-label-${entry?.paneId ?? 'add'}'), + end: kChatStackSlot + kChatStackLabelGap, + bottom: 0, + height: kChatStackSlot, + child: ChatStackPoseTransition( + progress: motion.label[i], + from: motion.labelFrom[i], + to: motion.target[i], + // The pill moves with its avatar but keeps its size, so the gap + // between them stays even. + child: _shift( + entry, + scales: false, + ExcludeSemantics( + child: FadeTransition( + opacity: motion.label[i], + child: Align( + alignment: AlignmentDirectional.centerEnd, + widthFactor: 1, + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: labelMax), + child: _handle( + entry, + GestureDetector( + onTap: entry == null ? onAdd : () => onOpen(entry), + child: ChatStackLabel( + text: entry?.title ?? ChatStackColumn.addLabel, + color: entry?.color(context), + emphasized: entry?.current ?? false, + lift: _lift(entry), + ), + ), + ), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _chatButton(BuildContext context, ChatStackEntry entry, int index) { + final remove = onRemove; + final reorder = onReorder; + final last = entries.length - 1; + final ring = entry.current + ? entry.color(context) ?? Theme.of(context).colorScheme.primary + : null; + // Up is toward the top of the column: a later place in the order. + final actions = { + if (reorder != null && index < last) + const CustomSemanticsAction(label: ChatStackColumn.moveUpLabel): () => + reorder(entry, index + 1), + if (reorder != null && index > 0) + const CustomSemanticsAction(label: ChatStackColumn.moveDownLabel): () => + reorder(entry, index - 1), + if (remove != null) + const CustomSemanticsAction(label: ChatStackColumn.removeLabel): () => + remove(entry), + }; + return Semantics( + container: true, + button: true, + selected: entry.current, + label: entry.title, + hint: entry.current ? 'Open now' : null, + onTap: () => onOpen(entry), + customSemanticsActions: actions.isEmpty ? null : actions, + child: _handle( + entry, + ChatStackTappable( + autofocus: entry.current, + onTap: () => onOpen(entry), + child: ChatStackDisc( + ring: ring, + lift: _lift(entry), + child: chatStackAvatar(entry), + ), + ), + ), + ); + } + + Widget _addButton(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final tokens = AppDesignTokens.of(context); + return Semantics( + container: true, + button: true, + label: ChatStackColumn.addLabel, + onTap: onAdd, + child: ChatStackTappable( + onTap: onAdd, + child: ChatStackDisc( + child: DecoratedBox( + decoration: ShapeDecoration( + color: tokens.flat ? null : scheme.primaryContainer, + shape: chatStackShape(tokens).copyWith( + side: tokens.flat + ? BorderSide(color: scheme.primary.withValues(alpha: .55)) + : BorderSide.none, + ), + ), + child: Icon( + Icons.add, + color: tokens.flat ? scheme.primary : scheme.onPrimaryContainer, + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_disc.dart b/app/lib/features/chat/stack/chat_stack_disc.dart index 7f317378..391a3ac4 100644 --- a/app/lib/features/chat/stack/chat_stack_disc.dart +++ b/app/lib/features/chat/stack/chat_stack_disc.dart @@ -22,13 +22,17 @@ const double kChatStackLabelGap = 10; /// through each other, and its rim separates them. A raised design drops a /// short shadow; a flat one casts none, and its avatar frames itself. class ChatStackDisc extends StatelessWidget { - const ChatStackDisc({super.key, required this.child, this.ring}); + const ChatStackDisc({super.key, required this.child, this.ring, this.lift}); final Widget child; /// The rim's colour when it marks the current chat; null for the surface. final Color? ring; + /// While dragged (0 at rest, 1 lifted): a deeper shadow, or under a flat + /// design a frame in the primary colour. + final Animation? lift; + @override Widget build(BuildContext context) { final tokens = AppDesignTokens.of(context); @@ -42,16 +46,20 @@ class ChatStackDisc extends StatelessWidget { ); final ring = this.ring; final shape = chatStackShape(tokens); + final rest = ShapeDecoration( + color: ring ?? base, + // A flat design's avatar frames itself; the rim stays bare. + shape: shape, + shadows: !tokens.flat ? chatStackShadows(scheme) : null, + ); + final lift = this.lift; return SizedBox.square( dimension: kChatStackSlot, child: Center( - child: DecoratedBox( - decoration: ShapeDecoration( - color: ring ?? base, - // A flat design's avatar frames itself; the rim stays bare. - shape: shape, - shadows: !tokens.flat ? chatStackShadows(scheme) : null, - ), + child: chatStackLifted( + lift, + rest, + chatStackRaised(rest, tokens, scheme), child: SizedBox.square( dimension: kChatStackDisc, child: Center( @@ -93,6 +101,52 @@ List chatStackShadows(ColorScheme scheme) => [ ), ]; +/// A short, close shadow's lifted form: deeper and softer, as a card +/// picked up off the column. +List chatStackLiftShadows(ColorScheme scheme) => [ + BoxShadow( + color: scheme.shadow.withValues(alpha: .20), + blurRadius: 8, + offset: const Offset(0, 4), + ), + BoxShadow( + color: scheme.shadow.withValues(alpha: .14), + blurRadius: 22, + offset: const Offset(0, 12), + ), +]; + +/// [rest] as a dragged item wears it: the lifted shadow, or under a flat +/// design (which casts none) a frame in the primary colour. +ShapeDecoration chatStackRaised( + ShapeDecoration rest, + AppDesignTokens tokens, + ColorScheme scheme, +) { + final shape = rest.shape; + return ShapeDecoration( + color: rest.color, + shape: tokens.flat && shape is OutlinedBorder + ? shape.copyWith(side: BorderSide(color: scheme.primary, width: 1.5)) + : shape, + shadows: tokens.flat ? null : chatStackLiftShadows(scheme), + ); +} + +/// [child] over [rest], or blending to [raised] as [lift] runs: repaints +/// only. +Widget chatStackLifted( + Animation? lift, + ShapeDecoration rest, + ShapeDecoration raised, { + required Widget child, +}) => lift == null + ? DecoratedBox(decoration: rest, child: child) + : DecoratedBoxTransition( + decoration: DecorationTween(begin: rest, end: raised).animate(lift), + child: child, + ); + /// The name beside an avatar in the open column: a small pill tinted with /// the chat's colour over an opaque face, one line, ellipsised. class ChatStackLabel extends StatelessWidget { @@ -101,12 +155,16 @@ class ChatStackLabel extends StatelessWidget { required this.text, this.color, this.emphasized = false, + this.lift, }); final String text; final Color? color; final bool emphasized; + /// While dragged, as [ChatStackDisc.lift]. + final Animation? lift; + @override Widget build(BuildContext context) { final tokens = AppDesignTokens.of(context); @@ -122,12 +180,15 @@ class ChatStackLabel extends StatelessWidget { color: scheme.onSurface, fontWeight: emphasized ? FontWeight.w700 : FontWeight.w500, ); - return DecoratedBox( - decoration: ShapeDecoration( - color: fill, - shape: _labelShape(tokens), - shadows: tokens.flat ? null : chatStackShadows(scheme), - ), + final rest = ShapeDecoration( + color: fill, + shape: _labelShape(tokens), + shadows: tokens.flat ? null : chatStackShadows(scheme), + ); + return chatStackLifted( + lift, + rest, + chatStackRaised(rest, tokens, scheme), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), child: Text( @@ -141,7 +202,7 @@ class ChatStackLabel extends StatelessWidget { ); } - ShapeBorder _labelShape(AppDesignTokens tokens) { + OutlinedBorder _labelShape(AppDesignTokens tokens) { final side = tokens.frameSide ?? BorderSide.none; final r = tokens.radius; return r == null diff --git a/app/lib/features/chat/stack/chat_stack_drag.dart b/app/lib/features/chat/stack/chat_stack_drag.dart new file mode 100644 index 00000000..4c80ee51 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_drag.dart @@ -0,0 +1,320 @@ +import 'dart:ui' show lerpDouble; + +import 'package:flutter/animation.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// How long a press is held before the chat lifts for a drag: long enough +/// that a tap still opens the chat, short enough to feel immediate. +const Duration chatStackLiftDelay = Duration(milliseconds: 300); + +/// The lifted avatar's scale. +const double chatStackLiftScale = 1.1; + +/// The lifted avatar's scale, relative to lifted, over the remove target. +const double chatStackOverRemoveScale = .8; + +/// How long the neighbours take to slide aside, and the lifted chat to +/// settle into its slot (or back) after the drop. +const Duration chatStackShiftDuration = Duration(milliseconds: 200); +const Duration chatStackSettleDuration = Duration(milliseconds: 220); + +/// How long the remove target takes to come in and to light up. +const Duration chatStackRemoveDuration = Duration(milliseconds: 180); +const Duration chatStackHoverDuration = Duration(milliseconds: 140); + +/// Where one item of the open column is painted relative to its slot while +/// a chat is dragged; a render object repaints when it changes. +class ChatStackDragItem extends ChangeNotifier { + Offset _offset = Offset.zero; + double _scale = 1; + + Offset get offset => _offset; + double get scale => _scale; + + void _set(Offset offset, double scale) { + if (offset == _offset && scale == _scale) return; + _offset = offset; + _scale = scale; + notifyListeners(); + } +} + +/// What a drop does. +sealed class ChatStackDrop { + const ChatStackDrop(); +} + +/// Nothing: the chat settles back into its own slot. +class ChatStackDropBack extends ChatStackDrop { + const ChatStackDropBack(); +} + +/// The chat moves to [index] in the open-chat order. +class ChatStackDropMove extends ChatStackDrop { + const ChatStackDropMove(this.index); + final int index; +} + +/// The chat leaves the open chats. +class ChatStackDropRemove extends ChatStackDrop { + const ChatStackDropRemove(); +} + +/// One drag in the open column: which chat is lifted, the slot it would +/// drop into, whether it is over the remove target, and the motion of every +/// item. It notifies only when a drag starts or ends (the column then +/// rebuilds once); each pointer move only repaints the items that move. +class ChatStackDrag extends ChangeNotifier { + ChatStackDrag({required TickerProvider vsync, required this.pitch}) + : _vsync = vsync { + lift = AnimationController(vsync: vsync, duration: chatStackShiftDuration) + ..addListener(_paintLifted); + settle = + AnimationController(vsync: vsync, duration: chatStackSettleDuration) + ..addListener(_paintLifted) + ..addStatusListener(_settled); + removeShown = AnimationController( + vsync: vsync, + duration: chatStackRemoveDuration, + ); + hover = AnimationController(vsync: vsync, duration: chatStackHoverDuration) + ..addListener(_paintLifted); + } + + final TickerProvider _vsync; + + /// The distance between neighbouring slots. + final double pitch; + + /// Under reduced motion neighbours swap at once and nothing slides. + bool reduced = false; + + late final AnimationController lift; + late final AnimationController settle; + + /// The remove target's entrance, and its highlight while a chat is over + /// it. + late final AnimationController removeShown; + late final AnimationController hover; + + final Map _items = {}; + final Map _shifts = {}; + + /// The chat being dragged or settling; it paints above the others. + String? get lifted => _lifted; + String? _lifted; + + /// The chats' order when the drag started; null when none is dragged. + List? get order => _order; + List? _order; + int _from = 0; + int? _slot; + bool _over = false; + Offset _pointer = Offset.zero; + Offset _residual = Offset.zero; + + bool get dragging => _order != null; + bool get overRemove => _over; + + /// Where [id]'s item is painted; created on first use. + ChatStackDragItem item(String id) => + _items.putIfAbsent(id, ChatStackDragItem.new); + + static const _curve = Curves.easeOutCubic; + + /// Lifts [id] out of [order] (the chats, without Add chat). + void start(String id, List order) { + final from = order.indexOf(id); + if (from < 0) return; + if (_lifted != null) _finishSettle(); + _order = List.of(order); + _from = from; + _slot = from; + _over = false; + _pointer = Offset.zero; + _residual = Offset.zero; + _lifted = id; + HapticFeedback.mediumImpact(); + if (reduced) { + lift.value = 1; + removeShown.value = 1; + } else { + lift.forward(from: 0); + removeShown.forward(); + } + hover.value = 0; + notifyListeners(); + } + + /// The pointer moved [fromOrigin] since the press; [overRemove] says + /// whether it is over the remove target. + void move(Offset fromOrigin, {required bool overRemove}) { + final order = _order; + if (order == null) return; + _pointer = fromOrigin; + if (overRemove != _over) { + _over = overRemove; + if (overRemove) HapticFeedback.selectionClick(); + if (reduced) { + hover.value = overRemove ? 1 : 0; + } else { + overRemove ? hover.forward() : hover.reverse(); + } + } + // Far to the side of the column, or over the target, there is no slot: + // the gap closes and a drop there puts the chat back. + final inColumn = !overRemove && fromOrigin.dx.abs() <= pitch * 1.5; + final slot = inColumn + ? (_from - (fromOrigin.dy / pitch).round()).clamp(0, order.length - 1) + : null; + if (slot != _slot) { + if (slot != null && _slot != null) HapticFeedback.selectionClick(); + _slot = slot; + _shiftNeighbours(animate: !reduced); + } + _paintLifted(); + } + + /// Ends the drag and says what the drop does; the motion back (or into + /// the new slot) runs from here. + ChatStackDrop end() { + final order = _order; + if (order == null) return const ChatStackDropBack(); + final slot = _slot; + final ChatStackDrop drop = _over + ? const ChatStackDropRemove() + : slot != null && slot != _from + ? ChatStackDropMove(slot) + : const ChatStackDropBack(); + _order = null; + switch (drop) { + case ChatStackDropMove(:final index): + // The new order puts the neighbours where they are now drawn; the + // dragged chat glides from the finger into its new slot. + _slot = null; + _residual = _pointer + Offset(0, (index - _from) * pitch); + _shiftNeighbours(animate: false); + case ChatStackDropRemove(): + _slot = null; + _residual = Offset.zero; + _shiftNeighbours(animate: false); + case ChatStackDropBack(): + _slot = null; + _residual = _pointer; + _shiftNeighbours(animate: !reduced); + } + _release(); + return drop; + } + + /// Puts the chat back where it was (Escape, a cancelled pointer, the + /// column folding). + void cancel() { + if (_order == null) return; + _order = null; + _slot = null; + _residual = _pointer; + _shiftNeighbours(animate: !reduced); + _release(); + } + + void _release() { + _pointer = Offset.zero; + if (_over) HapticFeedback.selectionClick(); + _over = false; + if (reduced) { + hover.value = 0; + removeShown.value = 0; + lift.value = 0; + _residual = Offset.zero; + _finishSettle(); + return; + } + hover.reverse(); + removeShown.reverse(); + lift.reverse(); + settle.forward(from: 0); + } + + void _settled(AnimationStatus status) { + if (status == AnimationStatus.completed) _finishSettle(); + } + + void _finishSettle() { + settle.stop(); + final id = _lifted; + _residual = Offset.zero; + if (id != null) item(id)._set(Offset.zero, 1); + if (_order != null) return; + _lifted = null; + notifyListeners(); + } + + void _paintLifted() { + final id = _lifted; + if (id == null) return; + // Over the remove target the chat shrinks into it, so the target's + // lit rim shows around it. + final scale = + lerpDouble(1, chatStackLiftScale, _curve.transform(lift.value))! * + lerpDouble(1, chatStackOverRemoveScale, hover.value)!; + final offset = _order != null + ? _pointer + : _residual * (1 - _curve.transform(settle.value)); + item(id)._set(offset, scale); + } + + /// Slides each neighbour aside to open the gap at the current slot, or + /// back home when there is none. + void _shiftNeighbours({required bool animate}) { + final order = _order ?? const []; + final ids = {...order, ..._shifts.keys}; + final slot = _slot; + for (final id in ids) { + if (id == _lifted && _order != null) continue; + final i = order.indexOf(id); + var target = 0.0; + if (slot != null && i >= 0) { + // Down (toward the thumb) when the lifted chat goes above it, up + // when it goes below. + if (_from < slot && i > _from && i <= slot) target = 1; + if (slot < _from && i >= slot && i < _from) target = -1; + } + final shift = _shifts.putIfAbsent(id, () => _shiftFor(id)); + if (shift.value == target) continue; + if (animate) { + shift.animateTo( + target, + duration: chatStackShiftDuration, + curve: _curve, + ); + } else { + shift + ..stop() + ..value = target; + } + } + } + + AnimationController _shiftFor(String id) { + final shift = AnimationController.unbounded(vsync: _vsync); + shift.addListener(() => item(id)._set(Offset(0, shift.value * pitch), 1)); + return shift; + } + + @override + void dispose() { + lift.dispose(); + settle.dispose(); + removeShown.dispose(); + hover.dispose(); + for (final shift in _shifts.values) { + shift.dispose(); + } + for (final item in _items.values) { + item.dispose(); + } + super.dispose(); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_drag_shift.dart b/app/lib/features/chat/stack/chat_stack_drag_shift.dart new file mode 100644 index 00000000..292499a8 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_drag_shift.dart @@ -0,0 +1,145 @@ +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +import 'chat_stack_drag.dart'; + +/// Paints [child] where [item] says while a chat of the open column is +/// dragged: moved, and scaled about its centre when [scales]. A change only +/// repaints (the matrix and the layer are reused); hit tests follow it. At +/// rest it paints straight through, with no layer. +class ChatStackDragShift extends SingleChildRenderObjectWidget { + const ChatStackDragShift({ + super.key, + required this.item, + this.scales = true, + super.child, + }); + + final ChatStackDragItem item; + final bool scales; + + @override + RenderChatStackDragShift createRenderObject(BuildContext context) => + RenderChatStackDragShift(item: item, scales: scales); + + @override + void updateRenderObject( + BuildContext context, + RenderChatStackDragShift renderObject, + ) { + renderObject + ..item = item + ..scales = scales; + } +} + +class RenderChatStackDragShift extends RenderProxyBox { + RenderChatStackDragShift({ + required ChatStackDragItem item, + required bool scales, + }) { + _item = item; + _scales = scales; + } + + late ChatStackDragItem _item; + set item(ChatStackDragItem value) { + if (identical(value, _item)) return; + if (attached) _item.removeListener(_changed); + _item = value; + if (attached) _item.addListener(_changed); + _changed(); + } + + late bool _scales; + set scales(bool value) { + if (value == _scales) return; + _scales = value; + _changed(); + } + + final Matrix4 _matrix = Matrix4.identity(); + final LayerHandle _layer = LayerHandle(); + + bool get _moved => + _item.offset != Offset.zero || (_scales && _item.scale != 1); + + bool _wasMoved = false; + + void _changed() { + // Entering or leaving rest adds or drops the transform layer. + final moved = _moved; + if (moved != _wasMoved) { + _wasMoved = moved; + markNeedsCompositingBitsUpdate(); + } + markNeedsPaint(); + } + + @override + void attach(PipelineOwner owner) { + super.attach(owner); + _wasMoved = _moved; + _item.addListener(_changed); + } + + @override + void detach() { + _item.removeListener(_changed); + super.detach(); + } + + @override + void dispose() { + _layer.layer = null; + super.dispose(); + } + + @override + bool get alwaysNeedsCompositing => child != null && _moved; + + Matrix4 _current() { + final offset = _item.offset; + final scale = _scales ? _item.scale : 1.0; + final cx = size.width / 2; + final cy = size.height / 2; + return _matrix + ..setIdentity() + ..translateByDouble(offset.dx + cx, offset.dy + cy, 0, 1) + ..scaleByDouble(scale, scale, 1, 1) + ..translateByDouble(-cx, -cy, 0, 1); + } + + @override + void paint(PaintingContext context, Offset offset) { + if (child == null) return; + if (!_moved) { + _layer.layer = null; + super.paint(context, offset); + return; + } + _layer.layer = context.pushTransform( + needsCompositing, + offset, + _current(), + super.paint, + oldLayer: _layer.layer, + ); + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + if (!_moved) return super.hitTestChildren(result, position: position); + return result.addWithPaintTransform( + transform: _current(), + position: position, + hitTest: (result, position) => + super.hitTestChildren(result, position: position), + ); + } + + @override + void applyPaintTransform(RenderBox child, Matrix4 transform) { + if (_moved) transform.multiply(_current()); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_fab.dart b/app/lib/features/chat/stack/chat_stack_fab.dart index eafa67bb..7fb9e419 100644 --- a/app/lib/features/chat/stack/chat_stack_fab.dart +++ b/app/lib/features/chat/stack/chat_stack_fab.dart @@ -20,6 +20,7 @@ class ChatStackFab extends StatefulWidget { required this.onOpen, required this.onAdd, this.onRemove, + this.onReorder, }); /// The open chats in their synced order; one is [ChatStackEntry.current]. @@ -30,6 +31,10 @@ class ChatStackFab extends StatefulWidget { final ValueChanged onAdd; final ValueChanged? onRemove; + /// Moves a chat to an index of the open-chat order (a drag in the open + /// column, or its Move up and Move down actions). + final void Function(ChatStackEntry entry, int index)? onReorder; + @override State createState() => ChatStackFabState(); } @@ -216,6 +221,7 @@ class ChatStackFabState extends State onAdd: _add, onDismiss: collapse, onRemove: canRemove ? _remove : null, + onReorder: widget.onReorder, ); }, child: AnimatedOpacity( diff --git a/app/lib/features/chat/stack/chat_stack_handles.dart b/app/lib/features/chat/stack/chat_stack_handles.dart new file mode 100644 index 00000000..3bb76256 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_handles.dart @@ -0,0 +1,95 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/theme/app_design_tokens.dart'; +import 'chat_stack_disc.dart'; +import 'chat_stack_drag.dart'; + +/// Lifts [child] for a drag after a short hold ([chatStackLiftDelay]); a +/// quicker tap still reaches [child]'s own tap. Null callbacks leave the +/// child alone. +class ChatStackDragHandle extends StatelessWidget { + const ChatStackDragHandle({ + super.key, + required this.child, + this.onStart, + this.onMove, + this.onEnd, + this.onCancel, + }); + + final Widget child; + final VoidCallback? onStart; + final ValueChanged? onMove; + final VoidCallback? onEnd; + final VoidCallback? onCancel; + + @override + Widget build(BuildContext context) { + if (onStart == null) return child; + return RawGestureDetector( + // The items offer moving and removing as semantic actions instead. + excludeFromSemantics: true, + gestures: { + LongPressGestureRecognizer: + GestureRecognizerFactoryWithHandlers( + () => LongPressGestureRecognizer( + duration: chatStackLiftDelay, + debugOwner: this, + ), + (recognizer) { + recognizer + ..onLongPressStart = ((_) => onStart?.call()) + ..onLongPressMoveUpdate = onMove + ..onLongPressEnd = ((_) => onEnd?.call()) + ..onLongPressCancel = onCancel; + }, + ), + }, + child: child, + ); + } +} + +/// A disc's ink and focus: the splash is drawn over the disc (the disc is +/// opaque, so ink under it would never show), in the design's shape. +class ChatStackTappable extends StatelessWidget { + const ChatStackTappable({ + super.key, + required this.child, + required this.onTap, + this.autofocus = false, + }); + + final Widget child; + final VoidCallback onTap; + final bool autofocus; + + @override + Widget build(BuildContext context) { + final shape = chatStackShape(AppDesignTokens.of(context)); + return Stack( + children: [ + child, + Positioned.fill( + child: Padding( + padding: const EdgeInsets.all( + (kChatStackSlot - kChatStackDisc) / 2, + ), + child: Material( + type: MaterialType.transparency, + shape: shape, + clipBehavior: Clip.antiAlias, + child: InkWell( + autofocus: autofocus, + excludeFromSemantics: true, + customBorder: shape, + onTap: onTap, + ), + ), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_remove_target.dart b/app/lib/features/chat/stack/chat_stack_remove_target.dart new file mode 100644 index 00000000..72123b52 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_remove_target.dart @@ -0,0 +1,106 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/theme/app_design_tokens.dart'; +import 'chat_stack_disc.dart'; + +/// The remove target's diameter: a little larger than an item, so it reads +/// as a destination rather than another chat. +const double kChatStackRemoveSize = kChatStackSlot + 8; + +/// How near its centre a finger counts as over the target: past its rim, +/// as a thumb covers what it drags. +const double kChatStackRemoveReach = kChatStackRemoveSize * .8; + +/// How much the target grows while a chat is over it. +const double chatStackRemoveGrowth = 1.2; + +/// The "×" a dragged chat is dropped on to leave the open chats: a circle +/// (the design's square under a flat design) that comes in when a drag +/// starts and fills with the error colour while a chat is over it. It takes +/// no input and says nothing to assistive technology: dropping is decided +/// from the pointer's position, and the column's items offer the same +/// removal as an action. +/// +/// Everything moves through transitions (fade, slide, scale, decoration), +/// so a drag repaints it without rebuilding. +class ChatStackRemoveTarget extends StatelessWidget { + const ChatStackRemoveTarget({ + super.key, + required this.shown, + required this.hover, + required this.reduced, + }); + + /// 0 hidden, 1 in place. + final Animation shown; + + /// 0 idle, 1 with a chat over it. + final Animation hover; + + /// Fades only: no slide in, no growth. + final bool reduced; + + @override + Widget build(BuildContext context) { + final tokens = AppDesignTokens.of(context); + final scheme = Theme.of(context).colorScheme; + final dark = Theme.of(context).brightness == Brightness.dark; + final shape = chatStackShape(tokens); + final side = tokens.flat + ? tokens.frameSide ?? BorderSide(color: scheme.outlineVariant) + : BorderSide.none; + final idle = ShapeDecoration( + color: tokens.panelFill( + scheme, + dark ? scheme.surfaceContainerHighest : scheme.surface, + ), + shape: shape.copyWith(side: side), + shadows: tokens.flat ? null : chatStackShadows(scheme), + ); + final hot = ShapeDecoration( + color: scheme.error, + shape: shape.copyWith( + side: tokens.flat ? side.copyWith(color: scheme.error) : side, + ), + shadows: tokens.flat ? null : chatStackShadows(scheme), + ); + final curve = shown.drive(CurveTween(curve: Curves.easeOutCubic)); + Widget target = DecoratedBoxTransition( + decoration: DecorationTween(begin: idle, end: hot).animate(hover), + child: SizedBox.square( + dimension: kChatStackRemoveSize, + child: Stack( + alignment: Alignment.center, + children: [ + Icon(Icons.close, color: scheme.onSurfaceVariant), + FadeTransition( + opacity: hover, + child: Icon(Icons.close, color: scheme.onError), + ), + ], + ), + ), + ); + if (!reduced) { + target = ScaleTransition( + scale: Tween( + begin: 1, + end: chatStackRemoveGrowth, + ).chain(CurveTween(curve: Curves.easeOutBack)).animate(hover), + child: target, + ); + target = SlideTransition( + position: Tween( + begin: const Offset(0, .5), + end: Offset.zero, + ).animate(curve), + child: target, + ); + } + return IgnorePointer( + child: ExcludeSemantics( + child: FadeTransition(opacity: curve, child: target), + ), + ); + } +} diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart index c6643a71..4a671b28 100644 --- a/app/lib/features/chat/workspace/chat_workspace_controller.dart +++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart @@ -163,6 +163,24 @@ class ChatWorkspaceController extends ChangeNotifier { _changed(); } + /// Moves the pane [paneId] to [index] in the pane order (the open-chat + /// order the server syncs). The panes keep their ids and the splits their + /// geometry; only the leaves change slots. The active pane stays. + void movePane(String paneId, int index) { + final order = panes; + final from = order.indexWhere((pane) => pane.id == paneId); + if (from < 0) return; + final to = index.clamp(0, order.length - 1); + if (from == to) return; + order.insert(to, order.removeAt(from)); + final next = reconcileChatWorkspaceTree(_root, [ + for (final pane in order) pane.sessionId, + ], _id); + if (identical(next, _root)) return; + _root = next; + _changed(); + } + void resize(String splitId, double ratio) { if (_root == null || !ratio.isFinite) return; _root = _resize(_root!, splitId, ratio.clamp(.01, .99)); diff --git a/app/notes/chat-stack.md b/app/notes/chat-stack.md index 2bb27641..0ffac150 100644 --- a/app/notes/chat-stack.md +++ b/app/notes/chat-stack.md @@ -13,9 +13,23 @@ restored in `bootstrap.dart`), applied live, and only on a phone-width layout - The stack's chats are the workspace's panes: the same open-chat set the server syncs (`ChatOpenWorkspaceController`). Choosing one opens it as a tap on its list row does (`_openBySelection`); Add chat is the pane menu's Add - chat pane picker (searchable, the list's own rows) titled "Add chat"; - long press removes the chat's pane, with an Undo snack bar that re-adds it - and keeps the chat on screen. + chat pane picker (searchable, the list's own rows) titled "Add chat". +- Drag: in the open column a 300 ms hold (a quicker tap still opens) lifts + a chat with its pill: a medium haptic, 1.1x scale and a deeper shadow + (flat designs: a primary-colour frame instead). Dragged up or down, the + others slide aside (200 ms ease-out) to open its slot, with a selection + tick per slot; dropping commits through `ChatWorkspaceController.movePane` + (the pane order the server syncs as the open-chat order). A "×" fades and + slides in, centred in the band below the stack's slot (over the composer, + above the safe area); over it (a reach of 0.8x its size around its centre) + it grows 1.2x and fills with the error colour, and the chat shrinks into + it. Dropping there removes the pane with the Undo snack bar; Undo re-adds + it at its old index and keeps the chat on screen. A drop far to the side + (more than 1.5 pitches) or Escape or a cancelled pointer puts it back. + Add chat never lifts and is never a slot. Semantics: Move up, Move down, + Remove from open chats as custom actions on each chat. Reduced motion: + neighbours swap at once, the lift and settle are instant, the "×" only + fades and does not grow. - Collapsed: up to four avatars piled with small offsets and turns, the chat on screen on top; a count badge when more are open, and a bell when another open chat waits on the operator. It sits bottom-end in the active chat's @@ -31,21 +45,47 @@ restored in `bootstrap.dart`), applied live, and only on a phone-width layout - Motion: one controller, 280 ms open (staggered, a slight-overshoot ease), 220 ms fold (top first). Items move through `ChatStackPoseTransition`, a repaint-only transform render object that reuses its matrix and layer; no - per-frame rebuilds, no blur. Reduced motion: a 120 ms plain fade in place. + per-frame rebuilds, no blur. A drag adds `ChatStackDragShift` (same idea, + driven by a per-item notifier, no layer at rest); the column rebuilds only + when a drag starts and ends. Reduced motion: a 120 ms plain fade in place. - Design tokens: circle discs with a short shadow under Default; the design's square corners and no shadow under flat designs (Terminal, Paper); label pills take the design radius and frame. ## Structure -- `lib/features/chat/stack/`: setting, pose, motion, disc/label, column, FAB, +- `lib/features/chat/stack/`: setting, pose, motion, disc/label, column and + its items, drag (session, shift render object, handles, remove target), FAB, anchor (a `LayerLink` the active pane's transcript marks; the one stack above the workspace follows it, so it survives switching chats). - `lib/features/chat/chat_screen_stack.dart`: entries, open/add/remove. - `chat_thread_view.dart`: anchor target, bottom clearance, Jump offset. - `tool/search_selection_probe_entry.dart`: `?chatNav=stack`. +## Floating chats on a phone + +A phone layout (Quick switch or Chat stack) ignores floating: windows are +hidden below `kListDetailMinWidth`, so each floating chat is held as an +ordinary pane (`_phoneDocked` in `chat_screen_workspace.dart`) and the +server's set keeps it `floating`. Widening the window (a foldable opened, a +desktop resized) floats those chats again; closing one on the phone drops +it from the open chats. Tests: `test/features/chat/chat_floating_phone_test.dart`. + +## Captures + +Drag captures use the kit's mouse `drag` with `press: 700`: with Flutter +web semantics on (the kit turns it on), the engine's click debouncer holds a +press on a tappable node for about 200 ms before the framework sees it, so +a 300 ms hold needs about 500 ms in the browser. Not an issue on a device +without a screen reader. + ## Not verified On-device behaviour (Android keyboard insets, haptics) was not run on a device; web captures used Chrome's touch emulation at 390x844. + +Drag limits: no auto-scroll while dragging; when the column is taller than +the screen it scrolls and clips, so a lifted chat cannot leave the clipped +column to reach the "×" there (Move and Remove remain as semantic actions). +The drag captures used the mouse (CDP), not touch; on-device haptics and the +hold feel are unverified. diff --git a/app/test/features/chat/stack/chat_stack_drag_test.dart b/app/test/features/chat/stack/chat_stack_drag_test.dart new file mode 100644 index 00000000..a97afd51 --- /dev/null +++ b/app/test/features/chat/stack/chat_stack_drag_test.dart @@ -0,0 +1,323 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_column.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_disc.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_drag.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_remove_target.dart'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../conversation/chat_thread_fixtures.dart'; + +/// A chat server keeping the open-chat set, as the sync test's does. +class _Server extends FakeChatGateway { + List open = ['a', 'b', 'c']; + int revision = 1; + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b', 'c', 'd']) + {'id': id, 'title': 'Chat $id', 'directory': '/w'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + if (type == 'chat_open_workspace') { + final request = fields['chat_open_workspace_request'] as Map?; + var rejected = false; + if (request != null && request['seed'] != true) { + if (request['base_revision'] != revision) { + rejected = true; + } else { + open = [ + for (final e in (request['entries'] as List).cast()) + '${e['session_id']}', + ]; + revision++; + } + } + return Future.value({ + 'type': 'chat_open_workspace', + 'chat_open_workspace': { + 'revision': revision, + 'entries': [ + for (final id in open) {'session_id': id}, + ], + if (rejected) 'rejected': true, + }, + }); + } + return super.call(type, fields); + } +} + +Future<_Server> _pump(WidgetTester tester, {bool reduced = false}) async { + SharedPreferences.setMockInitialValues({}); + unawaited( + MobileChatNavigationController.instance.setValue( + MobileChatNavigation.chatStack, + ), + ); + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final server = _Server()..history = (_) async => chatPage(const []); + bindServerIdentity(server, 'server-stack'); + addTearDown(server.close); + await tester.pumpWidget( + MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: reduced), + child: child!, + ), + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => + ChatScreen(gateway: server, persistWorkspace: true), + }, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-stack'))); + await tester.pumpAndSettle(); + return server; +} + +ChatWorkspaceController _workspace(WidgetTester tester) => + tester.widget(find.byType(ChatWorkspace)).controller; + +List _order(WidgetTester tester) => [ + for (final pane in _workspace(tester).panes) pane.sessionId, +]; + +/// Chat [id]'s avatar in the open column. +Finder _button(WidgetTester tester, String id) { + final pane = _workspace( + tester, + ).panes.firstWhere((pane) => pane.sessionId == id); + return find.byKey(ValueKey('chat-stack-button-${pane.id}')); +} + +final _add = find.byKey(const ValueKey('chat-stack-button-add')); +final _target = find.byType(ChatStackRemoveTarget); + +/// Holds [finder] until it lifts. +Future _lift(WidgetTester tester, Finder finder) async { + final gesture = await tester.startGesture(tester.getCenter(finder)); + await tester.pump(chatStackLiftDelay + const Duration(milliseconds: 20)); + return gesture; +} + +double _shown(WidgetTester tester) => + tester.widget(_target).shown.value; + +void main() { + final navigation = MobileChatNavigationController.instance; + tearDown(() { + unawaited(navigation.setValue(MobileChatNavigation.quickSwitch)); + }); + + test('movePane moves a pane and keeps the active one', () { + final controller = ChatWorkspaceController()..open('a'); + controller + ..splitActive('b', ChatSplitAxis.horizontal) + ..splitActive('c', ChatSplitAxis.horizontal); + final active = controller.activePaneId; + final a = controller.panes.first.id; + controller.movePane(a, 2); + expect(controller.panes.map((p) => p.sessionId), ['b', 'c', 'a']); + expect(controller.panes.last.id, a); + expect(controller.activePaneId, active); + controller.dispose(); + }); + + testWidgets('hold and drag reorders, and the order reaches the server', ( + tester, + ) async { + final server = await _pump(tester); + expect(_order(tester), ['a', 'b', 'c']); + final b = tester.getCenter(_button(tester, 'b')); + final gesture = await _lift(tester, _button(tester, 'a')); + // Lifted: the remove target comes in. + await tester.pumpAndSettle(); + expect(_shown(tester), 1); + // Up two slots: b and c slide down to open the gap. + await gesture.moveBy(const Offset(0, -kChatStackPitch * 2)); + await tester.pumpAndSettle(); + expect(tester.getCenter(_button(tester, 'b')).dy, b.dy + kChatStackPitch); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['b', 'c', 'a']); + expect(server.open, ['b', 'c', 'a']); + // Everyone settles in the new slots; the column stays open. + expect(tester.getCenter(_button(tester, 'b')).dy, closeTo(b.dy + 56, .5)); + expect(_shown(tester), 0); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('dropping on the × removes; Undo restores the place', ( + tester, + ) async { + final server = await _pump(tester); + final gesture = await _lift(tester, _button(tester, 'b')); + await tester.pumpAndSettle(); + final from = tester.getCenter(_button(tester, 'b')); + await gesture.moveBy(tester.getCenter(_target) - from); + await tester.pumpAndSettle(); + final drag = tester.widget(_target).hover; + expect(drag.value, 1); + await gesture.up(); + await tester.pumpAndSettle(); + expect(find.text('Removed Chat b from open chats'), findsOneWidget); + expect(_order(tester), ['a', 'c']); + expect(server.open, ['a', 'c']); + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + expect(server.open, ['a', 'b', 'c']); + // The chat on screen stays on screen. + expect(_workspace(tester).activePane?.sessionId, 'a'); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Escape, or a drop away from the column, puts the chat back', ( + tester, + ) async { + final server = await _pump(tester); + final home = tester.getCenter(_button(tester, 'a')); + var gesture = await _lift(tester, _button(tester, 'a')); + await gesture.moveBy(const Offset(0, -kChatStackPitch * 2)); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + expect(tester.getCenter(_button(tester, 'a')), home); + // Escape only cancelled the drag: the column is still open. + expect(find.byType(ChatStackColumn), findsOneWidget); + + gesture = await _lift(tester, _button(tester, 'a')); + await gesture.moveBy(const Offset(-200, -kChatStackPitch * 3)); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + expect(server.open, ['a', 'b', 'c']); + expect(tester.getCenter(_button(tester, 'a')), home); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a tap still opens a chat; Add chat does not lift', ( + tester, + ) async { + await _pump(tester); + final add = tester.getCenter(_add); + final gesture = await _lift(tester, _add); + await tester.pumpAndSettle(); + expect(_shown(tester), 0); + await gesture.moveBy(const Offset(0, kChatStackPitch * 2)); + await tester.pumpAndSettle(); + expect(tester.getCenter(_add), add); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + + // A drag that moved off "+" is no tap: the column is still open. + expect(find.byType(ChatStackColumn), findsOneWidget); + await tester.tap(_button(tester, 'c')); + await tester.pumpAndSettle(); + expect( + find + .byWidgetPredicate((w) => w is ChatThreadView && w.sessionId == 'c') + .hitTestable(), + findsOneWidget, + ); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Move up, Move down and Remove are semantic actions', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + final server = await _pump(tester); + void act(String id, String label) { + final node = tester.getSemantics(_button(tester, id)); + final action = node + .getSemanticsData() + .customSemanticsActionIds! + .map(CustomSemanticsAction.getAction) + .firstWhere((action) => action!.label == label)!; + tester.binding.renderViews.first.owner!.semanticsOwner!.performAction( + node.id, + SemanticsAction.customAction, + CustomSemanticsAction.getIdentifier(action), + ); + } + + // The bottom chat cannot move down; the top one cannot move up. + final bottom = tester.getSemantics(_button(tester, 'a')); + expect( + bottom.getSemanticsData().customSemanticsActionIds!.map( + (id) => CustomSemanticsAction.getAction(id)!.label, + ), + unorderedEquals([ + ChatStackColumn.moveUpLabel, + ChatStackColumn.removeLabel, + ]), + ); + act('a', ChatStackColumn.moveUpLabel); + await tester.pumpAndSettle(); + expect(server.open, ['b', 'a', 'c']); + act('c', ChatStackColumn.moveDownLabel); + await tester.pumpAndSettle(); + expect(server.open, ['b', 'c', 'a']); + act('b', ChatStackColumn.removeLabel); + await tester.pumpAndSettle(); + expect(server.open, ['c', 'a']); + expect(find.text('Removed Chat b from open chats'), findsOneWidget); + semantics.dispose(); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('reduced motion: neighbours swap at once, the × only fades', ( + tester, + ) async { + await _pump(tester, reduced: true); + final b = tester.getCenter(_button(tester, 'b')); + final gesture = await _lift(tester, _button(tester, 'a')); + expect(_shown(tester), 1); + await gesture.moveBy(const Offset(0, -kChatStackPitch)); + await tester.pump(); + expect(tester.getCenter(_button(tester, 'b')).dy, b.dy + kChatStackPitch); + // No slide: the target sits in place. + expect( + find.descendant(of: _target, matching: find.byType(SlideTransition)), + findsNothing, + ); + await gesture.up(); + await tester.pump(); + expect(_order(tester), ['b', 'a', 'c']); + expect(_shown(tester), 0); + await tester.pumpAndSettle(); + await tester.pumpWidget(const SizedBox.shrink()); + }); +} diff --git a/app/test/features/chat/stack/chat_stack_fab_test.dart b/app/test/features/chat/stack/chat_stack_fab_test.dart index 6804eb4a..6b7339ea 100644 --- a/app/test/features/chat/stack/chat_stack_fab_test.dart +++ b/app/test/features/chat/stack/chat_stack_fab_test.dart @@ -145,17 +145,18 @@ void main() { expect(harness.opened, ['s3']); }); - testWidgets('add opens the picker; long press removes', (tester) async { + testWidgets('add opens the picker; a hold alone removes nothing', ( + tester, + ) async { final harness = await _pump(tester); await tester.tap(find.byKey(const Key('chat-stack'))); await _settle(tester); + // A hold lifts the chat for a drag; let go in place, it settles back. await tester.longPress(find.text('Chat 2')); await _settle(tester); - expect(harness.removed, ['s2']); - // Removing folds the column, so a snack bar's Undo is in reach. - expect(find.byType(ChatStackColumn), findsNothing); - await tester.tap(find.byKey(const Key('chat-stack'))); - await _settle(tester); + expect(harness.removed, isEmpty); + expect(harness.opened, isEmpty); + expect(find.byType(ChatStackColumn), findsOneWidget); await tester.tap(find.byKey(const ValueKey('chat-stack-button-add'))); await _settle(tester); expect(harness.added, 1); diff --git a/app/test/features/chat/stack/chat_stack_screen_test.dart b/app/test/features/chat/stack/chat_stack_screen_test.dart index 0e970e7a..789a19a0 100644 --- a/app/test/features/chat/stack/chat_stack_screen_test.dart +++ b/app/test/features/chat/stack/chat_stack_screen_test.dart @@ -114,31 +114,6 @@ void main() { await tester.pumpWidget(const SizedBox.shrink()); }); - testWidgets('long press removes a chat, Undo restores it', (tester) async { - await _pump(tester, const Size(390, 844)); - await tester.tap(find.byKey(const Key('chat-row-a'))); - await tester.pumpAndSettle(); - await tester.tap(_stack); - await tester.pumpAndSettle(); - await tester.tap(find.byKey(const ValueKey('chat-stack-button-add'))); - await tester.pumpAndSettle(); - await tester.tap(find.text('Gamma').last); - await tester.pumpAndSettle(); - expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget); - await tester.tap(_stack); - await tester.pumpAndSettle(); - await tester.longPress(find.text('Alpha').last); - await tester.pumpAndSettle(); - expect(find.text('Removed Alpha from open chats'), findsOneWidget); - expect(find.bySemanticsLabel(chatStackLabel(1)), findsOneWidget); - await tester.tap(find.text('Undo')); - await tester.pumpAndSettle(); - // Gamma stays on screen; Alpha is back in the stack. - expect(_thread('c').hitTestable(), findsOneWidget); - expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget); - await tester.pumpWidget(const SizedBox.shrink()); - }); - testWidgets('a wide window keeps its panes and shows no stack', ( tester, ) async { diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index 5e98e76e..ef62148c 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -85,7 +85,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`. | `grant=clipboard` | let the page read and write the clipboard (`navigator.clipboard` in `eval`) | | `clipboard=read[:label]` / `clipboard=write:` | read or write the browser's clipboard from a scratch page on the loopback origin (a secure context), then bring the page back; JSON `expect` fails the run unless the read text matches. Works for an `--insecure` page, which has no `navigator.clipboard` | | `files=a.ttf[,b.ttf]` | answer the next file chooser the page opens with these files (paths relative to the working directory); put it before the click that opens the picker | -| `swipe=>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) | +| `swipe=>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on); JSON `press` holds the finger down that many ms first (a long press), `hold: true` leaves it down for a capture, and the next swipe moves it on from there | | `pinch=>scale` | two-finger touch pinch, spreading (>1) or closing (<1) (needs `--touch true`) | | `tabs=name` | write the open tabs (`{url, type}`) to JSON, e.g. to see a link open a new tab | | `follow=/window/chat/` | move the following steps to the page whose URL contains the text (a window the app opened with `window.open`, at its own size, semantics on); `follow=main` returns to the page the kit opened (`examples/detached-chat-window.json`) | diff --git a/app/tool/capture/capture.mjs b/app/tool/capture/capture.mjs index c280a9e5..b1facc78 100644 --- a/app/tool/capture/capture.mjs +++ b/app/tool/capture/capture.mjs @@ -34,7 +34,9 @@ steps: open=[@WxH] wait= shot= click= waitfor= (secondary button: context menus) drag=>, (JSON: drag, dx, dy, steps, gap, hold) - swipe=>, pinch=> (with --touch true) + swipe=>, pinch=> (with --touch true; + JSON swipe: press ms held before moving, hold keeps the finger down + for the next swipe) target: