creek

The AI Image Editor of 2030

project_selector.dart (16254B)


  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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:creekui/data/models/project_model.dart';
import 'package:creekui/data/repos/project_repo.dart';
import 'package:creekui/data/repos/image_repo.dart';
import 'package:creekui/ui/styles/variables.dart';
import 'package:creekui/ui/widgets/search_bar.dart';
import 'package:creekui/ui/widgets/section_header.dart';
import 'package:creekui/ui/widgets/empty_state.dart';

class ProjectItemViewModel {
  final ProjectModel item;
  final String? parentTitle;
  final String? coverPath;

  ProjectItemViewModel({required this.item, this.parentTitle, this.coverPath});

  String get title => item.title;
  bool get isEvent => item.isEvent;
  int get id => item.id!;
}

class ProjectGroup {
  final ProjectModel project;
  final List<ProjectItemViewModel> events;
  final String? coverPath;
  bool isExpanded;

  ProjectGroup({
    required this.project,
    this.events = const [],
    this.coverPath,
    this.isExpanded = false,
  });
}

class ProjectSelector extends StatefulWidget {
  final Function(int id, String title, String? parentTitle) onProjectSelected;
  final String searchHint;
  final ScrollController? scrollController;

  const ProjectSelector({
    super.key,
    required this.onProjectSelected,
    this.searchHint = "Search",
    this.scrollController,
  });

  @override
  State<ProjectSelector> createState() => _ProjectSelectorState();
}

class _ProjectSelectorState extends State<ProjectSelector> {
  final ProjectRepo _projectRepo = ProjectRepo();
  final ImageRepo _imageRepo = ImageRepo();

  final TextEditingController _searchController = TextEditingController();

  List<ProjectItemViewModel> _recentViewModels = [];
  List<ProjectGroup> _groupedProjects = [];
  List<ProjectGroup> _filteredGroupedProjects = [];

  bool _isLoading = true;
  String _searchQuery = "";

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  Future<String?> _getProjectCover(int projectId) async {
    try {
      final images = await _imageRepo.getImages(projectId);
      if (images.isNotEmpty) {
        return images.first.filePath;
      }
    } catch (e) {
      debugPrint("Error fetching cover for project $projectId: $e");
    }
    return null;
  }

  Future<void> _loadData() async {
    if (!mounted) return;
    setState(() => _isLoading = true);

    // 1. Fetch Raw Data
    final recentItems = await _projectRepo.getRecentProjectsAndEvents();
    final allProjects = await _projectRepo.getAllProjects();

    // 2. Build Recent View Models
    final List<ProjectItemViewModel> recents = [];
    for (var item in recentItems.take(3)) {
      String? parentTitle;
      if (item.parentId != null) {
        final parent = await _projectRepo.getProjectById(item.parentId!);
        parentTitle = parent?.title;
      }
      final cover = await _getProjectCover(item.id!);
      recents.add(
        ProjectItemViewModel(
          item: item,
          parentTitle: parentTitle,
          coverPath: cover,
        ),
      );
    }

    // 3. Build Grouped Projects
    final List<ProjectGroup> groups = [];
    for (final p in allProjects) {
      final rawEvents = await _projectRepo.getEvents(p.id!);
      final List<ProjectItemViewModel> eventVMs = [];
      for (final e in rawEvents) {
        final eCover = await _getProjectCover(e.id!);
        eventVMs.add(ProjectItemViewModel(item: e, coverPath: eCover));
      }
      final pCover = await _getProjectCover(p.id!);
      groups.add(ProjectGroup(project: p, events: eventVMs, coverPath: pCover));
    }

    if (mounted) {
      setState(() {
        _recentViewModels = recents;
        _groupedProjects = groups;
        _filterProjects(_searchQuery); // Re-apply filter if any
        _isLoading = false;
      });
    }
  }

