attachment_picker.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import 'dart:io';
  2. import 'package:flutter/material.dart';
  3. import 'package:image_picker/image_picker.dart';
  4. import 'package:file_picker/file_picker.dart';
  5. import 'package:tdesign_flutter/tdesign_flutter.dart';
  6. import '../models/attachment_file.dart';
  7. import '../../core/i18n/app_localizations.dart';
  8. import '../../core/theme/app_colors.dart';
  9. import '../../core/theme/app_colors_extension.dart';
  10. // ═══════════════════════════════════════════════════════════════
  11. // Controller
  12. // ═══════════════════════════════════════════════════════════════
  13. class AttachmentPickerController extends ChangeNotifier {
  14. final int maxCount;
  15. final List<AttachmentFile> _files = [];
  16. List<AttachmentFile> get files => List.unmodifiable(_files);
  17. int get count => _files.length;
  18. bool get isFull => _files.length >= maxCount;
  19. AttachmentPickerController({
  20. this.maxCount = 9,
  21. List<AttachmentFile>? initialFiles,
  22. }) {
  23. if (initialFiles != null) {
  24. _files.addAll(initialFiles.take(maxCount));
  25. }
  26. }
  27. void addFile(AttachmentFile file) {
  28. if (_files.length >= maxCount) return;
  29. _files.add(file);
  30. notifyListeners();
  31. }
  32. void addFiles(List<AttachmentFile> files) {
  33. for (final f in files) {
  34. if (_files.length >= maxCount) break;
  35. _files.add(f);
  36. }
  37. notifyListeners();
  38. }
  39. void removeFile(int index) {
  40. if (index < 0 || index >= _files.length) return;
  41. _files.removeAt(index);
  42. notifyListeners();
  43. }
  44. void clear() {
  45. if (_files.isEmpty) return;
  46. _files.clear();
  47. notifyListeners();
  48. }
  49. /// 从路径列表恢复(草稿兼容)
  50. Future<void> restoreFromPaths(List<String> paths) async {
  51. _files.clear();
  52. for (final path in paths.take(maxCount)) {
  53. _files.add(await AttachmentFile.fromPath(path));
  54. }
  55. notifyListeners();
  56. }
  57. /// 导出为路径列表(草稿持久化)
  58. List<String> toPathList() => _files.map((f) => f.path).toList();
  59. }
  60. // ═══════════════════════════════════════════════════════════════
  61. // Widget
  62. // ═══════════════════════════════════════════════════════════════
  63. class AttachmentPicker extends StatefulWidget {
  64. final AttachmentPickerController controller;
  65. /// 图片大小上限(MB),null 不限制
  66. final double? maxImageSizeMB;
  67. /// 文件大小上限(MB),null 不限制
  68. final double? maxFileSizeMB;
  69. /// 允许的文件扩展名,null 使用默认 pdf/doc/docx/xls/xlsx/ppt/pptx/txt
  70. final List<String>? allowedExtensions;
  71. /// 文件被拒时回调
  72. final void Function(AttachmentFile file, String reason)? onFileRejected;
  73. /// 缩略图尺寸
  74. final double thumbnailSize;
  75. const AttachmentPicker({
  76. super.key,
  77. required this.controller,
  78. this.maxImageSizeMB,
  79. this.maxFileSizeMB,
  80. this.allowedExtensions,
  81. this.onFileRejected,
  82. this.thumbnailSize = 80,
  83. });
  84. @override
  85. State<AttachmentPicker> createState() => _AttachmentPickerState();
  86. }
  87. class _AttachmentPickerState extends State<AttachmentPicker> {
  88. List<AttachmentFile> get _files => widget.controller.files;
  89. @override
  90. void initState() {
  91. super.initState();
  92. widget.controller.addListener(_onChanged);
  93. }
  94. @override
  95. void dispose() {
  96. widget.controller.removeListener(_onChanged);
  97. super.dispose();
  98. }
  99. void _onChanged() {
  100. if (mounted) setState(() {});
  101. }
  102. // ── 选择入口 ──
  103. Future<void> _showPicker() async {
  104. _unfocus();
  105. final l10n = AppLocalizations.of(context);
  106. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  107. final choice = await showModalBottomSheet<String>(
  108. context: context,
  109. backgroundColor: colors.bgCard,
  110. shape: const RoundedRectangleBorder(
  111. borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
  112. ),
  113. builder: (ctx) => SafeArea(
  114. child: Padding(
  115. padding: const EdgeInsets.fromLTRB(0, 8, 0, 20),
  116. child: Column(
  117. mainAxisSize: MainAxisSize.min,
  118. children: [
  119. // 拖拽手柄
  120. Center(
  121. child: Container(
  122. width: 36,
  123. height: 4,
  124. margin: const EdgeInsets.only(bottom: 12),
  125. decoration: BoxDecoration(
  126. color: colors.border,
  127. borderRadius: BorderRadius.circular(2),
  128. ),
  129. ),
  130. ),
  131. // 选择图片
  132. InkWell(
  133. onTap: () => Navigator.pop(ctx, 'image'),
  134. child: Padding(
  135. padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
  136. child: Row(
  137. children: [
  138. Container(
  139. width: 44,
  140. height: 44,
  141. decoration: BoxDecoration(
  142. color: colors.primaryLight,
  143. borderRadius: BorderRadius.circular(12),
  144. ),
  145. child: Icon(Icons.image_outlined, color: colors.primary, size: 24),
  146. ),
  147. const SizedBox(width: 16),
  148. Text(
  149. l10n.get('pickImage'),
  150. style: TextStyle(fontSize: 16, color: colors.textPrimary),
  151. ),
  152. ],
  153. ),
  154. ),
  155. ),
  156. const Divider(height: 1, indent: 76),
  157. // 选择文件
  158. InkWell(
  159. onTap: () => Navigator.pop(ctx, 'file'),
  160. child: Padding(
  161. padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
  162. child: Row(
  163. children: [
  164. Container(
  165. width: 44,
  166. height: 44,
  167. decoration: BoxDecoration(
  168. color: colors.primaryLight,
  169. borderRadius: BorderRadius.circular(12),
  170. ),
  171. child: Icon(Icons.description_outlined, color: colors.primary, size: 24),
  172. ),
  173. const SizedBox(width: 16),
  174. Text(
  175. l10n.get('pickFile'),
  176. style: TextStyle(fontSize: 16, color: colors.textPrimary),
  177. ),
  178. ],
  179. ),
  180. ),
  181. ),
  182. ],
  183. ),
  184. ),
  185. ),
  186. );
  187. if (!mounted || choice == null) return;
  188. if (choice == 'image') {
  189. await _pickImages();
  190. } else {
  191. await _pickDocuments();
  192. }
  193. }
  194. Future<void> _pickImages() async {
  195. final available = widget.controller.maxCount - widget.controller.count;
  196. if (available <= 0) return;
  197. final picker = ImagePicker();
  198. final images = await picker.pickMultiImage(limit: available);
  199. if (!mounted || images.isEmpty) return;
  200. for (final img in images) {
  201. if (widget.controller.isFull) break;
  202. final file = await AttachmentFile.fromXFile(img);
  203. if (_checkOversized(file)) continue;
  204. widget.controller.addFile(file);
  205. }
  206. }
  207. Future<void> _pickDocuments() async {
  208. final available = widget.controller.maxCount - widget.controller.count;
  209. if (available <= 0) return;
  210. final result = await FilePicker.pickFiles(
  211. type: FileType.custom,
  212. allowedExtensions: widget.allowedExtensions ??
  213. const ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'],
  214. allowMultiple: true,
  215. );
  216. if (!mounted || result == null || result.files.isEmpty) return;
  217. for (final pf in result.files) {
  218. if (widget.controller.isFull) break;
  219. if (pf.path == null) continue;
  220. final file = AttachmentFile.fromPlatformFile(pf);
  221. if (_checkOversized(file)) continue;
  222. widget.controller.addFile(file);
  223. }
  224. }
  225. /// 返回 true 表示文件超过大小限制
  226. bool _checkOversized(AttachmentFile file) {
  227. final l10n = AppLocalizations.of(context);
  228. final sizeMB = file.sizeMB;
  229. if (file.isImage && widget.maxImageSizeMB != null && sizeMB > widget.maxImageSizeMB!) {
  230. final reason = l10n.getString('imageSizeLimit', args: {'max': widget.maxImageSizeMB!.toStringAsFixed(0)});
  231. widget.onFileRejected?.call(file, reason);
  232. if (mounted) TDToast.showText(reason, context: context);
  233. return true;
  234. }
  235. if (!file.isImage && widget.maxFileSizeMB != null && sizeMB > widget.maxFileSizeMB!) {
  236. final reason = l10n.getString('fileSizeLimit', args: {'max': widget.maxFileSizeMB!.toStringAsFixed(0)});
  237. widget.onFileRejected?.call(file, reason);
  238. if (mounted) TDToast.showText(reason, context: context);
  239. return true;
  240. }
  241. return false;
  242. }
  243. void _unfocus() => FocusScope.of(context).unfocus();
  244. // ── UI ──
  245. @override
  246. Widget build(BuildContext context) {
  247. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  248. return Column(
  249. crossAxisAlignment: CrossAxisAlignment.start,
  250. children: [
  251. Wrap(
  252. spacing: 8,
  253. runSpacing: 8,
  254. children: [
  255. ..._files.asMap().entries.map(
  256. (e) => Stack(
  257. clipBehavior: Clip.none,
  258. children: [
  259. _buildThumbnail(e.value),
  260. Positioned(
  261. right: -4,
  262. top: -4,
  263. child: GestureDetector(
  264. onTap: () => widget.controller.removeFile(e.key),
  265. child: Container(
  266. width: 20,
  267. height: 20,
  268. decoration: BoxDecoration(
  269. color: colors.danger,
  270. shape: BoxShape.circle,
  271. ),
  272. child: const Icon(
  273. Icons.close,
  274. size: 12,
  275. color: Colors.white,
  276. ),
  277. ),
  278. ),
  279. ),
  280. ],
  281. ),
  282. ),
  283. if (!widget.controller.isFull)
  284. GestureDetector(
  285. onTap: () => _showPicker(),
  286. child: Container(
  287. width: widget.thumbnailSize,
  288. height: widget.thumbnailSize,
  289. decoration: BoxDecoration(
  290. color: colors.bgCard,
  291. borderRadius: BorderRadius.circular(4),
  292. border: Border.all(color: colors.border, width: 1),
  293. ),
  294. child: Center(
  295. child: Icon(
  296. Icons.add,
  297. size: 24,
  298. color: colors.textPlaceholder,
  299. ),
  300. ),
  301. ),
  302. ),
  303. ],
  304. ),
  305. ],
  306. );
  307. }
  308. Widget _buildThumbnail(AttachmentFile file) {
  309. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  310. final size = widget.thumbnailSize;
  311. if (file.isImage) {
  312. return Container(
  313. width: size,
  314. height: size,
  315. decoration: BoxDecoration(
  316. borderRadius: BorderRadius.circular(4),
  317. border: Border.all(color: colors.border, width: 0.5),
  318. ),
  319. child: ClipRRect(
  320. borderRadius: BorderRadius.circular(4),
  321. child: Image.file(
  322. File(file.path),
  323. width: size,
  324. height: size,
  325. fit: BoxFit.cover,
  326. errorBuilder: (_, _, _) => _buildDocTile(file, colors, size),
  327. ),
  328. ),
  329. );
  330. }
  331. return _buildDocTile(file, colors, size);
  332. }
  333. Widget _buildDocTile(AttachmentFile file, AppColorsExtension colors, double size) {
  334. return SizedBox(
  335. width: size,
  336. child: Column(
  337. mainAxisSize: MainAxisSize.min,
  338. children: [
  339. Container(
  340. width: size,
  341. height: size,
  342. decoration: BoxDecoration(
  343. color: colors.primaryLight,
  344. borderRadius: BorderRadius.circular(4),
  345. ),
  346. child: Center(
  347. child: Icon(
  348. _fileTypeIcon(file.extension),
  349. color: colors.primary,
  350. size: size * 0.4,
  351. ),
  352. ),
  353. ),
  354. const SizedBox(height: 4),
  355. SizedBox(
  356. width: size,
  357. height: 16,
  358. child: _MarqueeText(
  359. text: file.name,
  360. style: TextStyle(
  361. fontSize: AppFontSizes.caption,
  362. color: colors.textSecondary,
  363. ),
  364. ),
  365. ),
  366. ],
  367. ),
  368. );
  369. }
  370. IconData _fileTypeIcon(String ext) {
  371. switch (ext) {
  372. case 'pdf':
  373. return Icons.picture_as_pdf;
  374. case 'doc':
  375. case 'docx':
  376. return Icons.description;
  377. case 'xls':
  378. case 'xlsx':
  379. return Icons.table_chart;
  380. case 'ppt':
  381. case 'pptx':
  382. return Icons.slideshow;
  383. default:
  384. return Icons.insert_drive_file;
  385. }
  386. }
  387. }
  388. // ═══════════════════════════════════════════════════════════════
  389. // Marquee Text
  390. // ═══════════════════════════════════════════════════════════════
  391. class _MarqueeText extends StatefulWidget {
  392. final String text;
  393. final TextStyle style;
  394. const _MarqueeText({required this.text, required this.style});
  395. @override
  396. State<_MarqueeText> createState() => _MarqueeTextState();
  397. }
  398. class _MarqueeTextState extends State<_MarqueeText>
  399. with SingleTickerProviderStateMixin {
  400. late final AnimationController _controller;
  401. final ScrollController _scrollController = ScrollController();
  402. bool _needsScroll = false;
  403. @override
  404. void initState() {
  405. super.initState();
  406. _controller = AnimationController(
  407. vsync: this,
  408. duration: const Duration(milliseconds: 3000),
  409. );
  410. WidgetsBinding.instance.addPostFrameCallback(_measure);
  411. }
  412. void _measure(_) {
  413. if (!mounted || !_scrollController.hasClients) return;
  414. if (_scrollController.position.maxScrollExtent > 0) {
  415. setState(() => _needsScroll = true);
  416. _controller.addListener(_onScroll);
  417. _controller.repeat(reverse: true);
  418. }
  419. }
  420. void _onScroll() {
  421. if (!_scrollController.hasClients) return;
  422. final max = _scrollController.position.maxScrollExtent;
  423. if (max > 0) {
  424. _scrollController.jumpTo(_controller.value * max);
  425. }
  426. }
  427. @override
  428. void dispose() {
  429. _controller.dispose();
  430. _scrollController.dispose();
  431. super.dispose();
  432. }
  433. @override
  434. Widget build(BuildContext context) {
  435. return SingleChildScrollView(
  436. controller: _scrollController,
  437. scrollDirection: Axis.horizontal,
  438. physics: _needsScroll
  439. ? const NeverScrollableScrollPhysics()
  440. : const ClampingScrollPhysics(),
  441. child: Text(widget.text, style: widget.style, maxLines: 1),
  442. );
  443. }
  444. }