Support unfocused chat composer paste
This commit is contained in:
@@ -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;
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# Unfocused chat paste
|
||||
|
||||
Text paste routes to the active visible chat composer from transcript/background chrome. Native Cmd/Ctrl+V uses a single controlled Clipboard read when that composer is unfocused. Web uses the browser paste event without another clipboard read. Focused active composers retain native text insertion; another Flutter search/rename editor or external DOM editor retains its own paste. A stale inactive composer cannot swallow active-pane paste.
|
||||
|
||||
Routing combines Flutter focus ownership with DOM composed-path and open-shadow-root checks. Engine shared `flt-text-editing` elements and accessibility-mode inputs directly owned by `flt-semantics` remain eligible for the Flutter ownership check. Opaque external custom-element/iframe focus is conservatively left native. File/image paste follows the existing web attachment path, including focused accessibility-mode composers. Native file clipboard remains unsupported as before.
|
||||
|
||||
Verification:
|
||||
- 22 focused VM tests passed under `tool/memwatch/full.sh 'test/features/chat/conversation/chat_unfocused_paste_routing_test.dart test/features/chat/conversation/chat_composer_paste_test.dart test/features/chat/domain/chat_clipboard_paste_test.dart'`, `/tmp/memwatch/out.6cFRrZ`. Real composer wiring exercises Cmd/Ctrl+V, another editor, focused active composer exactly once, inactive focused composer and file/text acceptance. Clipboard is mocked through the platform channel; no host clipboard access.
|
||||
- 7 Chrome tests passed under `tool/memwatch/full.sh 'test/features/chat/domain/chat_clipboard_paste_web_test.dart --platform chrome'`, `/tmp/memwatch/out.RK4wSb`. Real synthetic ClipboardEvent/DataTransfer covers text/files/images, external textarea, open and closed shadows, Flutter eligibility and capture ordering, and unclassed semantics editor files.
|
||||
- `tool/analyze.sh` clean: `flutter-analyze.4A4P1A`; `git diff --check` clean. Fixture web release build succeeded using `tool/search_selection_probe_entry.dart`.
|
||||
- Full app browser fixture evidence: `/tmp/review/unfocused-paste-final/` and `/tmp/unfocused-paste-capture.json`. Uses in-process fixtures, synthetic events and private Chrome only. Synthetic paste validates routing/default-prevention; it does not claim trusted OS clipboard integration or native-device verification.
|
||||
|
||||
Harness limitation: importing full app widget dependencies into Flutter's Chrome test runner collides with SDK `host.dart.js` naming and hangs at loading. That attempt was interrupted and is not counted as passing. Browser bridge tests and a release-mode full app fixture avoid that test-server issue. No real chats or device clipboard were used. Work preserved for pipeline continuation; no commit, deployment or shared-service restart performed here.
|
||||
@@ -20,20 +20,26 @@ class _FakePaste {
|
||||
ChatPasteFiles? onFiles;
|
||||
ChatPasteCanAccept? canAccept;
|
||||
ChatPasteFailed? onError;
|
||||
ChatPasteText? onText;
|
||||
ChatPasteCanAcceptText? canAcceptText;
|
||||
int listens = 0;
|
||||
int stops = 0;
|
||||
|
||||
ChatClipboardPaste get source => ChatClipboardPaste(
|
||||
subscribe: (onFiles, canAccept, onError) {
|
||||
subscribe: (onFiles, canAccept, onError, onText, canAcceptText) {
|
||||
listens += 1;
|
||||
this.onFiles = onFiles;
|
||||
this.canAccept = canAccept;
|
||||
this.onError = onError;
|
||||
this.onText = onText;
|
||||
this.canAcceptText = canAcceptText;
|
||||
return () {
|
||||
stops += 1;
|
||||
this.onFiles = null;
|
||||
this.canAccept = null;
|
||||
this.onError = null;
|
||||
this.onText = null;
|
||||
this.canAcceptText = null;
|
||||
};
|
||||
},
|
||||
);
|
||||
@@ -82,10 +88,16 @@ void main() {
|
||||
Future<void> pumpWith(
|
||||
WidgetTester tester, {
|
||||
ChatClipboardPaste? paste,
|
||||
bool pasteTarget = true,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChatComposerBar(composer: composer, running: false, paste: paste),
|
||||
ChatComposerBar(
|
||||
composer: composer,
|
||||
running: false,
|
||||
paste: paste,
|
||||
pasteTarget: pasteTarget,
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
@@ -95,6 +107,7 @@ void main() {
|
||||
WidgetTester tester, {
|
||||
ChatClipboardPaste? paste,
|
||||
ChatDraftStore? drafts,
|
||||
bool pasteTarget = true,
|
||||
}) async {
|
||||
composer = ChatComposerController(
|
||||
gateway,
|
||||
@@ -103,7 +116,7 @@ void main() {
|
||||
newOperationId: () => 'op/1',
|
||||
);
|
||||
controllers.add(composer);
|
||||
await pumpWith(tester, paste: paste);
|
||||
await pumpWith(tester, paste: paste, pasteTarget: pasteTarget);
|
||||
}
|
||||
|
||||
Future<void> focusField(WidgetTester tester) async {
|
||||
@@ -116,7 +129,6 @@ void main() {
|
||||
) async {
|
||||
final fake = _FakePaste();
|
||||
await pumpBar(tester, paste: fake.source);
|
||||
await focusField(tester);
|
||||
|
||||
fake.paste([
|
||||
_file('shot.png', [1, 2, 3], mime: 'image/png'),
|
||||
@@ -261,20 +273,43 @@ void main() {
|
||||
expect(drafts.entries, {'s': 'hello there world'});
|
||||
});
|
||||
|
||||
testWidgets('paste is only taken while this composer owns the field', (
|
||||
testWidgets('unfocused text paste is inserted at the composer caret', (
|
||||
tester,
|
||||
) async {
|
||||
final fake = _FakePaste();
|
||||
await pumpBar(tester, paste: fake.source);
|
||||
await tester.enterText(_field, 'hello');
|
||||
await tester.pumpAndSettle();
|
||||
tester.binding.focusManager.primaryFocus?.unfocus();
|
||||
await tester.pump();
|
||||
|
||||
expect(fake.canAcceptText!(), isTrue);
|
||||
fake.onText!(' world');
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(composer.draft, 'hello world');
|
||||
expect(find.text('hello world'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('text paste is not accepted by an inactive pane', (tester) async {
|
||||
final fake = _FakePaste();
|
||||
await pumpBar(tester, paste: fake.source, pasteTarget: false);
|
||||
expect(fake.canAcceptText!(), isFalse);
|
||||
});
|
||||
|
||||
testWidgets('paste is only taken by the active composer', (
|
||||
tester,
|
||||
) async {
|
||||
final fake = _FakePaste();
|
||||
await pumpBar(tester, paste: fake.source);
|
||||
|
||||
expect(fake.canAccept!(), isTrue);
|
||||
await pumpWith(tester, paste: fake.source, pasteTarget: false);
|
||||
expect(fake.canAccept!(), isFalse);
|
||||
await pumpWith(tester, paste: fake.source, pasteTarget: true);
|
||||
|
||||
await focusField(tester);
|
||||
expect(fake.canAccept!(), isTrue);
|
||||
|
||||
tester.binding.focusManager.primaryFocus?.unfocus();
|
||||
await tester.pump();
|
||||
expect(fake.canAccept!(), isFalse);
|
||||
});
|
||||
|
||||
testWidgets('a paste during an in-flight prompt adds nothing', (
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_clipboard_paste.dart';
|
||||
import 'chat_composer_bar_fixtures.dart';
|
||||
|
||||
Finder _field(String id) => find.descendant(
|
||||
of: find.byKey(ValueKey('bar-$id')),
|
||||
matching: find.byKey(const Key('chat-composer-field')),
|
||||
);
|
||||
|
||||
void main() {
|
||||
late ComposerBarGateway gateway;
|
||||
late ChatComposerController active, inactive;
|
||||
var reads = 0;
|
||||
setUp(() {
|
||||
gateway = ComposerBarGateway();
|
||||
active = ChatComposerController(
|
||||
gateway,
|
||||
'active',
|
||||
drafts: MemoryChatDraftStore(),
|
||||
);
|
||||
inactive = ChatComposerController(
|
||||
gateway,
|
||||
'inactive',
|
||||
drafts: MemoryChatDraftStore(),
|
||||
);
|
||||
reads = 0;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
|
||||
if (call.method == 'Clipboard.getData') {
|
||||
reads++;
|
||||
return {'text': 'controlled paste'};
|
||||
}
|
||||
if (call.method == 'Clipboard.hasStrings') return {'value': true};
|
||||
return null;
|
||||
});
|
||||
});
|
||||
tearDown(() {
|
||||
active.dispose();
|
||||
inactive.dispose();
|
||||
gateway.close();
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, null);
|
||||
});
|
||||
Future<void> mount(WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const TextField(key: Key('other-editor')),
|
||||
ChatComposerBar(
|
||||
key: const ValueKey('bar-inactive'),
|
||||
composer: inactive,
|
||||
running: false,
|
||||
pasteTarget: false,
|
||||
),
|
||||
ChatComposerBar(
|
||||
key: const ValueKey('bar-active'),
|
||||
composer: active,
|
||||
running: false,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<void> paste(WidgetTester tester, {bool meta = false}) async {
|
||||
final modifier = meta
|
||||
? LogicalKeyboardKey.metaLeft
|
||||
: LogicalKeyboardKey.controlLeft;
|
||||
await tester.sendKeyDownEvent(modifier);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.keyV);
|
||||
await tester.sendKeyUpEvent(modifier);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<void> done(WidgetTester tester) => tester.pumpWidget(const SizedBox());
|
||||
|
||||
for (final meta in [false, true]) {
|
||||
testWidgets(
|
||||
'unfocused active composer takes one controlled native ${meta ? 'Cmd' : 'Ctrl'}+V',
|
||||
(tester) async {
|
||||
await mount(tester);
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
await tester.pump();
|
||||
await paste(tester, meta: meta);
|
||||
expect(active.draft, 'controlled paste');
|
||||
expect(inactive.draft, isEmpty);
|
||||
expect(reads, 1);
|
||||
await done(tester);
|
||||
},
|
||||
);
|
||||
}
|
||||
testWidgets('another focused field keeps native paste', (tester) async {
|
||||
await mount(tester);
|
||||
await tester.showKeyboard(find.byKey(const Key('other-editor')));
|
||||
await paste(tester);
|
||||
final editor = tester.widget<EditableText>(
|
||||
find.descendant(
|
||||
of: find.byKey(const Key('other-editor')),
|
||||
matching: find.byType(EditableText),
|
||||
),
|
||||
);
|
||||
expect(editor.controller.text, 'controlled paste');
|
||||
expect(active.draft, isEmpty);
|
||||
expect(inactive.draft, isEmpty);
|
||||
expect(reads, 1);
|
||||
await done(tester);
|
||||
});
|
||||
testWidgets(
|
||||
'focused active composer retains its own native path exactly once',
|
||||
(tester) async {
|
||||
await mount(tester);
|
||||
await tester.showKeyboard(_field('active'));
|
||||
await paste(tester);
|
||||
expect(active.draft, 'controlled paste');
|
||||
expect(reads, 1);
|
||||
await done(tester);
|
||||
},
|
||||
);
|
||||
testWidgets('inactive focused composer cannot swallow active-pane paste', (
|
||||
tester,
|
||||
) async {
|
||||
await mount(tester);
|
||||
await tester.showKeyboard(_field('inactive'));
|
||||
await paste(tester);
|
||||
expect(active.draft, 'controlled paste');
|
||||
expect(inactive.draft, isEmpty);
|
||||
expect(reads, 1);
|
||||
await done(tester);
|
||||
});
|
||||
testWidgets('file/text acceptance excludes another Flutter editor', (
|
||||
tester,
|
||||
) async {
|
||||
ChatPasteCanAccept? files;
|
||||
ChatPasteCanAcceptText? text;
|
||||
final source = ChatClipboardPaste(
|
||||
subscribe: (onFiles, canAccept, onError, onText, canAcceptText) {
|
||||
files = canAccept;
|
||||
text = canAcceptText;
|
||||
return () {};
|
||||
},
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
Column(
|
||||
children: [
|
||||
const TextField(key: Key('other-editor')),
|
||||
ChatComposerBar(composer: active, running: false, paste: source),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.showKeyboard(find.byKey(const Key('other-editor')));
|
||||
expect(files!(), isFalse);
|
||||
expect(text!(), isFalse);
|
||||
await done(tester);
|
||||
});
|
||||
}
|
||||
@@ -27,7 +27,7 @@ void main() {
|
||||
var listens = 0;
|
||||
var stops = 0;
|
||||
final paste = ChatClipboardPaste(
|
||||
subscribe: (onFiles, canAccept, onError) {
|
||||
subscribe: (onFiles, canAccept, onError, onText, canAcceptText) {
|
||||
listens += 1;
|
||||
return () => stops += 1;
|
||||
},
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
@TestOn('browser')
|
||||
library;
|
||||
|
||||
import 'dart:js_interop';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_attachment_picker.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_clipboard_paste.dart';
|
||||
|
||||
@JS('Function')
|
||||
external JSFunction _function(JSString body);
|
||||
JSAny? _js(String body) => _function(body.toJS).callAsFunction(null);
|
||||
|
||||
bool _paste(String target, {String? filename}) =>
|
||||
(_js('''
|
||||
const target = $target;
|
||||
const data = new DataTransfer();
|
||||
${filename != null ? "data.items.add(new File([new Uint8Array([104,105])], '$filename', {type:'${filename.endsWith('.png') ? 'image/png' : 'text/plain'}'}));" : "data.setData('text/plain', 'browser text');"}
|
||||
const event = new ClipboardEvent('paste', {clipboardData:data, bubbles:true, composed:true, cancelable:true});
|
||||
target.dispatchEvent(event);
|
||||
return event.defaultPrevented;
|
||||
''')
|
||||
as JSBoolean)
|
||||
.toDart;
|
||||
|
||||
void main() {
|
||||
late List<ChatPickedFile> files;
|
||||
late List<String> texts;
|
||||
late List<Object> errors;
|
||||
late ChatPasteUnsubscribe stop;
|
||||
var accepts = true, acceptsText = true;
|
||||
setUp(() {
|
||||
files = [];
|
||||
texts = [];
|
||||
errors = [];
|
||||
accepts = true;
|
||||
acceptsText = true;
|
||||
stop = hostChatClipboardPaste.listen(
|
||||
onFiles: files.addAll,
|
||||
canAccept: () => accepts,
|
||||
onError: errors.add,
|
||||
onText: texts.add,
|
||||
canAcceptText: () => acceptsText,
|
||||
);
|
||||
});
|
||||
tearDown(() {
|
||||
stop();
|
||||
_js("document.getElementById('paste-test-host')?.remove();");
|
||||
});
|
||||
void editingElement({
|
||||
bool flutter = false,
|
||||
bool shadow = false,
|
||||
bool closed = false,
|
||||
}) {
|
||||
_js('''
|
||||
const host = document.createElement('${shadow ? 'paste-test-editor' : 'div'}'); host.id='paste-test-host'; host.tabIndex=0;
|
||||
const input = document.createElement('textarea');
|
||||
${flutter ? "input.className='flt-text-editing';" : ''}
|
||||
const root = ${shadow ? "host.attachShadow({mode:'${closed ? 'closed' : 'open'}'})" : 'host'};
|
||||
root.append(input); document.body.append(host); input.focus();
|
||||
globalThis.pasteTestTarget=input;
|
||||
''');
|
||||
}
|
||||
|
||||
Future<void> filesRead() async {
|
||||
for (var i = 0; i < 50 && files.isEmpty && errors.isEmpty; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
}
|
||||
}
|
||||
|
||||
test(
|
||||
'production bridge consumes unfocused text and clipboard files/images',
|
||||
() async {
|
||||
expect(_paste('document.body'), isTrue);
|
||||
expect(texts, ['browser text']);
|
||||
expect(_paste('document.body', filename: 'clipboard.txt'), isTrue);
|
||||
await filesRead();
|
||||
expect(files.single.name, 'clipboard.txt');
|
||||
expect(files.single.bytes, [104, 105]);
|
||||
files.clear();
|
||||
expect(_paste('document.body', filename: 'clipboard.png'), isTrue);
|
||||
await filesRead();
|
||||
expect(files.single.mime, 'image/png');
|
||||
expect(errors, isEmpty);
|
||||
},
|
||||
);
|
||||
test(
|
||||
'semantics-owned unclassed editor preserves native text and accepts files',
|
||||
() async {
|
||||
_js(
|
||||
"const host=document.createElement('flt-semantics');host.id='paste-test-host';const input=document.createElement('textarea');host.append(input);document.body.append(host);input.focus();globalThis.pasteTestTarget=input;",
|
||||
);
|
||||
acceptsText = false;
|
||||
expect(_paste('globalThis.pasteTestTarget'), isFalse);
|
||||
expect(
|
||||
_paste('globalThis.pasteTestTarget', filename: 'clipboard.txt'),
|
||||
isTrue,
|
||||
);
|
||||
await filesRead();
|
||||
expect(files.single.name, 'clipboard.txt');
|
||||
accepts = false;
|
||||
expect(
|
||||
_paste('globalThis.pasteTestTarget', filename: 'clipboard.txt'),
|
||||
isFalse,
|
||||
);
|
||||
},
|
||||
);
|
||||
test(
|
||||
'external DOM and open-shadow editors keep both text and files',
|
||||
() async {
|
||||
for (final shadow in [false, true]) {
|
||||
editingElement(shadow: shadow);
|
||||
expect(_paste('globalThis.pasteTestTarget'), isFalse);
|
||||
expect(
|
||||
_paste('globalThis.pasteTestTarget', filename: 'clipboard.png'),
|
||||
isFalse,
|
||||
);
|
||||
_js("document.getElementById('paste-test-host').remove();");
|
||||
}
|
||||
expect(texts, isEmpty);
|
||||
expect(files, isEmpty);
|
||||
},
|
||||
);
|
||||
test('closed external shadow editor is conservatively left native', () {
|
||||
editingElement(shadow: true, closed: true);
|
||||
expect(_paste('globalThis.pasteTestTarget'), isFalse);
|
||||
expect(texts, isEmpty);
|
||||
});
|
||||
test(
|
||||
'Flutter focus eligibility rejects unrelated editor sharing engine class',
|
||||
() {
|
||||
accepts = false;
|
||||
acceptsText = false;
|
||||
editingElement(flutter: true, shadow: true);
|
||||
expect(_paste('globalThis.pasteTestTarget'), isFalse);
|
||||
expect(
|
||||
_paste('globalThis.pasteTestTarget', filename: 'clipboard.png'),
|
||||
isFalse,
|
||||
);
|
||||
expect(texts, isEmpty);
|
||||
expect(files, isEmpty);
|
||||
},
|
||||
);
|
||||
test('inactive Flutter editing target is consumed before target listeners', () {
|
||||
editingElement(flutter: true, shadow: true);
|
||||
_js(
|
||||
"globalThis.pasteAtTarget=null; pasteTestTarget.addEventListener('paste',e=>globalThis.pasteAtTarget=e.defaultPrevented);",
|
||||
);
|
||||
expect(_paste('globalThis.pasteTestTarget'), isTrue);
|
||||
expect(texts, ['browser text']);
|
||||
expect(
|
||||
(_js('return globalThis.pasteAtTarget;') as JSBoolean).toDart,
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
test(
|
||||
'focused composer native text path is untouched while file path remains available',
|
||||
() async {
|
||||
acceptsText = false;
|
||||
editingElement(flutter: true, shadow: true);
|
||||
expect(_paste('globalThis.pasteTestTarget'), isFalse);
|
||||
expect(texts, isEmpty);
|
||||
expect(
|
||||
_paste('globalThis.pasteTestTarget', filename: 'clipboard.txt'),
|
||||
isTrue,
|
||||
);
|
||||
await filesRead();
|
||||
expect(files.single.name, 'clipboard.txt');
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user