import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart' as flutter_services; /// Typed, per-content-kind clipboard with a plaintext fallback. /// /// Extensions write typed values (`write(hunk)`) and read in /// the same type (`readAs()`). Anything with a `toPlain` /// callback also syncs to the OS clipboard so external apps see /// reasonable text. The history ring keeps the last [historyLimit] /// entries per type for quick recall. class ClideClipboard { ClideClipboard({this.historyLimit = 16}); final int historyLimit; final Map> _history = {}; Future write( T value, { String Function(T)? toPlain, }) async { final bucket = _history.putIfAbsent(T, () => []); bucket.insert(0, value); if (bucket.length > historyLimit) bucket.removeLast(); if (toPlain != null) { await flutter_services.Clipboard.setData( flutter_services.ClipboardData(text: toPlain(value))); } } T? readAs() { final bucket = _history[T]; if (bucket == null || bucket.isEmpty) return null; return bucket.first as T; } List historyOf() { final bucket = _history[T]; if (bucket == null) return const []; return bucket.cast().toList(growable: false); } Future readPlain() async { final d = await flutter_services.Clipboard.getData('text/plain'); return d?.text; } Future writePlain(String text) async { await flutter_services.Clipboard.setData( flutter_services.ClipboardData(text: text)); final bucket = _history.putIfAbsent(String, () => []); bucket.insert(0, text); if (bucket.length > historyLimit) bucket.removeLast(); } @visibleForTesting void clear() => _history.clear(); }