import 'dart:async'; import 'dart:js_interop'; import 'dart:js_interop_unsafe'; import 'package:web/web.dart' as web; import 'insecure_clipboard.dart'; InsecureClipboardHost? insecureClipboardHost() => _BrowserClipboard(); /// The legacy clipboard of a page without the Clipboard API. class _BrowserClipboard implements InsecureClipboardHost { /// `navigator.clipboard` exists only in a secure context (and a browser /// new enough to have it); neither changes while the page is open. @override late final bool unavailable = !web.window.isSecureContext || (web.window.navigator as JSObject) .getProperty('clipboard'.toJS) .isUndefinedOrNull; /// The copy command writes what its `copy` event puts on the event's /// clipboard data, so no element is focused or selected for it: the /// Flutter text field keeps its focus, caret and any IME composition, and /// a selection in it is not copied instead. @override bool copy(String text) { var written = false; void onCopy(web.Event event) { final data = (event as web.ClipboardEvent).clipboardData; if (data == null) return; data.setData('text/plain', text); event.preventDefault(); event.stopImmediatePropagation(); written = true; } final listener = onCopy.toJS; web.window.addEventListener( 'copy', listener, web.AddEventListenerOptions(capture: true), ); try { // False (or no copy event) without a user activation. return web.document.execCommand('copy') && written; } on Object { return false; } finally { web.window.removeEventListener( 'copy', listener, web.EventListenerOptions(capture: true), ); } } /// Listens on the window in the capture phase, ahead of the composer's /// document listener and the focused element's own insertion. @override Future nextPaste(Duration timeout) { final result = Completer(); late final JSFunction listener; Timer? timer; void finish(String? text) { if (result.isCompleted) return; timer?.cancel(); web.window.removeEventListener( 'paste', listener, web.EventListenerOptions(capture: true), ); result.complete(text); } void onPaste(web.Event event) { final data = (event as web.ClipboardEvent).clipboardData; final text = data?.getData('text/plain') ?? ''; if (text.isNotEmpty) { event.preventDefault(); event.stopImmediatePropagation(); } // A paste with no text (files) is left to the page's other listeners. finish(text); } listener = onPaste.toJS; web.window.addEventListener( 'paste', listener, web.AddEventListenerOptions(capture: true), ); timer = Timer(timeout, () => finish(null)); return result.future; } }