  void _filterProjects(String query) {
    setState(() {
      _searchQuery = query;
      if (query.isEmpty) {
        _filteredGroupedProjects = _groupedProjects;
      } else {
        final q = query.toLowerCase();
        final List<ProjectGroup> filtered = [];
        for (final g in _groupedProjects) {
          final projectMatch = g.project.title.toLowerCase().contains(q);
          final matchingEvents =
              g.events.where((e) => e.title.toLowerCase().contains(q)).toList();

          if (projectMatch) {
            filtered.add(
              ProjectGroup(
                project: g.project,
                events: g.events,
                isExpanded: true,
                coverPath: g.coverPath,
              ),
            );
          } else if (matchingEvents.isNotEmpty) {
            filtered.add(
              ProjectGroup(
                project: g.project,
                events: matchingEvents,
                isExpanded: true,
                coverPath: g.coverPath,
              ),
            );
          }
        }
        _filteredGroupedProjects = filtered;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    return Column(
      children: [
        // Search Bar
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
          child: CommonSearchBar(
            controller: _searchController,
            onChanged: _filterProjects,
            hintText: widget.searchHint,
          ),
        ),
        Expanded(
          child: SingleChildScrollView(
            controller: widget.scrollController,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Empty State
                if (_filteredGroupedProjects.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",
                    ),
                  ),

                // Recents Section
                if (_searchQuery.isEmpty && _recentViewModels.isNotEmpty) ...[
                  const Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16),
                    child: SectionHeader(title: "Recent Projects/Events"),
                  ),
                  const SizedBox(height: 12),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Column(
                      children:
                          _recentViewModels
                              .map((vm) => _buildRecentItem(vm))
                              .toList(),
                    ),
                  ),
                  const SizedBox(height: 24),
                ],

                // All Projects Section
                if (_filteredGroupedProjects.isNotEmpty) ...[
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: SectionHeader(
                      title:
                          _searchQuery.isEmpty
                              ? "All Projects/Events"
                              : "Search Results",
                    ),
                  ),
                  const SizedBox(height: 12),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: _filteredGroupedProjects.length,
                      itemBuilder:
                          (context, index) => _buildProjectGroup(
                            _filteredGroupedProjects[index],
                          ),
                    ),
                  ),
                ],
                const SizedBox(height: 40),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildRecentItem(ProjectItemViewModel vm) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      child: InkWell(
        onTap: () => widget.onProjectSelected(vm.id, vm.title, vm.parentTitle),
        borderRadius: BorderRadius.circular(Variables.radiusMedium),
        child: Container(
          padding: const EdgeInsets.fromLTRB(4, 4, 0, 4),
          decoration: BoxDecoration(
            color: Variables.background,
            borderRadius: BorderRadius.circular(Variables.radiusMedium),
            border: Border.all(color: Variables.borderSubtle, width: 1),
          ),
          child: Row(
            children: [
              // Cover Image
              Container(
                width: 56,
                height: 56,
                decoration: BoxDecoration(
                  color: Variables.surfaceSubtle,
                  borderRadius: BorderRadius.circular(Variables.radiusSmall),
                  image:
                      vm.coverPath != null
                          ? DecorationImage(
                            image: FileImage(File(vm.coverPath!)),
                            fit: BoxFit.cover,
                          )
                          : null,
                ),
                child:
                    vm.coverPath == null
                        ? const Icon(
                          Icons.image,
                          color: Variables.textDisabled,
                          size: 28,
                        )
                        : null,
              ),
              const SizedBox(width: 12),
              // Text Content
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    if (vm.isEvent && vm.parentTitle != null)
                      Padding(
                        padding: const EdgeInsets.only(bottom: 2),
                        child: Text(
                          vm.parentTitle!,
                          style: Variables.captionStyle,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    Text(
                      vm.title,
                      style: Variables.bodyStyle.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildProjectGroup(ProjectGroup g) {
    final project = g.project;
    final hasEvents = g.events.isNotEmpty;

    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        color: Variables.background,
        borderRadius: BorderRadius.circular(Variables.radiusMedium),
        border: Border.all(color: Variables.borderSubtle),
      ),
      child: Column(
        children: [
          // Parent Project
          ListTile(
            onTap:
                () =>
                    hasEvents
                        ? setState(() => g.isExpanded = !g.isExpanded)
                        : widget.onProjectSelected(
                          project.id!,
                          project.title,
                          null,
                        ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 4,
            ),
            visualDensity: VisualDensity.compact,
            leading: Container(
              width: 48,
              height: 48,
              decoration: BoxDecoration(
                color: Variables.surfaceSubtle,
                borderRadius: BorderRadius.circular(Variables.radiusMedium),
                image:
                    g.coverPath != null
                        ? DecorationImage(
                          image: FileImage(File(g.coverPath!)),
                          fit: BoxFit.cover,
                        )
                        : null,
              ),
              child:
                  g.coverPath == null
                      ? const Icon(Icons.folder, color: Variables.textDisabled)
                      : null,
            ),
            title: Text(
              project.title,
              style: Variables.bodyStyle.copyWith(
                fontWeight: FontWeight.w600,
                fontSize: 16,
              ),
            ),
            trailing:
                hasEvents
                    ? IconButton(
                      icon: Icon(
                        g.isExpanded
                            ? Icons.keyboard_arrow_up
                            : Icons.keyboard_arrow_down,
                        color: Variables.textSecondary,
                      ),
                      onPressed: () {
                        setState(() => g.isExpanded = !g.isExpanded);
                      },
                    )
                    : null,
          ),

          // Children (Events)
          if (hasEvents)
            AnimatedCrossFade(
              firstChild: const SizedBox.shrink(),
              secondChild: Container(
                width: double.infinity,
                color: Variables.surfaceSubtle.withOpacity(0.5),
                child: Column(
                  children:
                      g.events.map((e) {
                        return ListTile(
                          onTap:
                              () => widget.onProjectSelected(
                                e.id,
                                e.title,
                                project.title,
                              ),
                          contentPadding: const EdgeInsets.symmetric(
                            horizontal: 24,
                            vertical: 2,
                          ),
                          visualDensity: VisualDensity.compact,
                          leading: Container(
                            width: 40,
                            height: 40,
                            decoration: BoxDecoration(
                              color: Variables.background,
                              borderRadius: BorderRadius.circular(
                                Variables.radiusSmall,
                              ),
                              border: Border.all(color: Variables.borderSubtle),
                              image:
                                  e.coverPath != null
                                      ? DecorationImage(
                                        image: FileImage(File(e.coverPath!)),
                                        fit: BoxFit.cover,
                                      )
                                      : null,
                            ),
                            child:
                                e.coverPath == null
                                    ? const Icon(
                                      Icons.event,
                                      size: 20,
                                      color: Variables.textDisabled,
                                    )
                                    : null,
                          ),
                          title: Text(
                            e.title,
                            style: Variables.bodyStyle.copyWith(
                              fontSize: 15,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        );
                      }).toList(),
                ),
              ),
              crossFadeState:
                  g.isExpanded
                      ? CrossFadeState.showSecond
                      : CrossFadeState.showFirst,
              duration: const Duration(milliseconds: 200),
            ),
        ],
      ),
    );
  }
}