share_to_file_page.dart (12183B)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | import 'dart:io'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:image/image.dart' as img; import 'package:creekui/services/file_service.dart'; import 'package:creekui/services/project_service.dart'; import 'package:creekui/data/models/file_model.dart'; import 'package:creekui/data/models/project_model.dart'; import 'package:creekui/ui/styles/variables.dart'; import 'package:creekui/ui/widgets/search_bar.dart'; import 'package:creekui/ui/widgets/file_card.dart'; import 'package:creekui/ui/widgets/section_header.dart'; import 'package:creekui/ui/widgets/empty_state.dart'; import 'package:creekui/ui/widgets/app_bar.dart'; import 'create_file_page.dart'; import 'canvas_page.dart'; class ShareToFilePage extends StatefulWidget { final File sharedImage; const ShareToFilePage({super.key, required this.sharedImage}); @override State<ShareToFilePage> createState() => _ShareToFilePageState(); } class _ShareToFilePageState extends State<ShareToFilePage> { final FileService _fileService = FileService(); final ProjectService _projectService = ProjectService(); final TextEditingController _searchController = TextEditingController(); List<FileModel> _allFiles = []; List<FileModel> _filteredFiles = []; List<FileModel> _recentFiles = []; // file.id -> { 'preview': path, 'dimensions': str } Map<String, Map<String, String>> _fileMetadata = {}; // Avoid repeated fetches final Map<int, ProjectModel> _projectCache = {}; bool _isLoading = true; String _searchQuery = ""; @override void initState() { super.initState(); _fetchFiles(); } @override void dispose() { _searchController.dispose(); super.dispose(); } Future<void> _fetchFiles() async { setState(() => _isLoading = true); try { final List<FileModel> files = await _fileService.getAllFiles(); final List<FileModel> recent = await _fileService.getRecentFiles( limit: 10, ); // Sort by lastUpdated descending files.sort((a, b) => b.lastUpdated.compareTo(a.lastUpdated)); recent.sort((a, b) => b.lastUpdated.compareTo(a.lastUpdated)); _allFiles = files; _filteredFiles = List.from(files); _recentFiles = recent.take(3).toList(); await _loadFileMetadata(files); setState(() => _isLoading = false); } catch (e) { debugPrint('Error fetching files in ShareToFilePage: $e'); setState(() => _isLoading = false); } } Future<void> _loadFileMetadata(List<FileModel> files) async { final Map<String, Map<String, String>> meta = {}; for (final fmodel in files) { final info = await _fileService.getFileMetadata(fmodel.filePath); meta[fmodel.id] = { 'preview': info.previewPath ?? '', 'dimensions': info.dimensions, }; } _fileMetadata = meta; } void _filterFiles(String query) { setState(() { _searchQuery = query; if (query.trim().isEmpty) { _filteredFiles = List.from(_allFiles); } else { final q = query.toLowerCase(); _filteredFiles = _allFiles.where((file) { final nameMatch = file.name.toLowerCase().contains(q); final breadcrumb = _getProjectBreadcrumbSync(file).toLowerCase(); final projectMatch = breadcrumb.contains(q); return nameMatch || projectMatch; }).toList(); } }); } // Synchronous breadcrumb using cached project (returns empty if not cached) String _getProjectBreadcrumbSync(FileModel file) { final proj = _projectCache[file.projectId]; if (proj == null) return ''; if (proj.parentId != null) { final parent = _projectCache[proj.parentId!]; if (parent != null) return '${parent.title} / ${proj.title}'; } return proj.title; } // Async breadcrumb loader that fetches projects into cache as needed Future<String> _getProjectEventLabel(FileModel file) async { if (!_projectCache.containsKey(file.projectId)) { try { final p = await _projectService.getProjectById(file.projectId); if (p != null) _projectCache[file.projectId] = p; } catch (e) { debugPrint('Project load failed for ${file.projectId}: $e'); } } final project = _projectCache[file.projectId]; if (project == null) return "Unknown"; if (project.parentId == null) { return project.title; } final parentId = project.parentId!; if (!_projectCache.containsKey(parentId)) { try { final parent = await _projectService.getProjectById(parentId); if (parent != null) _projectCache[parentId] = parent; } catch (e) { debugPrint('Parent project load failed for $parentId: $e'); } } final parentProject = _projectCache[parentId]; if (parentProject == null) return project.title; return "${parentProject.title} / ${project.title}"; } void _onAddPressed() { Navigator.push( context, MaterialPageRoute( builder: (_) => CreateFilePage(file: widget.sharedImage), ), ); } void _onFileSelected(FileModel file) async { try { final f = File(file.filePath); if (!await f.exists()) { ScaffoldMessenger.of( context, ).showSnackBar(const SnackBar(content: Text("File not found"))); return; } // Default values double width = 1080; double height = 1080; // File Metadata final meta = await _fileService.getFileMetadata(file.filePath); if (meta.width > 0 && meta.height > 0) { width = meta.width; height = meta.height; } Navigator.push( context, MaterialPageRoute( builder: (_) => CanvasPage( projectId: file.projectId, width: width, height: height, existingFile: file, injectedMedia: widget.sharedImage, ), ), ); } catch (e) { debugPrint("Error opening file: $e"); } } String _formatDate(DateTime date) { final diff = DateTime.now().difference(date); if (diff.inDays == 0) return 'Today'; if (diff.inDays == 1) return 'Yesterday'; if (diff.inDays < 7) return '${diff.inDays} days ago'; return '${date.day}/${date.month}/${date.year}'; } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Variables.surfaceBackground, appBar: CommonAppBar( title: 'Files', leading: IconButton( icon: const Icon(Icons.arrow_back, color: Variables.textPrimary), onPressed: () => Navigator.pop(context), ), actions: [ IconButton( icon: const Icon(Icons.add, color: Variables.textPrimary, size: 28), onPressed: _onAddPressed, tooltip: "Create New File", ), ], ), body: _isLoading ? const Center( child: CircularProgressIndicator(color: Variables.textPrimary), ) : _allFiles.isEmpty ? _buildEmptyState() : Column( children: [ // Search bar Padding( padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), child: CommonSearchBar( controller: _searchController, onChanged: _filterFiles, ), ), Expanded( child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (_filteredFiles.isEmpty && _searchQuery.isNotEmpty) const Padding( padding: EdgeInsets.all(32.0), child: EmptyState( icon: Icons.search_off, title: "No results found", subtitle: "Try adjusting your search", ), ), // Recent Files if (_recentFiles.isNotEmpty && _searchQuery.isEmpty) ...[ const Padding( padding: EdgeInsets.symmetric(horizontal: 16), child: SectionHeader(title: "Recent Files"), ), const SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric( horizontal: 16, ), child: Column( children: _recentFiles .map((file) => _buildFileCard(file)) .toList(), ), ), const SizedBox(height: 24), ], // All files header if (_filteredFiles.isNotEmpty) ...[ Padding( padding: const EdgeInsets.symmetric( horizontal: 16, ), child: SectionHeader( title: _searchQuery.isEmpty ? "All Files" : "Search Results", ), ), const SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric( horizontal: 16, ), child: ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: _filteredFiles.length, itemBuilder: (context, index) => _buildFileCard(_filteredFiles[index]), ), ), ], const SizedBox(height: 40), ], ), ), ), ], ), ); } Widget _buildEmptyState() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon(Icons.folder_open, size: 80, color: Colors.grey), const SizedBox(height: 16), const Text( "No files yet", style: TextStyle(color: Colors.grey, fontSize: 16), ), const SizedBox(height: 8), TextButton( onPressed: _onAddPressed, child: const Text("Create your first file"), ), ], ), ); } Widget _buildFileCard(FileModel file) { final meta = _fileMetadata[file.id] ?? {}; final preview = meta['preview'] ?? ''; final dimensions = meta['dimensions'] ?? 'Unknown'; return FutureBuilder<String>( future: _getProjectEventLabel(file), builder: (context, snapshot) { return Padding( padding: const EdgeInsets.only(bottom: 12), child: FileCard( file: file, breadcrumb: snapshot.data ?? "", dimensions: dimensions, previewPath: preview, timeAgo: _formatDate(file.lastUpdated), onTap: () => _onFileSelected(file), onMenuAction: null, ), ); }, ); } } |