Support unfocused chat composer paste

This commit is contained in:
2026-11-07 22:32:07 +00:00
parent f6ca558302
commit 63758cd176
12 changed files with 619 additions and 35 deletions
@@ -20,6 +20,7 @@ import '../ui/sessions/chat_adaptive.dart';
import 'chat_command_actions.dart';
import 'chat_command_palette.dart';
import 'chat_composer_controller.dart';
import 'chat_composer_paste_focus.dart';
import '../ui/transcript/chat_attachment_frame.dart';
import '../../../ui/adaptive/glass_bar.dart';
import '../../../ui/adaptive/glass_pill.dart';
@@ -117,6 +118,7 @@ class ChatComposerBar extends StatefulWidget {
this.picker,
this.commands,
this.paste,
this.pasteTarget = true,
this.backgroundTasks,
this.placeholder = chatComposerPlaceholder,
this.enterSends,
@@ -152,6 +154,9 @@ class ChatComposerBar extends StatefulWidget {
/// The host clipboard-file seam; production uses [hostChatClipboardPaste].
final ChatClipboardPaste? paste;
/// True only for the active visible pane.
final bool pasteTarget;
final Widget? backgroundTasks;
@override
@@ -215,6 +220,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
canRestore: _composerIsCurrent,
);
widget.composer.addListener(_syncDraft);
ChatComposerPasteFocus.register(_focus);
FocusManager.instance.addEarlyKeyEventHandler(_nativePasteKey);
_listenForPaste();
unawaited(widget.composer.loadDraft());
}
@@ -241,7 +248,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
_seenAccepted = widget.composer.composerSendsAccepted;
_syncDraft();
}
if (oldWidget.paste != widget.paste) {
if (oldWidget.paste != widget.paste ||
oldWidget.pasteTarget != widget.pasteTarget) {
_stopListeningForPaste();
_listenForPaste();
}
@@ -253,6 +261,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
onFiles: _onPastedFiles,
canAccept: _canAcceptPaste,
onError: _onPasteError,
onText: _onPastedText,
canAcceptText: _canAcceptTextPaste,
);
}
@@ -262,12 +272,62 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
stop?.call();
}
/// A pasted file is taken only while this composer owns the field and no
/// prompt is in flight, which is the same window as the attach control. The
/// host checks this before it suppresses the paste's default behaviour, so a
/// paste elsewhere is never swallowed.
/// A pasted file is taken by the active, visible composer even when its
/// field is not focused. The host checks this before suppressing the paste's
/// default behaviour, so an inactive pane is never allowed to swallow it.
bool _canAcceptPaste() =>
mounted && _focus.hasFocus && !widget.composer.sending;
mounted &&
widget.pasteTarget &&
_composerIsCurrent() &&
!ChatComposerPasteFocus.anotherEditableHasFocus &&
!widget.composer.sending;
bool _canAcceptTextPaste() => _canAcceptPaste() && !_focus.hasFocus;
KeyEventResult _nativePasteKey(KeyEvent event) {
// Web uses the browser's clipboard event, never a second Clipboard read.
if (kIsWeb || event is! KeyDownEvent || !_canAcceptTextPaste()) {
return KeyEventResult.ignored;
}
final keys = HardwareKeyboard.instance;
if (event.logicalKey != LogicalKeyboardKey.keyV ||
keys.isAltPressed ||
keys.isShiftPressed ||
!(keys.isControlPressed != keys.isMetaPressed)) {
return KeyEventResult.ignored;
}
unawaited(_readNativePaste());
return KeyEventResult.handled;
}
Future<void> _readNativePaste() async {
try {
final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text;
if (text != null && text.isNotEmpty) _onPastedText(text);
} catch (_) {
if (mounted && _canAcceptPaste()) {
_onPasteError('Could not read clipboard text.');
}
}
}
void _onPastedText(String text) {
// Recheck after an asynchronous native read, but permit the same composer
// to have received focus meanwhile. Never insert into another editor.
if (!mounted || !_canAcceptPaste()) return;
final value = _text.value;
final selection = value.selection.isValid
? value.selection
: TextSelection.collapsed(offset: value.text.length);
final next = value.text.replaceRange(selection.start, selection.end, text);
_text.value = TextEditingValue(
text: next,
selection: TextSelection.collapsed(offset: selection.start + text.length),
);
_onDraftEdited(next);
_focus.requestFocus();
}
void _onPastedFiles(List<ChatPickedFile> files) {
if (!mounted) return;
@@ -669,6 +729,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
@override
void dispose() {
_stopListeningForPaste();
FocusManager.instance.removeEarlyKeyEventHandler(_nativePasteKey);
ChatComposerPasteFocus.unregister(_focus);
widget.composer.removeListener(_syncDraft);
_focusRestorer.dispose();
_focusRequests.dispose();
@@ -0,0 +1,25 @@
import 'package:flutter/widgets.dart';
/// Flutter shares a single web editing element across fields. DOM identity
/// alone cannot tell a chat composer from search, rename or another editor.
abstract final class ChatComposerPasteFocus {
static final Set<FocusNode> _composers = {};
static void register(FocusNode focus) => _composers.add(focus);
static void unregister(FocusNode focus) => _composers.remove(focus);
static bool get anotherEditableHasFocus {
final primary = FocusManager.instance.primaryFocus;
if (primary == null || _composers.any((focus) => focus.hasFocus)) {
return false;
}
final context = primary.context;
if (context == null) return false;
var editable = context.widget is EditableText;
context.visitAncestorElements((element) {
if (element.widget is EditableText) editable = true;
return !editable;
});
return editable;
}
}
@@ -98,6 +98,7 @@ class ChatThreadView extends StatefulWidget {
this.sidebarControl,
this.showBackButton,
this.useNativeBack = false,
this.pasteTarget = true,
});
final ApiGateway gateway;
@@ -108,6 +109,7 @@ class ChatThreadView extends StatefulWidget {
final Widget? sidebarControl;
final bool? showBackButton;
final bool useNativeBack;
final bool pasteTarget;
/// Sets the chat's shared colour (a palette name, null for none) from the
/// information sheet; null leaves the sheet without the Colour choice.
@@ -1061,6 +1063,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
'${widget.session?['directory'] ?? ''}',
),
chatColor: chatSessionColor(widget.session),
pasteTarget: widget.pasteTarget,
backgroundTasks: ChatBackgroundTasks(
key: ValueKey('chat-background-tasks-${widget.sessionId}'),
gateway: widget.gateway,
@@ -5,10 +5,12 @@ import 'chat_clipboard_paste_stub.dart'
/// Receives the files one paste carried, in clipboard order.
typedef ChatPasteFiles = void Function(List<ChatPickedFile> files);
typedef ChatPasteText = void Function(String text);
/// Whether the composer would take a pasted file right now. The host asks this
/// before it suppresses the paste's default behaviour.
typedef ChatPasteCanAccept = bool Function();
typedef ChatPasteCanAcceptText = bool Function();
/// Reports a clipboard file whose bytes could not be read.
typedef ChatPasteFailed = void Function(Object error);
@@ -19,13 +21,16 @@ typedef ChatPasteUnsubscribe = void Function();
/// Registers [onFiles] for file pastes the composer may take and returns the
/// cancellation for that registration.
///
/// A text-only paste is never reported: it stays with the host field, so caret,
/// selection and the draft update exactly as typing does.
/// A text-only paste is reported when the active chat pane owns it; otherwise
/// it stays with the host field, so unrelated editable controls keep native
/// caret and selection behaviour.
typedef ChatPasteSubscribe =
ChatPasteUnsubscribe Function(
ChatPasteFiles onFiles,
ChatPasteCanAccept canAccept,
ChatPasteFailed onError,
ChatPasteText onText,
ChatPasteCanAcceptText canAcceptText,
);
/// The clipboard seam for one host.
@@ -60,10 +65,18 @@ class ChatClipboardPaste {
required ChatPasteFiles onFiles,
required ChatPasteCanAccept canAccept,
required ChatPasteFailed onError,
ChatPasteText? onText,
ChatPasteCanAcceptText? canAcceptText,
}) {
final subscribe = this.subscribe;
if (subscribe == null) throw UnsupportedError(unsupportedMessage!);
return subscribe(onFiles, canAccept, onError);
return subscribe(
onFiles,
canAccept,
onError,
onText ?? (_) {},
canAcceptText ?? () => false,
);
}
}
@@ -4,28 +4,36 @@ import 'dart:js_interop_unsafe';
import 'chat_attachment_picker.dart';
import 'chat_clipboard_paste.dart';
import 'chat_clipboard_target_web.dart';
/// The browser's clipboard-file paste, observed at the document once per
/// composer.
///
/// Declared with `dart:js_interop` rather than `package:web`, so the same source
/// compiles for the JavaScript and WebAssembly web targets. A paste carrying no
/// file is left completely alone: the field's own text paste keeps its caret,
/// selection and draft behaviour. Only a paste with files the composer will
/// accept is consumed, and its bytes are read before the files join the
/// composer's attachment draft.
/// Browser clipboard paste observed at the document for each mounted composer.
/// Focused fields retain native text insertion. An eligible active composer can
/// receive unfocused text or files; external editors retain their own paste.
/// Uses dart:js_interop so the bridge supports JavaScript and WebAssembly builds.
@JS('document')
external _Document get _document;
extension type _Document._(JSObject _) implements JSObject {
external void addEventListener(JSString type, JSFunction listener);
external void addEventListener(
JSString type,
JSFunction listener,
JSBoolean capture,
);
external void removeEventListener(JSString type, JSFunction listener);
external void removeEventListener(
JSString type,
JSFunction listener,
JSBoolean capture,
);
external JSObject? get activeElement;
}
extension type _ClipboardEvent._(JSObject _) implements JSObject {
external bool get defaultPrevented;
external JSObject? get target;
external _ClipboardData? get clipboardData;
external void preventDefault();
@@ -33,6 +41,8 @@ extension type _ClipboardEvent._(JSObject _) implements JSObject {
extension type _ClipboardData._(JSObject _) implements JSObject {
external _DataTransferItemList get items;
external JSString getData(JSString format);
}
extension type _DataTransferItemList._(JSObject _) implements JSObject {
@@ -60,6 +70,8 @@ ChatPasteUnsubscribe _subscribeToPaste(
ChatPasteFiles onFiles,
ChatPasteCanAccept canAccept,
ChatPasteFailed onError,
ChatPasteText onText,
ChatPasteCanAcceptText canAcceptText,
) {
var sequence = 0;
@@ -79,15 +91,31 @@ ChatPasteUnsubscribe _subscribeToPaste(
final file = item.getAsFile();
if (file != null) files.add(file);
}
// A text-only clipboard keeps the field's native paste untouched.
if (files.isEmpty || !canAccept()) return;
if (chatPasteHasExternalEditable(raw)) return;
if (files.isNotEmpty) {
// An active chat pane may take over from an inactive chat composer, but
// an unrelated editable field keeps the browser's native paste.
if (!canAccept()) {
return;
}
event.preventDefault();
unawaited(_readFiles(files, onFiles, onError, () => ++sequence));
return;
}
// A focused composer owns its native paste. An eligible active pane may
// take over when the focused editable is an inactive chat composer.
if (!canAcceptText()) {
return;
}
final text = data.getData('text/plain'.toJS).toDart;
if (text.isEmpty) return;
event.preventDefault();
unawaited(_readFiles(files, onFiles, onError, () => ++sequence));
onText(text);
}
final listener = handlePaste.toJS;
_document.addEventListener('paste'.toJS, listener);
return () => _document.removeEventListener('paste'.toJS, listener);
_document.addEventListener('paste'.toJS, listener, true.toJS);
return () => _document.removeEventListener('paste'.toJS, listener, true.toJS);
}
Future<void> _readFiles(
@@ -0,0 +1,67 @@
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
@JS('document')
external _Document get _document;
extension type _Document._(JSObject _) implements JSObject {
external JSObject? get activeElement;
}
extension type _Event._(JSObject _) implements JSObject {
external JSObject? get target;
external JSArray<JSObject> composedPath();
}
/// Never take a paste owned by an external editor. Flutter field ownership is
/// checked by the composer's Flutter FocusNode before this DOM check; the
/// engine's shared flt-text-editing element is not itself a composer identity.
bool chatPasteHasExternalEditable(JSObject event) {
final paste = _Event._(event);
final candidates = <JSObject>[...paste.composedPath().toDart];
if (paste.target case final target?) candidates.add(target);
var active = _document.activeElement;
for (var depth = 0; active != null && depth < 32; depth++) {
candidates.add(active);
final shadow = active.getProperty<JSObject?>('shadowRoot'.toJS);
final next = shadow?.getProperty<JSObject?>('activeElement'.toJS);
if (next == null) break;
active = next;
}
for (final node in candidates) {
final tag = node
.getProperty<JSString?>('tagName'.toJS)
?.toDart
.toUpperCase();
final editable =
tag == 'INPUT' ||
tag == 'TEXTAREA' ||
node.getProperty<JSBoolean?>('isContentEditable'.toJS)?.toDart == true;
if (editable) {
final classes =
node.getProperty<JSString?>('className'.toJS)?.toDart ?? '';
final parent = node.getProperty<JSObject?>('parentElement'.toJS);
final semanticsOwned =
parent
?.getProperty<JSString?>('tagName'.toJS)
?.toDart
.toUpperCase() ==
'FLT-SEMANTICS';
if (!classes.split(RegExp(r'\s+')).contains('flt-text-editing') &&
!semanticsOwned) {
return true;
}
}
}
// A focused embedded document or opaque custom-element editor owns its
// keyboard. Closed shadow roots cannot expose their private editable node.
if (active != null) {
final tag =
active.getProperty<JSString?>('tagName'.toJS)?.toDart.toUpperCase() ??
'';
if (tag == 'IFRAME' || (tag.contains('-') && !tag.startsWith('FLT-'))) {
return true;
}
}
return false;
}
+1
View File
@@ -469,6 +469,7 @@ class _ChatScreenState extends State<ChatScreen>
? () => _openNext(selected)
: null,
useNativeBack: _page.open,
pasteTarget: pane == null || pane.id == _workspace.activePaneId,
showBackButton: pane == null
? null
: _page.open || !showsListBesideDetail(context),