diff --git a/assets/icons/chat-3-line.svg b/assets/icons/chat-3-line.svg new file mode 100644 index 000000000..e7857f644 --- /dev/null +++ b/assets/icons/chat-3-line.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/double-quotes-l.svg b/assets/icons/double-quotes-l.svg new file mode 100644 index 000000000..c4bd7ee76 --- /dev/null +++ b/assets/icons/double-quotes-l.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/icons/file-copy-line.svg b/assets/icons/file-copy-line.svg new file mode 100644 index 000000000..c6754e9bb --- /dev/null +++ b/assets/icons/file-copy-line.svg @@ -0,0 +1,2 @@ + + diff --git a/lib/chat/chat_history_view.dart b/lib/chat/chat_history_view.dart index aa79f0aad..b1a8f59f9 100644 --- a/lib/chat/chat_history_view.dart +++ b/lib/chat/chat_history_view.dart @@ -12,10 +12,15 @@ import 'package:super_sliver_list/super_sliver_list.dart'; import '../base/smooth_scroll.dart'; import '../diagnostics/frame_watch.dart'; +import '../ide/ide_commands.dart' show IdeKeybinding; import '../ide/ide_find_widget.dart'; import '../ide/ide_hover.dart'; +import '../ide/ide_menu.dart'; +import '../ide/ide_motion.dart'; +import '../ide/selection_bubble.dart'; import '../l10n/l10n.dart'; import '../theme/app_theme.dart'; +import '../theme/svg_icons.dart'; import '../theme/workbench_theme.dart' show themeColors; import '../usage/usage_ledger.dart'; import '../usage/usage_prices.dart'; @@ -60,6 +65,8 @@ class ChatHistoryView extends StatefulWidget { this.onFindClosed, this.after, this.forkAfter, + this.onQuote, + this.onQuoteAside, this.underTitle = false, }); @@ -95,6 +102,16 @@ class ChatHistoryView extends StatefulWidget { /// ends, its footer's button; none where it cannot be forked there. final VoidCallback? Function(int index)? forkAfter; + /// Puts text selected in it in the message being written, as a quote of + /// it (the selection's Quote); none where there is no message to put it + /// in. + final ValueChanged? onQuote; + + /// Puts text selected in it in a `/btw` message, as a quote of it (the + /// selection's By the Way); none where nothing is asked beside the + /// conversation. + final ValueChanged? onQuoteAside; + /// Whether a row is right over it (its card's title): room of its own /// above the history, which then keeps less above its first item and a /// stuck message, and fades less deep at its top. @@ -714,6 +731,9 @@ class _ChatHistoryViewState extends State /// The press went to the minimap, beside the list. bool _pressOnMinimap = false; + /// The press went to the bar over the selection (see [_placeBubbleBy]). + bool _pressOnBubble = false; + // --- Scrubbing --------------------------------------------------------------- // // The minimap's glass or the bar's thumb dragged: each frame a jump to rows @@ -835,6 +855,7 @@ class _ChatHistoryViewState extends State ..addListener(_findChanged); _scrollController.addListener(_handleScroll); _feed.addListener(_handleSessionChanged); + _selection.addListener(_selectionChanged); _statusIndex = _lastStatusIndex(); UserMessageStyle.current.addListener(_handleStyleChanged); ChatMinimap.side.addListener(_handleStyleChanged); @@ -1052,9 +1073,11 @@ class _ChatHistoryViewState extends State _editorClose.dispose(); _viewerScroll.dispose(); _handoff.dispose(); - _selection.dispose(); + _selection + ..removeListener(_selectionChanged) + ..dispose(); + _bubble.dispose(); _inertSelection.dispose(); - _menu.remove(); _listController.dispose(); _scrollController.dispose(); _selectionFocusNode.dispose(); @@ -1707,8 +1730,6 @@ class _ChatHistoryViewState extends State Duration _lastPress = Duration.zero; Offset? _lastPressAt; - final ContextMenuController _menu = ContextMenuController(); - /// Whether [event] landed on an interactive scrollbar anywhere inside this /// view (a table's sideways bar, a code block's, a step card's, …). bool _hitScrollbar(PointerDownEvent event) { @@ -1737,7 +1758,9 @@ class _ChatHistoryViewState extends State void _handlePointerDown(PointerDownEvent event) { _pressedDevices.add(event.device); - _menu.remove(); + final onBubble = _pressOnBubble; + _pressOnBubble = false; + if (!onBubble) _hideBubble(); // A press stops the list where it is (a trackpad swipe's fling carries // on for a while), as it does in the platform's lists: a mouse is not // one of the list's drag devices, so nothing else would, and a @@ -1770,6 +1793,7 @@ class _ChatHistoryViewState extends State } final elsewhere = _pressInEditor || + onBubble || own || onBar || onInnerBar || @@ -1779,6 +1803,8 @@ class _ChatHistoryViewState extends State _dragFrom = elsewhere || event.buttons != kPrimaryMouseButton ? null : event.position; + // What it selects has the bar over it (see [_placeBubbleBy]). + if (_dragFrom != null) _pointerSelects = true; _dragAt = null; // A press that may select stops the list following what is written, // while held: the text under the pointer would go on up, and the @@ -1793,7 +1819,7 @@ class _ChatHistoryViewState extends State _pressOnMinimap = false; if (_pressInEditor) { _pressInEditor = false; - } else if (!own && !onInnerBar) { + } else if (!own && !onInnerBar && !onBubble) { _selectionFocusNode.requestFocus(); } if (!elsewhere && event.buttons & kSecondaryMouseButton != 0) { @@ -1804,6 +1830,7 @@ class _ChatHistoryViewState extends State // selected, as a click does. if (elsewhere && event.kind != PointerDeviceKind.mouse && + !onBubble && !own && !onBar && !onInnerBar && @@ -2036,9 +2063,19 @@ class _ChatHistoryViewState extends State ), }; - /// A right click: a file link's menu on one; else copy and select all, - /// the word under the pointer selected when nothing is. + /// What is selected, put in the message being written by [put] (as a + /// quote of it, see [ChatHistoryView.onQuote]). + void _quoteSelection(ValueChanged put) { + final text = _selection.selectedText(); + _hideBubble(); + if (text != null) put(text); + } + + /// A right click: a file link's menu on one; else what there is to do + /// with the selection (the bar's, and select all), the word under the + /// pointer selected when nothing is. void _openMenu(Offset at) { + _hideBubble(); if (fileLinkMenuAt(context, at) case final menu?) { unawaited(menu.show(context, at)); return; @@ -2053,31 +2090,262 @@ class _ChatHistoryViewState extends State } } } - _menu.show( - context: context, - contextMenuBuilder: (context) => AdaptiveTextSelectionToolbar.buttonItems( - anchors: TextSelectionToolbarAnchors(primaryAnchor: at), - buttonItems: [ - if (_selection.hasSelection) - ContextMenuButtonItem( - type: ContextMenuButtonType.copy, - onPressed: () { - _copySelection(); - _menu.remove(); - }, + final l10n = context.l10n; + final selected = _selection.hasSelection; + String? keys(LogicalKeyboardKey key) => + IdeKeybinding(key, primary: true).label(); + unawaited( + showIdeMenu( + context, + position: at, + entries: ideMenuGroups([ + [ + IdeMenuAction( + l10n.commonCopy, + keybinding: keys(LogicalKeyboardKey.keyC), + enabled: selected, + onSelected: _copySelection, ), - ContextMenuButtonItem( - type: ContextMenuButtonType.selectAll, - onPressed: () { - _selection.selectAll(); - _menu.remove(); - }, - ), - ], + if (widget.onQuote case final quote? when selected) + IdeMenuAction( + l10n.chatQuote, + onSelected: () => _quoteSelection(quote), + ), + if (widget.onQuoteAside case final aside? when selected) + IdeMenuAction( + l10n.chatQuoteAside, + onSelected: () => _quoteSelection(aside), + ), + ], + [ + IdeMenuAction( + l10n.commonSelectAll, + keybinding: keys(LogicalKeyboardKey.keyA), + onSelected: _selection.selectAll, + ), + ], + ]), ), ); } + // --- The bar over the selection --------------------------------------------- + // + // Text selected with the pointer has a small bar, with Copy, Quote and By + // the Way, as a document's editor has its marks: over the selection (what + // of it shows), in its middle; under it where there is no room over it. + // It comes in as soon as there is a selection, while it is still dragged; + // as it grows, it goes there once it holds still a moment (or is let go + // of), not at a quick drag's every step, and at once then (it only comes + // and goes softly). It goes with the selection, at the next press, or at + // a click anywhere else. Placed as it is painted (see + // [_Follower]), it goes with the text as the list scrolls, nothing built + // or laid out for it meanwhile; and nothing is read of what is selected + // until one of its buttons wants it. + + /// Which showing of the bar this is (see [_bubbleShows]), while it shows; + /// 0 while it does not (fading out). + final ValueNotifier _bubble = ValueNotifier(0); + + /// The bar's showings so far: each comes in anew, where the last one, if + /// still fading out, goes at once. + int _bubbleShows = 0; + + /// Whether the selection is the pointer's (a drag, a double click, a + /// Shift+click in the text), which has the bar; one by the keys (Select + /// All) has none. + bool _pointerSelects = false; + + /// What the bar is over: the first and last characters of the text + /// selected, each where it is built (none where its item is not). + ({_SelectionEnd? start, _SelectionEnd? end})? _bubbleAt; + + /// The selection changed since [_bubbleAt] was read from it, the bar + /// showing: read again as the bar is painted, in the frame the selection + /// is (not the next one, the bar behind what it is over). + bool _bubbleStale = false; + + /// The item the selection started in as the bar was placed: as it is + /// renumbered (earlier history read in), so are the ends the bar is by. + int _bubbleFrom = 0; + + bool _bubbleScheduled = false; + + /// The bar gone till the next press selects (a button of it used, a + /// click elsewhere). + void _hideBubble() { + _pointerSelects = false; + _bubble.value = 0; + } + + void _selectionChanged() { + if (!_selection.hasSelection || _selection.selectsAll) { + _bubble.value = 0; + } else if (_pointerSelects) { + if (_bubble.value == 0) { + _bubbleSoon(); + } else { + _bubbleStale = true; + } + } + } + + /// [_placeBubbleBy] the selection once it is laid out, for the bar to + /// come in: once a frame however often it changed. + void _bubbleSoon() { + if (!mounted || _bubbleScheduled) return; + _bubbleScheduled = true; + SchedulerBinding.instance.addPostFrameCallback((_) { + _bubbleScheduled = false; + if (mounted) _placeBubbleBy(); + }); + SchedulerBinding.instance.ensureVisualUpdate(); + } + + /// The bar over the selection as it is now, coming in. + void _placeBubbleBy() { + if (!_pointerSelects || + !_selection.hasSelection || + _selection.selectsAll || + !_readBubbleAt()) { + return; + } + if (_bubble.value == 0) _bubble.value = ++_bubbleShows; + } + + /// [_bubbleAt] the selection as it is laid out now: over its text, not + /// over a line break or blanks it starts or ends with (dragged from + /// beside a message), which may be far from it. Whether any of it is + /// built. + bool _readBubbleAt() { + _bubbleStale = false; + final range = _selection.textRange() ?? _selection.range!; + final (first, last) = range; + _SelectionEnd? end(ChatTextPos pos, {required bool after}) => + switch (_selection.charRectAt(pos, after: after)) { + (:final char, :final leaf) => ( + item: pos.item, + char: char, + leaf: leaf, + ), + null => null, + }; + final next = (start: end(first, after: true), end: end(last, after: false)); + if (next.start == null && next.end == null) return false; + _bubbleFrom = _selection.range!.$1.item; + _bubbleAt = next; + return true; + } + + /// Where the bar goes in [layer] (the history's box), [size] as it is, + /// by what shows of the selection as it is laid out now (see + /// [SelectionBubble.placeBy]). None while none of it shows. + Offset? _placeBubble(RenderBox layer, Size size) { + if (_bubbleStale && _pointerSelects && _selection.hasSelection) { + _readBubbleAt(); + } + final at = _bubbleAt; + if (at == null || size.isEmpty || !layer.hasSize) return null; + // Its items renumbered (earlier history read in): where the ends are + // now; fading out, where they were (not where the next press went). + final shift = switch (_selection.range) { + (final start, _) => start.item - _bubbleFrom, + null => 0, + }; + ({Rect char, Rect leaf})? shown(_SelectionEnd? end) { + if (end == null) return null; + final item = _selection.builtItems[end.item + shift]; + if (item == null || !item.attached || !item.hasSize) return null; + final to = item.getTransformTo(layer); + return ( + char: MatrixUtils.transformRect(to, end.char), + leaf: MatrixUtils.transformRect(to, end.leaf), + ); + } + + final start = shown(at.start); + final end = shown(at.end); + if (start == null && end == null) return null; + final view = Offset.zero & layer.size; + // An end built nowhere is past the view's edge on its side. + final top = start?.char.top ?? view.top - 1; + final bottom = end?.char.bottom ?? view.bottom + 1; + final Rect across; + if (start != null && + end != null && + (start.char.center.dy - end.char.center.dy).abs() < + start.char.height / 2) { + // Within a line: the characters selected. + across = Rect.fromLTRB(start.char.left, 0, end.char.right, 0); + } else { + // Over lines: the text they are in. + across = [ + ?start?.leaf, + ?end?.leaf, + ].reduce((a, b) => a.expandToInclude(b)); + } + final around = Rect.fromLTRB(across.left, top, across.right, bottom); + if (!around.overlaps(view)) return null; + return SelectionBubble.placeBy(around.intersect(view), view, size); + } + + /// The bar, while [_bubble] says it shows. + Widget _buildBubble() => Listener( + onPointerDown: (_) => _pressOnBubble = true, + child: ValueListenableBuilder( + valueListenable: _bubble, + builder: (context, shown, _) { + final l10n = context.l10n; + // Between the user's messages' text and their muted text: the bar + // reads, but does not outshine what is selected. + final color = Color.lerp(AppColors.textMuted, AppColors.text, 0.45); + return FadeAway( + key: ValueKey(_bubbleShows), + child: shown != 0 + ? TapRegion( + onTapOutside: (_) => _hideBubble(), + child: PopIn( + // As the user's messages are: their fill and line. + child: SelectionBubble( + color: AppColors.bubbleFill, + border: AppColors.bubbleBorder(), + children: [ + SelectionBubbleButton( + icon: SvgIcons.copy, + label: l10n.commonCopy, + color: color, + hover: AppColors.bubbleHover, + onTap: () { + _copySelection(); + _hideBubble(); + }, + ), + if (widget.onQuote case final quote?) + SelectionBubbleButton( + icon: SvgIcons.quote, + label: l10n.chatQuote, + color: color, + hover: AppColors.bubbleHover, + onTap: () => _quoteSelection(quote), + ), + if (widget.onQuoteAside case final aside?) + SelectionBubbleButton( + icon: SvgIcons.aside, + label: l10n.chatQuoteAside, + color: color, + hover: AppColors.bubbleHover, + onTap: () => _quoteSelection(aside), + ), + ], + ), + ), + ) + : null, + ); + }, + ), + ); + /// Item [index]'s row, its text in the conversation's selection. Widget _selectable(int index, Widget child) => ChatSelectionItemScope( index: index, @@ -3625,6 +3893,19 @@ class _ChatHistoryViewState extends State onPointerPanZoomEnd: _endForwardedPan, ), ), + // By the selection (see [_placeBubbleBy]). + Positioned.fill( + child: SelectionBubbleFollower( + place: _placeBubble, + repaint: Listenable.merge([ + _scrollController, + _editorMoved, + _selection, + _bubble, + ]), + child: _buildBubble(), + ), + ), // Over the history's top right, as the editor's; over the // side panel's rail too, where it floats there. Positioned( @@ -3940,6 +4221,11 @@ class _RenderStickyFollower extends RenderProxyBox { _paintedTop == null ? Rect.zero : null; } +/// An end of the selection, as the bar over it has it: its character +/// ([char]) and the piece of text that is in ([leaf]), in the box of its +/// item [item]. +typedef _SelectionEnd = ({int item, Rect char, Rect leaf}); + /// Reports [child]'s size after layout whenever it changes. class _SizeReporter extends SingleChildRenderObjectWidget { const _SizeReporter({super.key, required this.onSize, required super.child}); diff --git a/lib/chat/chat_screen.dart b/lib/chat/chat_screen.dart index be1f1fabd..ee8cf6676 100644 --- a/lib/chat/chat_screen.dart +++ b/lib/chat/chat_screen.dart @@ -41,6 +41,7 @@ import 'resume_after_reset.dart'; import 'chat_width.dart'; import 'composer/command_details.dart'; import 'composer/composer.dart'; +import 'composer/composer_draft.dart'; import 'composer/composer_embeds.dart'; import 'composer/composer_mock_data.dart'; import 'composer/file_mentions.dart'; @@ -960,7 +961,16 @@ class _ChatScreenState extends State return _commands; } - static const _asideCommand = 'btw'; + static const _asideCommand = ComposerDraft.asideCommand; + + /// Text selected in the conversation, quoted in the message being + /// written (see [ChatHistoryView.onQuote]). + void _quote(String text) => _session.draft.insertQuote(text); + + /// …or in a `/btw` one, where there are conversations beside this one. + ValueChanged? get _quoteAside => widget.onSideQuestion == null + ? null + : (text) => _session.draft.insertQuote(text, aside: true); /// Takes `/btw …` for a conversation beside this one: true when it was /// one. What follows, on this line or the next, is asked there with the @@ -1429,6 +1439,8 @@ class _ChatScreenState extends State }, null => null, }, + onQuote: _quote, + onQuoteAside: _quoteAside, ), ), // The start hint, before the first message. @@ -1613,6 +1625,8 @@ class _ChatScreenState extends State onOpenAgent: _openAgent, onSetGoal: _setGoal, onFindClosed: layer.backFocus.requestFocus, + onQuote: _quote, + onQuoteAside: _quoteAside, ), ), ], diff --git a/lib/chat/composer/composer.dart b/lib/chat/composer/composer.dart index a46ce2b3b..8c55e4ee7 100644 --- a/lib/chat/composer/composer.dart +++ b/lib/chat/composer/composer.dart @@ -337,15 +337,16 @@ class ChatComposerState extends State return true; } - /// The number for a long paste: one past the highest the text has. - int _nextPastedNumber() { + /// The number for a long paste (a quote): one past the highest the text + /// has. + int _nextPastedNumber({bool quoted = false}) { var highest = 0; for (final (:embed, start: _, end: _) in _controller.embeds) { if (embed.type == ComposerPastedTextEmbed.type) { - highest = math.max( - highest, - ComposerPastedTextEmbed.decode(embed.data).number, - ); + final pasted = ComposerPastedTextEmbed.decode(embed.data); + if (pasted.quoted == quoted) { + highest = math.max(highest, pasted.number); + } } } return highest + 1; @@ -366,6 +367,7 @@ class ChatComposerState extends State _focusNode.requestFocus(); _takeDraftFiles(); _takeDraftCode(); + _takeDraftQuotes(); _takeDraftMessage(); }); } @@ -685,6 +687,46 @@ class ChatComposerState extends State ], at: _controller.length); } + /// The text quoted from the conversation put in the draft from outside + /// (see [ComposerDraft.insertQuote]): tags of it after what is typed. One + /// asked aside makes the message a `/btw` too, unless it is one already; + /// the caret after the tags either way, for the question. + void _takeDraftQuotes() { + final quotes = widget.draft?.takeQuotes() ?? const []; + if (quotes.isEmpty) return; + var number = _nextPastedNumber(quoted: true); + _insertTags([ + for (final quote in quotes) + ComposerPastedTextEmbed.of( + PastedText(number: number++, text: quote.text, quoted: true), + ), + ], at: _controller.length); + if (!quotes.any((quote) => quote.aside) || _asksAside) return; + final command = ComposerTokenEmbed.fromSuggestion( + const Suggestion( + kind: SuggestionKind.command, + label: ComposerDraft.asideCommand, + ), + ); + final inserted = '${command.atom} '; + _controller + ..breakUndo() + ..replace( + 0, + 0, + inserted, + selection: TextSelection.collapsed( + offset: _controller.length + inserted.length, + ), + ) + ..breakUndo(); + } + + /// Whether the message is a `/btw` (By the Way), as typed or put in. + bool get _asksAside => + RegExp('^/${ComposerDraft.asideCommand}(\\s|\$)') + .hasMatch(composerPlainText(_controller.text).trimLeft()); + /// The message put back in the draft to be edited (see /// [ComposerDraft.restore]): after what is typed, the caret at its end. void _takeDraftMessage() { @@ -745,6 +787,7 @@ class ChatComposerState extends State final draft = widget.draft; if (draft != null && draft.pendingFiles.isNotEmpty) _takeDraftFiles(); if (draft != null && draft.pendingCode.isNotEmpty) _takeDraftCode(); + if (draft != null && draft.pendingQuotes.isNotEmpty) _takeDraftQuotes(); if (draft?.pendingMessage != null) _takeDraftMessage(); if (draft == null || identical(draft.savedBy, this) || !draft.saved) { return; @@ -1870,8 +1913,11 @@ class ChatComposerState extends State placeholder: context.l10n.composerPlaceholder, onKey: _handleKey, onPaste: _paste, - onPasteCopy: (markdown) => - renumberPastes(markdown, from: _nextPastedNumber()), + onPasteCopy: (markdown) => renumberPastes( + markdown, + from: _nextPastedNumber(), + quotesFrom: _nextPastedNumber(quoted: true), + ), style: MarkdownEditorStyle( text: base, selection: AppColors.textSelection, diff --git a/lib/chat/composer/composer_draft.dart b/lib/chat/composer/composer_draft.dart index 74224bd58..eb71db688 100644 --- a/lib/chat/composer/composer_draft.dart +++ b/lib/chat/composer/composer_draft.dart @@ -64,6 +64,31 @@ class ComposerDraft extends ChangeNotifier { return code; } + /// The command that asks a message beside the conversation, in one of + /// its own (see ChatScreen.onSideQuestion). + static const asideCommand = 'btw'; + + /// Text quoted from the conversation (its selection's Quote), to put in + /// as tags of it after what is typed, [aside] with the message made a + /// `/btw` (By the Way), taken by the composer that shows the draft, or by + /// the next to. + List<({String text, bool aside})> get pendingQuotes => + List.unmodifiable(_pendingQuotes); + final List<({String text, bool aside})> _pendingQuotes = []; + + void insertQuote(String text, {bool aside = false}) { + if (text.trim().isEmpty) return; + _pendingQuotes.add((text: text, aside: aside)); + notifyListeners(); + } + + /// [pendingQuotes], no longer pending. + List<({String text, bool aside})> takeQuotes() { + final quotes = [..._pendingQuotes]; + _pendingQuotes.clear(); + return quotes; + } + /// A message to put back in, to be edited (a queued one taken back), /// taken by the composer that shows the draft, or by the next to. ({String text, List images})? get pendingMessage => diff --git a/lib/chat/composer/composer_embeds.dart b/lib/chat/composer/composer_embeds.dart index 3c1740272..6d157a2a2 100644 --- a/lib/chat/composer/composer_embeds.dart +++ b/lib/chat/composer/composer_embeds.dart @@ -123,19 +123,25 @@ Iterable<({int start, int end, ComposerEmbed embed})> composerEmbedsIn( } /// [content], a copy of the composer's pasted back into one, its long -/// pastes numbered on from [from], as pasted anew they would be: their -/// references, which tell them apart in the message, not the same as -/// those of the pastes already there. -String renumberPastes(String content, {required int from}) { +/// pastes numbered on from [from] (its quotes from [quotesFrom]), as pasted +/// anew they would be: their references, which tell them apart in the +/// message, not the same as those of the pastes already there. +String renumberPastes( + String content, { + required int from, + required int quotesFrom, +}) { var next = from; + var nextQuote = quotesFrom; final renumbered = StringBuffer(); var at = 0; for (final (:start, :end, :embed) in composerEmbedsIn(content)) { if (embed.type != ComposerPastedTextEmbed.type) continue; final pasted = ComposerPastedTextEmbed.decode(embed.data); + final number = pasted.quoted ? nextQuote++ : next++; renumbered ..write(content.substring(at, start)) - ..write(ComposerPastedTextEmbed.of(pasted.numbered(next++)).atom); + ..write(ComposerPastedTextEmbed.of(pasted.numbered(number)).atom); at = end; } if (at == 0) return content; @@ -952,13 +958,13 @@ class _TextPreview extends StatelessWidget { ); } -/// The inline tag for a long paste ([ComposerPastedTextEmbed] data), -/// centered on text of [textStyle]: its number and its count of lines, its -/// first lines on hover, all of it on a click (see [showTextPreview]). In -/// the composer and in sent messages alike. +/// The inline tag for a long paste ([ComposerPastedTextEmbed] data), or a +/// quote, centered on text of [textStyle]: its number and its count of +/// lines, its first lines on hover, all of it on a click (see +/// [showTextPreview]). In the composer and in sent messages alike. /// /// Inside a selectable area it copies as its message text -/// (`[Pasted text #1 +120 lines]`). +/// (`[Pasted text #1 +120 lines]`, `[Quote #1]`). class ComposerPastedTextChip extends StatelessWidget { const ComposerPastedTextChip({ super.key, @@ -980,7 +986,9 @@ class ComposerPastedTextChip extends StatelessWidget { Widget build(BuildContext context) { final pasted = ComposerPastedTextEmbed.decode(data); final l10n = context.l10n; - final name = l10n.pastedTextChip(pasted.number); + final name = pasted.quoted + ? l10n.quoteChip(pasted.number) + : l10n.pastedTextChip(pasted.number); final lines = pasted.extraLines; final tag = _CenteredOnText( textStyle: textStyle, @@ -1001,7 +1009,11 @@ class ComposerPastedTextChip extends StatelessWidget { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Icon(Icons.notes_rounded, size: 13, color: AppColors.textMuted), + Icon( + pasted.quoted ? Codicons.quote : Icons.notes_rounded, + size: 13, + color: AppColors.textMuted, + ), const SizedBox(width: 4), Text( name, diff --git a/lib/chat/composer/composer_files.dart b/lib/chat/composer/composer_files.dart index 5d5dd32ff..4127aeab2 100644 --- a/lib/chat/composer/composer_files.dart +++ b/lib/chat/composer/composer_files.dart @@ -124,6 +124,10 @@ sealed class AppendedText { /// How the message's text refers to it, in brackets. String get reference; + /// The line over its [content] after the message's text: its + /// [reference], and what it is where that does not say. + String get header => reference; + /// What goes after the message's text. String get content; } @@ -192,6 +196,11 @@ class CodeReference extends AppendedText { /// `[Pasted text #1 +120 lines]`, as Claude Code's own input does, and /// carries it after its text (see [codeAppendix]); or, longer still, where /// it is kept ([file], see PasteStore). +/// +/// Or text [quoted] from the conversation (its selection's Quote), which +/// goes as a paste does, whatever its length: `[Quote #1]`, numbered apart +/// from the pastes, and said to be the user's quote where it goes after the +/// message's text. @immutable class PastedText extends AppendedText { const PastedText({ @@ -199,11 +208,15 @@ class PastedText extends AppendedText { required this.text, this.file, this.lines, + this.quoted = false, }); - /// Of the pastes in the message, from 1. + /// Of the pastes in the message (or of its quotes), from 1. final int number; + /// Quoted from the conversation, not pasted. + final bool quoted; + /// What was pasted; empty for one kept in a [file], until read. final String text; @@ -215,12 +228,22 @@ class PastedText extends AppendedText { final int? lines; /// This, kept at [path]. - PastedText storedAt(String path) => - PastedText(number: number, text: '', file: path, lines: extraLines); + PastedText storedAt(String path) => PastedText( + number: number, + text: '', + file: path, + lines: extraLines, + quoted: quoted, + ); - /// This, as the message's paste [number]. - PastedText numbered(int number) => - PastedText(number: number, text: text, file: file, lines: lines); + /// This, as the message's paste (or quote) [number]. + PastedText numbered(int number) => PastedText( + number: number, + text: text, + file: file, + lines: lines, + quoted: quoted, + ); /// Pasted as a tag past this many characters… static const maxLength = 1000; @@ -241,14 +264,25 @@ class PastedText extends AppendedText { return '\n'.allMatches(trimmed).length; } - /// `[Pasted text #1 +120 lines]`, or `[Pasted text #1]` for one line. + /// `[Pasted text #1 +120 lines]`, or `[Pasted text #1]` for one line; a + /// quote's, `[Quote #1]`. @override String get reference => switch (extraLines) { + _ when quoted => '[Quote #$number]', 0 => '[Pasted text #$number]', 1 => '[Pasted text #$number +1 line]', final lines => '[Pasted text #$number +$lines lines]', }; + /// A quote's says whose it is and where from, for the agent to take it + /// as the user's pointing at those words, not as text to work on. + @override + String get header => quoted ? '$reference $quoteNote' : reference; + + static const quoteNote = + '(text the user selected and quoted from the ' + 'conversation)'; + /// The text, or where it is kept (see [keptNote]). @override String get content => switch (file) { @@ -271,6 +305,7 @@ class PastedText extends AppendedText { 'text': text, 'file': ?file, 'lines': ?lines, + if (quoted) 'quoted': true, }; static PastedText fromJson(Map json) => PastedText( @@ -278,6 +313,7 @@ class PastedText extends AppendedText { text: json['text'] as String, file: json['file'] as String?, lines: json['lines'] as int?, + quoted: json['quoted'] == true, ); @override @@ -286,10 +322,11 @@ class PastedText extends AppendedText { other.number == number && other.text == text && other.file == file && - other.lines == lines; + other.lines == lines && + other.quoted == quoted; @override - int get hashCode => Object.hash(number, text, file, lines); + int get hashCode => Object.hash(number, text, file, lines, quoted); } /// A stash (see lib/stash/), put in the composer by `@` or dragged there: @@ -368,15 +405,16 @@ abstract final class CopiedCode { /// The code (and long pastes) a message refers to, as it is sent after the /// message's text: after an empty line, each reference in brackets on a -/// line of its own, then its lines between fences of backticks; a paste -/// kept in a file, where it is (see [PastedText.keptNote]). +/// line of its own (its [AppendedText.header]), then its lines between +/// fences of backticks; a paste kept in a file, where it is (see +/// [PastedText.keptNote]). String codeAppendix(Iterable references) { final buffer = StringBuffer(); for (final reference in references) { if (reference case PastedText(file: _?)) { buffer ..write('\n\n') - ..write(reference.reference) + ..write(reference.header) ..write('\n') ..write(reference.content); continue; @@ -386,7 +424,7 @@ String codeAppendix(Iterable references) { if (code.endsWith('\n')) code = code.substring(0, code.length - 1); buffer ..write('\n\n') - ..write(reference.reference) + ..write(reference.header) ..write('\n') ..write(fence) ..write('\n') @@ -428,6 +466,9 @@ String _fenceFor(String code) { final _referenceLine = RegExp(r'^\[(.+):(\d+)(?:-(\d+))?\]$'); final _pastedLine = RegExp(r'^\[Pasted text #(\d+)(?: \+(\d+) lines?)?\]$'); +final _quoteLine = RegExp( + '^\\[Quote #(\\d+)\\] ${RegExp.escape(PastedText.quoteNote)}\$', +); final _stashLine = RegExp(r'^\[Stash #(\d+)\]$'); /// The last block of a [codeAppendix] at the end of [text], and the text @@ -437,7 +478,9 @@ final _stashLine = RegExp(r'^\[Stash #(\d+)\]$'); // A paste kept in a file: an empty line, its reference, where it is. if (PastedText._keptNote.firstMatch(lines.last) case final kept? when lines.length >= 3 && lines[lines.length - 3].isEmpty) { - final match = _pastedLine.firstMatch(lines[lines.length - 2]); + final header = lines[lines.length - 2]; + final quote = _quoteLine.firstMatch(header); + final match = quote ?? _pastedLine.firstMatch(header); if (match == null) return null; return ( body: lines.sublist(0, lines.length - 3).join('\n'), @@ -445,7 +488,8 @@ final _stashLine = RegExp(r'^\[Stash #(\d+)\]$'); number: int.parse(match[1]!), text: '', file: kept[1], - lines: int.parse(match[2] ?? '0'), + lines: quote == null ? int.parse(match[2] ?? '0') : null, + quoted: quote != null, ), ); } @@ -462,6 +506,12 @@ final _stashLine = RegExp(r'^\[Stash #(\d+)\]$'); reference = PastedText(number: int.parse(match[1]!), text: content); // Its count of lines is the text's own. if (reference.reference != header) return null; + } else if (_quoteLine.firstMatch(header) case final match?) { + reference = PastedText( + number: int.parse(match[1]!), + text: content, + quoted: true, + ); } else if (_stashLine.firstMatch(header) case final match?) { reference = StashReference(id: int.parse(match[1]!), text: content); } else if (_referenceLine.firstMatch(header) case final match?) { diff --git a/lib/chat/selection/chat_selection.dart b/lib/chat/selection/chat_selection.dart index 81043b16d..0c5f73b0b 100644 --- a/lib/chat/selection/chat_selection.dart +++ b/lib/chat/selection/chat_selection.dart @@ -970,6 +970,87 @@ class ChatSelectionController extends ChangeNotifier { final rect = rects.isEmpty ? Offset.zero & leaf.box.size : rects.first; return leaf.box.localToGlobal(rect.center); } + + /// [range] trimmed to the text in it, as far as it is built: a start + /// with only blanks after it in its piece (the line break after a + /// message, a drag begun beside it) moved on to the next piece, an end + /// with only blanks before it back to the one before. Null when nothing + /// but blanks is selected. + (ChatTextPos, ChatTextPos)? textRange() { + final range = this.range; + if (range == null) return null; + var (start, end) = range; + List? leavesOf(int index) => switch (_items[index]) { + final item? when item.attached => item.leaves(), + _ => null, + }; + bool blank(String text, int from, int to) { + for (var i = from; i < to; i++) { + if (text.codeUnitAt(i) > 0x20) return false; + } + return true; + } + + var leaves = leavesOf(start.item); + while (start < end && leaves != null) { + if (start.leaf < leaves.length) { + final text = leaves[start.leaf].text; + final from = start.offset.clamp(0, text.length); + if (!blank(text, from, text.length)) break; + start = ChatTextPos(start.item, start.leaf + 1, 0); + } else { + start = ChatTextPos(start.item + 1, 0, 0); + leaves = leavesOf(start.item); + } + } + leaves = leavesOf(end.item); + while (start < end && leaves != null) { + final leaf = math.min(end.leaf, leaves.length - 1); + if (leaf >= 0) { + final text = leaves[leaf].text; + final to = end.offset.clamp(0, text.length); + if (!blank(text, 0, to)) break; + } + if (leaf > 0) { + end = ChatTextPos(end.item, leaf - 1, leaves[leaf - 1].text.length); + } else if (end.item > 0) { + leaves = leavesOf(end.item - 1); + end = ChatTextPos( + end.item - 1, + math.max(0, (leaves?.length ?? 1) - 1), + leaves?.lastOrNull?.text.length ?? 0, + ); + } else { + break; + } + } + return start < end ? (start, end) : null; + } + + /// The character [pos] is at the end of ([after]: at the start of), and + /// the piece of text it is in ([leaf]), in the box of its item (see + /// [builtItems]): where a selection's end is, if built. A line's height, + /// for a piece of no text. + ({Rect char, Rect leaf})? charRectAt(ChatTextPos pos, {bool after = false}) { + final item = _items[pos.item]; + if (item == null || !item.attached) return null; + final leaves = item.leaves(); + if (leaves.isEmpty) return null; + final leaf = leaves[math.min(pos.leaf, leaves.length - 1)]; + final length = leaf.text.length; + final offset = pos.offset.clamp(0, length); + final start = math.max( + 0, + math.min(after ? offset : offset - 1, length - 1), + ); + final rects = leaf.rectsFor(start, math.min(length, start + 1)); + final box = Offset.zero & leaf.box.size; + final toItem = leaf.box.getTransformTo(item); + return ( + char: MatrixUtils.transformRect(toItem, rects.firstOrNull ?? box), + leaf: MatrixUtils.transformRect(toItem, box), + ); + } } /// The conversation item [index] whose text is under it, and its diff --git a/lib/ide/ide_motion.dart b/lib/ide/ide_motion.dart index 7168baf3b..d7b3b0919 100644 --- a/lib/ide/ide_motion.dart +++ b/lib/ide/ide_motion.dart @@ -40,6 +40,74 @@ class IdeMotion extends InheritedWidget { bool updateShouldNotify(IdeMotion oldWidget) => lively != oldWidget.lively; } +/// [child] while there is one, and fading out once it is gone (null): the +/// last one kept meanwhile, taking no presses. A floating bar's going, as +/// [PopIn] is its coming; back before it is gone, it fades in again from +/// where it was, and once gone, it comes in anew. +class FadeAway extends StatefulWidget { + const FadeAway({ + super.key, + this.child, + this.duration = const Duration(milliseconds: 120), + }); + + final Widget? child; + final Duration duration; + + @override + State createState() => _FadeAwayState(); +} + +class _FadeAwayState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _shown = AnimationController( + vsync: this, + duration: widget.duration, + value: 1, + )..addStatusListener(_statusChanged); + + /// What shows: [FadeAway.child], or the last one while it fades out. + late Widget? _last = widget.child; + + @override + void didUpdateWidget(FadeAway oldWidget) { + super.didUpdateWidget(oldWidget); + _shown.duration = widget.duration; + if (widget.child case final child?) { + if (_last == null) { + _shown.value = 1; + } else if (_shown.value < 1) { + _shown.forward(); + } + _last = child; + } else if (_last != null && _shown.status != AnimationStatus.reverse) { + _shown.reverse(); + } + } + + void _statusChanged(AnimationStatus status) { + if (status == AnimationStatus.dismissed && widget.child == null) { + setState(() => _last = null); + } + } + + @override + void dispose() { + _shown.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final child = _last; + if (child == null) return const SizedBox.shrink(); + return IgnorePointer( + ignoring: widget.child == null, + child: FadeTransition(opacity: _shown, child: child), + ); + } +} + /// [child] coming in as it is first built: fading, from a little smaller /// and a few pixels [offset] off, settling where it is. A floating bar's /// or menu's showing; keyed anew, it comes in again. diff --git a/lib/ide/markdown/markdown_format_bar.dart b/lib/ide/markdown/markdown_format_bar.dart index 5cc7fadde..738e28390 100644 --- a/lib/ide/markdown/markdown_format_bar.dart +++ b/lib/ide/markdown/markdown_format_bar.dart @@ -4,15 +4,12 @@ // preview alike. import 'dart:async'; -import 'dart:math' as math; import 'package:bao_markdown/bao_markdown.dart'; import 'package:flutter/foundation.dart' show defaultTargetPlatform; import 'package:flutter/material.dart'; -import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; -import '../../chat/widgets/hover_builder.dart'; import '../../l10n/l10n.dart'; import '../../models/auxiliary_model_menu.dart'; import '../../models/model_providers.dart'; @@ -23,10 +20,10 @@ import '../../theme/codicons.dart'; import '../../theme/workbench_theme.dart' show themeColors; import '../ide_commands.dart' show IdeKeybinding; import '../ide_dialog.dart'; -import '../ide_hover.dart'; import '../ide_input.dart'; import '../ide_menu.dart'; import '../ide_motion.dart'; +import '../selection_bubble.dart'; /// [markdown] (the selection's) as a model is given it, and a reply to it /// as markdown again. @@ -91,9 +88,17 @@ class MarkdownFormatBar extends StatefulWidget { class MarkdownFormatBarState extends State { final GlobalKey _stackKey = GlobalKey(); - /// The selection's bounds, in the stack's box, for the bar over (or - /// under) it; none without one. + /// The selection's bounds, in the stack's box, as last read, for the bar + /// over (or under) it; none without one. Where the bar goes is read + /// again as it is painted (see [_barAt]). Rect? _barAround; + + /// Told that what the bar is by may have moved (the selection, the text + /// scrolled): it is placed anew as it is painted, in that frame. + final ValueNotifier _barMoved = ValueNotifier(0); + + /// What the bar was by as it was painted last: where it fades out. + Rect? _barPainted; bool _polishing = false; /// A menu opened from the bar (the model picker, the marks under "…") is @@ -165,13 +170,16 @@ class MarkdownFormatBarState extends State { _cellsOf?.tableCellChanges.removeListener(_barSoon); _linkFocus.dispose(); _linkText.dispose(); + _barMoved.dispose(); super.dispose(); } bool _barScheduled = false; - /// The bar (and the link's) where the selection is, once it is laid out. + /// The bar (and the link's) where the selection is, painted anew; what + /// it has (and whether it shows) once the selection is laid out. void _barSoon() { + _barMoved.value++; if (_barScheduled) return; _barScheduled = true; WidgetsBinding.instance.addPostFrameCallback((_) { @@ -199,15 +207,20 @@ class MarkdownFormatBarState extends State { around = _selectionBounds(selection); } final link = around == null ? _linkAtCaret() : null; - if (around == _barAround && + if ((around == null) == (_barAround == null) && + selection == _barSelection && link?.href == _caretLink?.href && link?.range == _caretLink?.range && - link?.around == _caretLink?.around && link?.cell == _caretLink?.cell && _barVersion == _controller.textVersion) { + // Only moved (the text scrolled): it is where it went already (see + // [_barAt]). + _barAround = around; + _caretLink = link; return; } setState(() { + _barSelection = selection; _barAround = around; _caretLink = link; _barVersion = _controller.textVersion; @@ -217,6 +230,9 @@ class MarkdownFormatBarState extends State { /// The text the bar's marks were read from. int _barVersion = -1; + /// The selection they were read for (and whether it is in code). + TextSelection? _barSelection; + /// Shows the bar while a menu opened from it shows, and keeps it once /// one closes: the editor's focus comes back with the menu. void _barMenuShown(bool open) { @@ -292,30 +308,8 @@ class MarkdownFormatBarState extends State { ); } - /// The text scrolled: the bar goes with the selection at once (by as - /// much as it was scrolled), where it is laid out then once it is. + /// The text scrolled: the bar goes with the selection in that frame. bool _scrolled(ScrollUpdateNotification notification) { - final delta = notification.scrollDelta; - if (notification.metrics.axis == Axis.vertical && - delta != null && - delta != 0 && - (_barAround != null || _caretLink != null) && - // Not while laying out (the text scrolled to its caret). - SchedulerBinding.instance.schedulerPhase != - SchedulerPhase.persistentCallbacks) { - final by = Offset(0, -delta); - setState(() { - _barAround = _barAround?.shift(by); - if (_caretLink case final link?) { - _caretLink = ( - href: link.href, - range: link.range, - around: link.around.shift(by), - cell: link.cell, - ); - } - }); - } _barSoon(); return false; } @@ -512,7 +506,7 @@ class MarkdownFormatBarState extends State { ), ), const SizedBox(width: 2), - _BarButton( + SelectionBubbleButton( icon: Codicons.check, tooltip: context.l10n.commonOk, onTap: () => _endLink(apply: true), @@ -529,24 +523,24 @@ class MarkdownFormatBarState extends State { return _SelectionBar( around: link.around, children: [ - _BarButton( + SelectionBubbleButton( icon: _linkIcon(link.href), label: _shortUrl(link.href), tooltip: l10n.stashLinkOpen, onTap: () => widget.onOpenLink(link.href), ), - const _BarDivider(), - _BarButton( + const SelectionBubbleDivider(), + SelectionBubbleButton( icon: Codicons.copy, tooltip: l10n.stashLinkCopy, onTap: () => _copyLink(link.href, cell: link.cell), ), - _BarButton( + SelectionBubbleButton( icon: Codicons.edit, tooltip: l10n.stashLinkEdit, onTap: () => editLink(link.href, link.range, cell: link.cell), ), - _BarButton( + SelectionBubbleButton( icon: Codicons.close, tooltip: l10n.stashLinkRemove, onTap: () => _removeLink(link.range, cell: link.cell), @@ -851,7 +845,12 @@ class MarkdownFormatBarState extends State { String tip, VoidCallback onTap, { bool active = false, - }) => _BarButton(icon: icon, tooltip: tip, onTap: onTap, active: active); + }) => SelectionBubbleButton( + icon: icon, + tooltip: tip, + onTap: onTap, + active: active, + ); final raw = _inRaw(_controller.selection); // What is used most; the rest under "…". In code, only proofreading. final items = [ @@ -890,7 +889,7 @@ class MarkdownFormatBarState extends State { tooltip: l10n.stashFormatColor, onPick: (key, name) => _color(key, name), ), - const _BarDivider(), + const SelectionBubbleDivider(), button( Codicons.listUnordered, l10n.stashFormatBullets, @@ -904,7 +903,7 @@ class MarkdownFormatBarState extends State { active: format == MdLineFormat.task, ), Builder( - builder: (context) => _BarButton( + builder: (context) => SelectionBubbleButton( icon: Codicons.ellipsis, tooltip: l10n.stashFormatMore, active: _moreActive(), @@ -919,9 +918,9 @@ class MarkdownFormatBarState extends State { ), ], if (widget.onPolish != null) ...[ - if (!raw) const _BarDivider(), + if (!raw) const SelectionBubbleDivider(), Builder( - builder: (context) => _BarButton( + builder: (context) => SelectionBubbleButton( icon: Codicons.sparkle, label: _polishing ? l10n.stashPolishing : l10n.stashPolish, tooltip: l10n.stashPolishHint, @@ -934,7 +933,7 @@ class MarkdownFormatBarState extends State { ), ), Builder( - builder: (context) => _BarButton( + builder: (context) => SelectionBubbleButton( icon: Codicons.chevronDown, tooltip: l10n.aiModelTooltip( actionsModelName(l10n, ModelProviders.current) ?? @@ -955,6 +954,37 @@ class MarkdownFormatBarState extends State { ); } + /// Where the bar goes in [layer] (the stack's box), [size] as it is, by + /// what it is for as it is laid out now (see [SelectionBubble.placeBy]): + /// the selection, or the link the caret is in. Going, where it was; + /// none of what it is for in view, nowhere. + Offset? _barAt(RenderBox layer, Size size) { + if (size.isEmpty || !layer.hasSize) return null; + TextSelection? range; + MarkdownEditorState? cell; + if (_barAround != null) { + if (_linkCell case final linked? when _linking) { + cell = linked; + range = linked.mounted ? linked.controller.selection : null; + } else { + range = _controller.selection; + } + if (range != null && (!range.isValid || range.isCollapsed)) range = null; + } else if (_caretLink case final link?) { + cell = link.cell; + range = link.range; + } + final Rect? around; + if (range == null || (cell != null && !cell.mounted)) { + around = _barPainted; + } else { + around = _selectionBounds(range, cell); + _barPainted = around; + } + if (around == null) return null; + return SelectionBubble.placeBy(around, Offset.zero & layer.size, size); + } + /// The bar, told when a menu opened from it shows and hides: while one /// does, the bar stays (see [_barMenuShown]). Widget _barWithMenus(BuildContext context, Rect around) => @@ -1042,11 +1072,29 @@ class MarkdownFormatBarState extends State { ), ), ), - // Its menus grow in from a little, as the stash's do. - if (_barAround case final around?) - IdeMotion(lively: true, child: _barWithMenus(context, around)) - else if (_caretLink != null) - IdeMotion(lively: true, child: _linkBar(context)), + // Coming in where the selection is, going out fading; its menus + // grow in from a little, as the stash's do. + Positioned.fill( + child: SelectionBubbleFollower( + place: _barAt, + repaint: _barMoved, + child: FadeAway( + child: switch ((_barAround, _caretLink)) { + (final around?, _) => IdeMotion( + key: const ValueKey('selection'), + lively: true, + child: _barWithMenus(context, around), + ), + (null, _?) => IdeMotion( + key: const ValueKey('link'), + lively: true, + child: _linkBar(context), + ), + _ => null, + }, + ), + ), + ), ], ); } @@ -1054,184 +1102,26 @@ class MarkdownFormatBarState extends State { // --- The bar over the selection ------------------------------------------------ -/// Over the selection, or under it where there is no room above (it -/// never covers what is selected while there is room for it at all). +/// The bar over [around], the selection (or under it where there is no +/// room above: it never covers what is selected while there is room for it +/// at all), placed as it is painted (see [MarkdownFormatBarState._barAt]). class _SelectionBar extends StatelessWidget { const _SelectionBar({required this.around, required this.children}); final Rect around; final List children; - static const _height = 32.0; - static const _gap = 8.0; - - @override - Widget build(BuildContext context) { - return Positioned.fill( - child: LayoutBuilder( - builder: (context, box) { - final above = around.top - _gap - _height; - final below = around.bottom + _gap; - final double top; - var over = true; - if (above >= 0) { - top = above; - } else if (below + _height <= box.maxHeight) { - top = below; - over = false; - } else { - // Selected past both ends: over the end in view. - top = math.max(0, box.maxHeight - _height - _gap); - } - return Stack( - clipBehavior: Clip.none, - children: [ - Positioned( - left: 0, - right: 0, - top: top, - // The editor's own: a click on it is not one beside the - // editor, which would take its focus (and the bar) away - // before the button had it. - child: TextFieldTapRegion( - // Coming in from the selection's side. - child: PopIn( - alignment: over - ? Alignment.bottomCenter - : Alignment.topCenter, - offset: Offset(0, over ? 4 : -4), - child: _bar(around.center.dx), - ), - ), - ), - ], - ); - }, - ), - ); - } - - Widget _bar(double x) { - return LayoutBuilder( - builder: (context, constraints) { - final bar = Container( - height: _height, - padding: const EdgeInsets.symmetric(horizontal: 4), - decoration: BoxDecoration( - color: themeColors['editorWidget.background'], - borderRadius: BorderRadius.circular(8), - border: Border.all(color: themeColors['editorWidget.border']), - boxShadow: [ - BoxShadow( - color: themeColors['widget.shadow'], - blurRadius: 10, - offset: const Offset(0, 2), - ), - ], - ), - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row(mainAxisSize: MainAxisSize.min, children: children), - ), - ); - return Align( - alignment: Alignment( - ((x / math.max(1, constraints.maxWidth)) * 2 - 1).clamp(-1, 1), - 0, - ), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 8), - child: bar, - ), - ); - }, - ); - } -} - -class _BarDivider extends StatelessWidget { - const _BarDivider(); - - @override - Widget build(BuildContext context) => Container( - width: 1, - height: 16, - margin: const EdgeInsets.symmetric(horizontal: 4), - color: AppColors.border, - ); -} - -class _BarButton extends StatelessWidget { - const _BarButton({ - required this.icon, - required this.tooltip, - required this.onTap, - this.label, - this.active = false, - this.busy = false, - }); - - final IconData icon; - final String tooltip; - final VoidCallback onTap; - final String? label; - final bool active; - final bool busy; - @override Widget build(BuildContext context) { - final color = active ? AppColors.textPrimary : AppColors.textMuted; - return IdeHover( - message: tooltip, - child: HoverBuilder( - cursor: SystemMouseCursors.click, - builder: (context, hovered) => GestureDetector( - // Keeps the editor's focus (and selection). - onTapDown: (_) {}, - onTap: busy ? null : onTap, - behavior: HitTestBehavior.opaque, - child: Container( - height: 24, - constraints: const BoxConstraints(minWidth: 24), - padding: EdgeInsets.symmetric(horizontal: label == null ? 0 : 6), - margin: const EdgeInsets.symmetric(horizontal: 1), - decoration: BoxDecoration( - color: active - ? themeColors['toolbar.activeBackground'] - : hovered - ? themeColors['toolbar.hoverBackground'] - : Colors.transparent, - borderRadius: BorderRadius.circular(5), - ), - alignment: Alignment.center, - child: label != null && icon == Icons.title - ? Text( - label!, - style: TextStyle( - color: color, - fontSize: 12, - fontWeight: FontWeight.w600, - ), - ) - : Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - icon, - size: 15, - color: busy ? AppColors.accent : color, - ), - if (label case final label?) ...[ - const SizedBox(width: 4), - Text( - label, - style: TextStyle(color: color, fontSize: 12), - ), - ], - ], - ), - ), - ), + final over = around.top - SelectionBubble.gap - SelectionBubble.height >= 0; + // The editor's own: a click on it is not one beside the editor, which + // would take its focus (and the bar) away before the button had it. + return TextFieldTapRegion( + // Coming in from the selection's side. + child: PopIn( + alignment: over ? Alignment.bottomCenter : Alignment.topCenter, + offset: Offset(0, over ? 4 : -4), + child: SelectionBubble(children: children), ), ); } @@ -1367,7 +1257,7 @@ class _ColorButtonState extends State<_ColorButton> { @override Widget build(BuildContext context) => KeyedSubtree( key: _key, - child: _BarButton( + child: SelectionBubbleButton( icon: Codicons.symbolColor, tooltip: widget.tooltip, onTap: _open, diff --git a/lib/ide/selection_bubble.dart b/lib/ide/selection_bubble.dart new file mode 100644 index 000000000..923f66325 --- /dev/null +++ b/lib/ide/selection_bubble.dart @@ -0,0 +1,273 @@ +// The small bar floating over selected text, and its buttons: a markdown +// editor's marks (see MarkdownFormatBar), the conversation's Copy, Quote +// and By the Way (see ChatHistoryView). + +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +import '../chat/widgets/hover_builder.dart'; +import '../theme/app_theme.dart'; +import '../theme/svg_icons.dart'; +import '../theme/workbench_theme.dart' show themeColors; +import 'ide_hover.dart'; + +/// The bar: [children] in a row, on the editor widgets' background, or +/// [color] within [border] (the chat's, its messages'). +class SelectionBubble extends StatelessWidget { + const SelectionBubble({ + super.key, + required this.children, + this.color, + this.border, + }); + + final List children; + final Color? color; + final Color? border; + + static const height = 32.0; + + /// Between it and the text it is over (or under). + static const gap = 8.0; + + /// Where a bar of [size] goes in [view] by [around], what shows of the + /// text it is for, as a document's editor has it: over it, in its + /// middle; under it where there is no room over it; with room for + /// neither (selected past both ends of the view), over the view's + /// bottom. Kept [gap] off the view's sides. + static Offset placeBy(Rect around, Rect view, Size size) { + final over = around.top - gap - size.height; + final under = around.bottom + gap; + final double y; + if (over >= view.top) { + y = over; + } else if (under + size.height <= view.bottom) { + y = under; + } else { + y = math.max(view.top, view.bottom - size.height - gap); + } + final left = view.left + gap; + final x = (around.center.dx - size.width / 2) + .clamp(left, math.max(left, view.right - size.width - gap)) + .toDouble(); + return Offset(x, y); + } + + @override + Widget build(BuildContext context) => Container( + height: height, + padding: const EdgeInsets.symmetric(horizontal: 4), + decoration: BoxDecoration( + color: color ?? themeColors['editorWidget.background'], + borderRadius: BorderRadius.circular(8), + border: Border.all(color: border ?? themeColors['editorWidget.border']), + boxShadow: [ + BoxShadow( + color: themeColors['widget.shadow'], + blurRadius: 10, + offset: const Offset(0, 2), + ), + ], + ), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row(mainAxisSize: MainAxisSize.min, children: children), + ), + ); +} + +/// Between groups of a [SelectionBubble]'s buttons. +class SelectionBubbleDivider extends StatelessWidget { + const SelectionBubbleDivider({super.key}); + + @override + Widget build(BuildContext context) => Container( + width: 1, + height: 16, + margin: const EdgeInsets.symmetric(horizontal: 4), + color: AppColors.border, + ); +} + +/// A [SelectionBubble]'s button: [icon] (one of [SvgIcons] too), and its +/// [label] if it has one, of [color] (muted by default); [hover] under it +/// hovered (the toolbars' by default). Pressing it keeps the focus where it +/// is (and the selection). +class SelectionBubbleButton extends StatelessWidget { + const SelectionBubbleButton({ + super.key, + required this.icon, + required this.onTap, + this.tooltip, + this.label, + this.active = false, + this.busy = false, + this.color, + this.hover, + }); + + final IconData icon; + final String? tooltip; + final VoidCallback onTap; + final String? label; + final bool active; + final bool busy; + final Color? color; + final Color? hover; + + @override + Widget build(BuildContext context) { + final color = active + ? AppColors.textPrimary + : this.color ?? AppColors.textMuted; + final hover = this.hover ?? themeColors['toolbar.hoverBackground']; + final button = HoverBuilder( + cursor: SystemMouseCursors.click, + builder: (context, hovered) => GestureDetector( + // Keeps the editor's focus (and selection). + onTapDown: (_) {}, + onTap: busy ? null : onTap, + behavior: HitTestBehavior.opaque, + child: AnimatedContainer( + duration: const Duration(milliseconds: 90), + height: 24, + constraints: const BoxConstraints(minWidth: 24), + padding: EdgeInsets.symmetric(horizontal: label == null ? 0 : 6), + margin: const EdgeInsets.symmetric(horizontal: 1), + decoration: BoxDecoration( + color: active + ? themeColors['toolbar.activeBackground'] + : hovered + ? hover + : hover.withValues(alpha: 0), + borderRadius: BorderRadius.circular(5), + ), + alignment: Alignment.center, + child: label != null && icon == Icons.title + ? Text( + label!, + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ) + : Row( + mainAxisSize: MainAxisSize.min, + children: [ + AppIcon( + icon, + size: 15, + color: busy ? AppColors.accent : color, + ), + if (label case final label?) ...[ + const SizedBox(width: 4), + Text(label, style: TextStyle(color: color, fontSize: 12)), + ], + ], + ), + ), + ), + ); + return switch (tooltip) { + final tooltip? => IdeHover(message: tooltip, child: button), + null => button, + }; + } +} + +/// Fills what it is given, and paints [child] (laid out at its own size) +/// where [place] puts it, read at paint time: after layout, so it goes with +/// what it is placed by elsewhere in the tree in the same frame (the +/// selection as it is dragged, the text as it scrolls), not a frame behind +/// it. Paints nothing where [place] gives no place. [repaint] says when it +/// may move. +class SelectionBubbleFollower extends SingleChildRenderObjectWidget { + const SelectionBubbleFollower({ + super.key, + required this.place, + required this.repaint, + required super.child, + }); + + final Offset? Function(RenderBox layer, Size child) place; + final Listenable repaint; + + @override + RenderObject createRenderObject(BuildContext context) => + _RenderFollower(place, repaint); + + @override + void updateRenderObject(BuildContext context, RenderObject renderObject) { + (renderObject as _RenderFollower) + ..place = place + ..repaint = repaint; + } +} + +class _RenderFollower extends RenderProxyBox { + _RenderFollower(this.place, this._repaint); + + Offset? Function(RenderBox layer, Size child) place; + Offset? _painted; + + Listenable _repaint; + set repaint(Listenable value) { + if (identical(value, _repaint)) return; + if (attached) { + _repaint.removeListener(markNeedsPaint); + value.addListener(markNeedsPaint); + } + _repaint = value; + } + + @override + void attach(PipelineOwner owner) { + super.attach(owner); + _repaint.addListener(markNeedsPaint); + } + + @override + void detach() { + _repaint.removeListener(markNeedsPaint); + super.detach(); + } + + @override + void performLayout() { + size = constraints.biggest; + child?.layout(constraints.loosen(), parentUsesSize: true); + } + + @override + void paint(PaintingContext context, Offset offset) { + final child = this.child; + _painted = child == null ? null : place(this, child.size); + if (child != null && _painted != null) { + context.paintChild(child, offset + _painted!); + } + } + + @override + bool hitTestSelf(Offset position) => false; + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + final painted = _painted; + final child = this.child; + if (painted == null || child == null) return false; + return result.addWithPaintOffset( + offset: painted, + position: position, + hitTest: (result, position) => child.hitTest(result, position: position), + ); + } + + @override + void applyPaintTransform(RenderBox child, Matrix4 transform) { + final painted = _painted ?? Offset.zero; + transform.translateByDouble(painted.dx, painted.dy, 0, 1); + } +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 4fd974d60..117c9b7a4 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1514,6 +1514,23 @@ } } }, + "quoteChip": "Quote #{number}", + "@quoteChip": { + "description": "Text quoted from the conversation, as a small tag in a message: the quote's number in the message.", + "placeholders": { + "number": { + "type": "int" + } + } + }, + "chatQuote": "Quote", + "@chatQuote": { + "description": "Over text selected in the conversation: puts it in the message being written, as a quote of it." + }, + "chatQuoteAside": "By the Way", + "@chatQuoteAside": { + "description": "Over text selected in the conversation: quotes it in a /btw message, asked in a conversation of its own beside this one." + }, "pastedTextGone": "This paste is no longer at {path}.", "@pastedTextGone": { "description": "Shown in place of a long paste kept in a file that has since gone.", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 799d7dbaa..2c93d6778 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -4658,6 +4658,24 @@ abstract class AppLocalizations { /// **'Pasted text #{number}'** String pastedTextChip(int number); + /// Text quoted from the conversation, as a small tag in a message: the quote's number in the message. + /// + /// In en, this message translates to: + /// **'Quote #{number}'** + String quoteChip(int number); + + /// Over text selected in the conversation: puts it in the message being written, as a quote of it. + /// + /// In en, this message translates to: + /// **'Quote'** + String get chatQuote; + + /// Over text selected in the conversation: quotes it in a /btw message, asked in a conversation of its own beside this one. + /// + /// In en, this message translates to: + /// **'By the Way'** + String get chatQuoteAside; + /// Shown in place of a long paste kept in a file that has since gone. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 7a5d4927f..ca3932c5f 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2629,6 +2629,17 @@ class AppLocalizationsEn extends AppLocalizations { return 'Pasted text #$number'; } + @override + String quoteChip(int number) { + return 'Quote #$number'; + } + + @override + String get chatQuote => 'Quote'; + + @override + String get chatQuoteAside => 'By the Way'; + @override String pastedTextGone(String path) { return 'This paste is no longer at $path.'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 5b20d0351..8cd972f29 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2542,6 +2542,17 @@ class AppLocalizationsZh extends AppLocalizations { return '粘贴的文本 #$number'; } + @override + String quoteChip(int number) { + return '引用 #$number'; + } + + @override + String get chatQuote => '引用'; + + @override + String get chatQuoteAside => '顺带一提'; + @override String pastedTextGone(String path) { return '这段粘贴的内容已不在 $path。'; diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 4e01db0d9..88c2fdc62 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -760,6 +760,9 @@ "imageChip": "图片 {number}", "imageReferenceRemoved": "[图片 {number}]", "pastedTextChip": "粘贴的文本 #{number}", + "quoteChip": "引用 #{number}", + "chatQuote": "引用", + "chatQuoteAside": "顺带一提", "pastedTextGone": "这段粘贴的内容已不在 {path}。", "pastedTextLines": "{count, plural, other{+{count} 行}}", "imageCopy": "复制图片", diff --git a/lib/theme/svg_icons.dart b/lib/theme/svg_icons.dart index 10a0eea6b..69b229670 100644 --- a/lib/theme/svg_icons.dart +++ b/lib/theme/svg_icons.dart @@ -10,7 +10,18 @@ abstract final class SvgIcons { /// Usage: a conversation's, and Settings → Usage (Lucide's chart-pie). static const usage = IconData(0xe000, fontFamily: fontFamily); - static const _assets = {0xe000: 'assets/icons/lucide-chart-pie.svg'}; + /// The conversation's selection bar's Copy, Quote and By the Way (Remix + /// Icon's file-copy-line, double-quotes-l and chat-3-line). + static const copy = IconData(0xe001, fontFamily: fontFamily); + static const quote = IconData(0xe002, fontFamily: fontFamily); + static const aside = IconData(0xe003, fontFamily: fontFamily); + + static const _assets = { + 0xe000: 'assets/icons/lucide-chart-pie.svg', + 0xe001: 'assets/icons/file-copy-line.svg', + 0xe002: 'assets/icons/double-quotes-l.svg', + 0xe003: 'assets/icons/chat-3-line.svg', + }; /// [icon]'s SVG, where it is one of these. static String? assetOf(IconData icon) => diff --git a/test/chat/composer_files_test.dart b/test/chat/composer_files_test.dart index ad640f0ce..58dacb698 100644 --- a/test/chat/composer_files_test.dart +++ b/test/chat/composer_files_test.dart @@ -253,6 +253,63 @@ void main() { expect(splitCodeAppendix(text).body, text); }); + test('quotes go as the user\'s, numbered apart from the pastes, and read ' + 'back, kept in a file or not', () { + const quote = PastedText( + number: 1, + text: 'line one\nline two', + quoted: true, + ); + const paste = PastedText(number: 1, text: 'a\nb'); + expect(quote.reference, '[Quote #1]'); + final text = + 'why ${quote.reference} and ${paste.reference}' + '${codeAppendix([quote, paste])}'; + expect( + text, + 'why [Quote #1] and [Pasted text #1 +1 line]\n' + '\n' + '[Quote #1] (text the user selected and quoted from the ' + 'conversation)\n' + '```\n' + 'line one\n' + 'line two\n' + '```\n' + '\n' + '[Pasted text #1 +1 line]\n' + '```\n' + 'a\n' + 'b\n' + '```', + ); + final split = splitCodeAppendix(text); + expect(split.body, 'why [Quote #1] and [Pasted text #1 +1 line]'); + expect(split.references, { + quote.reference: quote, + paste.reference: paste, + }); + expect(PastedText.fromJson(quote.toJson()), quote); + + final kept = quote.storedAt('/data/pastes/q.txt'); + final keptText = 'why ${kept.reference}${codeAppendix([kept])}'; + expect( + keptText, + 'why [Quote #1]\n' + '\n' + '[Quote #1] (text the user selected and quoted from the ' + 'conversation)\n' + 'Too long to include here, saved in full to `/data/pastes/q.txt`: ' + 'read it from there.', + ); + final back = splitCodeAppendix(keptText).references['[Quote #1]']; + expect(back, isA()); + back as PastedText; + expect( + (back.quoted, back.file, back.number), + (true, '/data/pastes/q.txt', 1), + ); + }); + test('stashes read back by their number, with fences in them', () { const stash = StashReference( id: 12, diff --git a/test/chat/history_selection_test.dart b/test/chat/history_selection_test.dart index 549f44519..8b76deec6 100644 --- a/test/chat/history_selection_test.dart +++ b/test/chat/history_selection_test.dart @@ -10,6 +10,7 @@ import 'package:baocode/chat/chat_session.dart'; import 'package:baocode/chat/selection/chat_selection.dart'; import 'package:baocode/chat/composer/composer_draft.dart'; import 'package:baocode/chat/widgets/step_header.dart'; +import 'package:baocode/ide/selection_bubble.dart'; import 'package:baocode/theme/app_theme.dart'; import 'package:super_sliver_list/super_sliver_list.dart'; @@ -1468,6 +1469,232 @@ void main() { }, variant: TargetPlatformVariant.desktop(), ); + + testWidgets('a selection has its bar over it as soon as it is made, the ' + 'drag still held; Quote hands its text over; it goes with the text as ' + 'the list scrolls, and fades out at the next press', (tester) async { + final quoted = []; + const answer = 'The parser drops the last token.'; + final feed = _Feed([ + for (var i = 0; i < 12; i++) ...[ + UserMessageItem(text: 'Question $i?'), + AssistantTextItem('Answer $i, long enough to scroll.\n\nMore of it.'), + ], + const UserMessageItem(text: 'Why does it fail?'), + const AssistantTextItem(answer), + ])..streaming = false; + addTearDown(feed.dispose); + await tester.pumpWidget( + MaterialApp( + theme: buildAppTheme(), + home: Scaffold( + body: ChatHistoryView(feed: feed, onQuote: quoted.add), + ), + ), + ); + await tester.pumpAndSettle(); + + final paragraph = tester.renderObject( + find.byWidgetPredicate( + (widget) => widget is RichText && widget.text.toPlainText() == answer, + ), + ); + final quote = find.text('Quote'); + final mouse = await tester.startGesture( + paragraph.localToGlobal(Offset(0.5, paragraph.size.height / 2)), + kind: PointerDeviceKind.mouse, + ); + await tester.pump(); + await mouse.moveTo( + paragraph.localToGlobal( + Offset(paragraph.size.width - 0.5, paragraph.size.height / 2), + ), + ); + await tester.pumpAndSettle(); + expect(quote, findsOneWidget, reason: 'while the drag is held'); + await mouse.up(); + await tester.pumpAndSettle(); + expect(quote, findsOneWidget); + expect(find.text('By the Way'), findsNothing, reason: 'nothing aside'); + // One line selected: over it. + final line = paragraph.localToGlobal(Offset.zero).dy; + final bar = find.byType(SelectionBubble); + expect(tester.getRect(bar).bottom, lessThanOrEqualTo(line)); + + // Scrolled, it goes with the text in the same frame. + final before = tester.getRect(bar).top; + final position = tester + .state(find.byType(Scrollable).first) + .position; + position.jumpTo(position.pixels - 30); + await tester.pump(); + expect(tester.getRect(bar).top, closeTo(before + 30, 0.5)); + + await tester.tap(quote); + await tester.pump(); + expect(quoted, [answer]); + // Fading out, then gone. + expect(quote, findsOneWidget); + await tester.pumpAndSettle(); + expect(quote, findsNothing); + + // Shown again, a press in the text takes it away. + final again = await tester.startGesture( + paragraph.localToGlobal(Offset(0.5, paragraph.size.height / 2)), + kind: PointerDeviceKind.mouse, + ); + await again.moveTo( + paragraph.localToGlobal( + Offset(paragraph.size.width - 0.5, paragraph.size.height / 2), + ), + ); + await again.up(); + await tester.pumpAndSettle(); + expect(quote, findsOneWidget); + // Away from the last press: not a second click of a double one + // (which selects a word, and has its bar). + await tester.tapAt( + paragraph.localToGlobal( + Offset(paragraph.size.width - 2, paragraph.size.height / 2), + ), + kind: PointerDeviceKind.mouse, + ); + await tester.pumpAndSettle(); + expect(quote, findsNothing); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + + testWidgets('the bar is over the selection, in its middle, as a ' + 'document\'s editor has it: over the characters within a line, over the ' + 'text across lines; as it grows, there at once', (tester) async { + const first = 'The parser drops the last token of every line.'; + const second = 'Then the printer has nothing to close the block with.'; + final feed = _Feed([ + const UserMessageItem(text: 'Why does it fail?'), + const AssistantTextItem('$first\n\n$second'), + ])..streaming = false; + addTearDown(feed.dispose); + await tester.pumpWidget( + MaterialApp( + theme: buildAppTheme(), + home: Scaffold( + body: ChatHistoryView(feed: feed, onQuote: (_) {}), + ), + ), + ); + await tester.pumpAndSettle(); + RenderParagraph paragraph(String text) => + tester.renderObject( + find.byWidgetPredicate( + (widget) => widget is RichText && widget.text.toPlainText() == text, + ), + ); + final top = paragraph(first); + final bottom = paragraph(second); + Offset at(RenderParagraph p, double x) => + p.localToGlobal(Offset(x, p.size.height / 2)); + final bar = find.byType(SelectionBubble); + final firstLine = top.localToGlobal(Offset.zero).dy; + + // Within a line: over the characters selected, in their middle (within + // a character of it: the selection ends at characters' edges). + final drag = await tester.startGesture( + at(top, 2), + kind: PointerDeviceKind.mouse, + ); + await tester.pump(); + await drag.moveTo(at(top, 120)); + await tester.pumpAndSettle(); + var rect = tester.getRect(bar); + expect(rect.bottom, lessThanOrEqualTo(firstLine)); + expect(rect.center.dx, closeTo((at(top, 2).dx + at(top, 120).dx) / 2, 16)); + + // Further along the line: in the middle again in the frame the + // selection is, not one behind it, there at once (it only comes and + // goes softly). + await drag.moveTo(at(top, 240)); + await tester.pump(); + rect = tester.getRect(bar); + expect(rect.center.dx, closeTo((at(top, 2).dx + at(top, 240).dx) / 2, 16)); + await tester.pumpAndSettle(); + expect(tester.getRect(bar), rect); + + // Across lines: over the first, in the middle of the text. + await drag.moveTo(at(bottom, 60)); + await tester.pumpAndSettle(); + rect = tester.getRect(bar); + expect(rect.bottom, lessThanOrEqualTo(firstLine)); + final text = (top.localToGlobal(Offset.zero) & top.size).expandToInclude( + bottom.localToGlobal(Offset.zero) & bottom.size, + ); + expect(rect.center.dx, closeTo(text.center.dx, 8)); + await drag.up(); + await tester.pumpAndSettle(); + expect(bar, findsOneWidget, reason: 'left where it is'); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + + testWidgets('dragged from the end of a message down into the reply, the ' + 'bar is over the reply\'s text, not over the message the drag began ' + 'beside', (tester) async { + const asked = 'Why does it fail?'; + const answer = 'The parser drops the last token of every line.'; + final feed = _Feed([ + for (var i = 0; i < 3; i++) ...[ + UserMessageItem(text: 'Question $i?'), + AssistantTextItem('Answer $i.'), + ], + const UserMessageItem(text: asked), + const AssistantTextItem(answer), + ])..streaming = false; + addTearDown(feed.dispose); + await tester.pumpWidget( + MaterialApp( + theme: buildAppTheme(), + home: Scaffold( + body: ChatHistoryView(feed: feed, onQuote: (_) {}), + ), + ), + ); + await tester.pumpAndSettle(); + RenderParagraph paragraph(String text) => + tester.renderObject( + find + .descendant( + of: find.byType(SuperListView), + matching: find.byWidgetPredicate( + (widget) => + widget is RichText && widget.text.toPlainText() == text, + ), + ) + .first, + ); + final message = paragraph(asked); + final reply = paragraph(answer); + final drag = await tester.startGesture( + // Past the message's last character, in its bubble. + message.localToGlobal( + Offset(message.size.width + 2, message.size.height / 2), + ), + kind: PointerDeviceKind.mouse, + ); + await tester.pump(); + await drag.moveTo(reply.localToGlobal(Offset(300, reply.size.height / 2))); + await tester.pumpAndSettle(); + final rect = tester.getRect(find.byType(SelectionBubble)); + final replyTop = reply.localToGlobal(Offset.zero).dy; + expect(rect.bottom, lessThanOrEqualTo(replyTop)); + expect( + rect.top, + greaterThan(message.localToGlobal(Offset.zero).dy), + reason: 'not over the message\'s line', + ); + // In the middle of what of the reply is selected. + expect( + rect.center.dx, + closeTo(reply.localToGlobal(const Offset(150, 0)).dx, 16), + ); + await drag.up(); + await tester.pumpAndSettle(); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); } /// A piece of text, in a box of its own. diff --git a/test/composer_test.dart b/test/composer_test.dart index a9c254489..dca933c96 100644 --- a/test/composer_test.dart +++ b/test/composer_test.dart @@ -703,6 +703,54 @@ void main() { ); }); + testWidgets('text quoted from the conversation goes in as tags after what ' + 'is typed; By the Way makes the message a /btw, once', (tester) async { + ComposerMessage? asked; + final session = ChatSession(historyCount: 16); + addTearDown(session.dispose); + await tester.pumpWidget( + MaterialApp( + theme: buildAppTheme(), + home: ChatScreen( + session: session, + onSideQuestion: (message) => asked = message, + ), + ), + ); + await tester.pump(); + await typeText(tester, 'why'); + final controller = composerController(tester); + + session.draft.insertQuote('line one\nline two'); + await tester.pump(); + expect(session.draft.pendingQuotes, isEmpty); + expect(composerPlainText(controller.text), 'why [Quote #1] '); + + session.draft.insertQuote('more', aside: true); + await tester.pump(); + expect( + composerPlainText(controller.text), + '/btw why [Quote #1] [Quote #2] ', + ); + // The caret after the tags, for the question. + expect(controller.selection.baseOffset, controller.length); + + session.draft.insertQuote('again', aside: true); + await tester.pump(); + expect( + composerPlainText(controller.text), + '/btw why [Quote #1] [Quote #2] [Quote #3] ', + ); + + await pressKey(tester, LogicalKeyboardKey.enter); + expect(session.itemCount, 16, reason: 'asked beside, not here'); + expect( + asked?.text, + 'why [Quote #1] [Quote #2] [Quote #3]' + '${codeAppendix(const [PastedText(number: 1, text: 'line one\nline two', quoted: true), PastedText(number: 2, text: 'more', quoted: true), PastedText(number: 3, text: 'again', quoted: true)])}', + ); + }); + testWidgets('accepting a suggestion inserts exactly one space', ( tester, ) async { diff --git a/test/ide/markdown/markdown_preview_test.dart b/test/ide/markdown/markdown_preview_test.dart index d1f83bb3d..c84bd2fe0 100644 --- a/test/ide/markdown/markdown_preview_test.dart +++ b/test/ide/markdown/markdown_preview_test.dart @@ -5,6 +5,7 @@ import 'package:bao_editor/monaco/flutter/editor_document_model.dart'; import 'package:bao_markdown/bao_markdown.dart'; import 'package:baocode/chat/widgets/markdown_math.dart'; import 'package:baocode/ide/ide_find_widget.dart'; +import 'package:baocode/ide/selection_bubble.dart'; import 'package:baocode/ide/markdown/markdown_preview.dart'; import 'package:baocode/ide/markdown/markdown_task_box.dart'; import 'package:baocode/theme/app_theme.dart'; @@ -639,6 +640,51 @@ void main() { expect(find.byIcon(Codicons.bold), findsNothing); }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + testWidgets('selected by a drag, the bar comes in at once, over the ' + 'selection\'s middle; goes where the selection goes in that frame, ' + 'and fades out as it goes', (tester) async { + // What is selected along the line, the bar not kept off its start. + const text = 'Words first: some text here, and more.'; + final model = EditorDocumentModel(text); + await pumpPreview(tester, model); + final from = _at(tester, 'some', within: text); + final drag = await tester.startGesture(from, kind: PointerDeviceKind.mouse); + await tester.pump(); + await drag.moveTo(_at(tester, 'here', within: text)); + await tester.pumpAndSettle(); + final bar = find.byType(SelectionBubble); + final bold = find.byIcon(Codicons.bold); + expect(bold, findsOneWidget, reason: 'while the drag is held'); + var rect = tester.getRect(bar); + // Under it: no room over the document's first line. + expect(rect.top, greaterThanOrEqualTo(from.dy)); + expect( + rect.center.dx, + closeTo((from.dx + _at(tester, 'here', within: text).dx) / 2, 16), + ); + + // Further on: there in the frame the selection is, at once (it only + // comes and goes softly). + final to = _at(tester, 'more', within: text); + await drag.moveTo(to); + await tester.pump(); + rect = tester.getRect(bar); + expect(rect.center.dx, closeTo((from.dx + to.dx) / 2, 16)); + await tester.pumpAndSettle(); + expect(tester.getRect(bar), rect); + await drag.up(); + await tester.pumpAndSettle(); + expect(bold, findsOneWidget); + + _controller(tester).selection = const TextSelection.collapsed(offset: 2); + await tester.pump(); + await tester.pump(); + expect(bold, findsOneWidget, reason: 'fading out'); + expect(tester.getRect(bar), rect, reason: 'where it was'); + await tester.pumpAndSettle(); + expect(bold, findsNothing); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + testWidgets('selected in code, the bar only proofreads; ⌘B marks nothing', ( tester, ) async {