LifeMate — Personal, Family & Learning Companion

fix/personal-upgrade-delivery-guard
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
dart 1,063 lines 41.6 KB
Raw
1 import 'package:flutter/material.dart';
2
3 import 'app.dart';
4 import 'model.dart';
5 import 'personal_dates.dart';
6 import 'personal_date_picker.dart';
7 import 'settings_ui.dart';
8 import 'store.dart';
9
10 DateTime _day(DateTime value) => DateTime(value.year, value.month, value.day);
11 DateTime _addDays(DateTime value, int count) =>
12 DateTime(value.year, value.month, value.day + count);
13 DateTime _saturday(DateTime value) =>
14 _addDays(_day(value), -((value.weekday + 1) % 7));
15
16 String _digits(Object value) => value.toString().replaceAllMapped(
17 RegExp('[0-9]'), (match) => '۰۱۲۳۴۵۶۷۸۹'[int.parse(match[0]!)]);
18 String _time(int minute) =>
19 '${_digits((minute ~/ 60).toString().padLeft(2, '0'))}:${_digits((minute % 60).toString().padLeft(2, '0'))}';
20 const _weekdays = <int, String>{
21 6: 'شنبه',
22 7: 'یکشنبه',
23 1: 'دوشنبه',
24 2: 'سه‌شنبه',
25 3: 'چهارشنبه',
26 4: 'پنجشنبه',
27 5: 'جمعه',
28 };
29 String _date(DateTime value) => personalDateLabel(value);
30 String _kind(StandalonePlanKind value) => switch (value) {
31 StandalonePlanKind.task => 'کار',
32 StandalonePlanKind.event => 'رویداد',
33 StandalonePlanKind.routine => 'عادت',
34 };
35 String _recurrence(StandaloneRecurrence value) => switch (value) {
36 StandaloneRecurrence.once => 'فقط یک بار',
37 StandaloneRecurrence.daily => 'هر روز',
38 StandaloneRecurrence.everyTwoDays => 'یک روز در میان',
39 StandaloneRecurrence.weekly => 'روزهای انتخابی هفته',
40 };
41
42 class StandalonePlannerShell extends StatefulWidget {
43 const StandalonePlannerShell({
44 super.key,
45 required this.store,
46 required this.profile,
47 required this.onProfileSaved,
48 this.reminderSettingsBuilder,
49 this.onPlansChanged,
50 this.onBeforePlansChange,
51 this.onResumed,
52 });
53 final StandaloneStore store;
54 final StandaloneProfile profile;
55 final Future<void> Function() onProfileSaved;
56 final StandaloneReminderSettingsBuilder? reminderSettingsBuilder;
57 final Future<void> Function(StandaloneStore)? onPlansChanged;
58 final Future<void> Function(StandaloneStore)? onBeforePlansChange;
59 final Future<void> Function(StandaloneStore)? onResumed;
60
61 @override
62 State<StandalonePlannerShell> createState() => _StandalonePlannerShellState();
63 }
64
65 class _StandalonePlannerShellState extends State<StandalonePlannerShell>
66 with WidgetsBindingObserver {
67 int _tab = 0;
68 DateTime _selectedDate = _day(DateTime.now());
69 List<StandaloneOccurrence> _today = [];
70 List<StandaloneOccurrence> _week = [];
71 bool _loading = true;
72 bool _failed = false;
73 bool _saving = false;
74 int _loadNumber = 0;
75
76 @override
77 void initState() {
78 super.initState();
79 WidgetsBinding.instance.addObserver(this);
80 _load();
81 }
82
83 @override
84 void dispose() {
85 WidgetsBinding.instance.removeObserver(this);
86 super.dispose();
87 }
88
89 @override
90 void didChangeAppLifecycleState(AppLifecycleState state) {
91 if (state == AppLifecycleState.resumed && !_saving) _resume();
92 }
93
94 Future<void> _resume() async {
95 await _load();
96 if (!mounted || _saving || _failed) return;
97 try {
98 await widget.onResumed?.call(widget.store);
99 } catch (_) {
100 if (mounted) {
101 ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
102 content: Text(
103 'برنامه‌ها باز شدند؛ وضعیت یادآوری را در تنظیمات بررسی کن.')));
104 }
105 }
106 }
107
108 Future<void> _load() async {
109 final request = ++_loadNumber;
110 setState(() {
111 _loading = true;
112 _failed = false;
113 });
114 try {
115 final today = _day(DateTime.now());
116 final weekStart = _saturday(_selectedDate);
117 final values = await Future.wait([
118 widget.store.occurrences(from: today, through: today),
119 widget.store
120 .occurrences(from: weekStart, through: _addDays(weekStart, 6)),
121 ]);
122 if (!mounted || request != _loadNumber) return;
123 setState(() {
124 _today = values[0].where((item) => !item.archived).toList();
125 _week = values[1].where((item) => !item.archived).toList();
126 _loading = false;
127 });
128 } catch (_) {
129 if (!mounted || request != _loadNumber) return;
130 setState(() {
131 _loading = false;
132 _failed = true;
133 });
134 }
135 }
136
137 Future<bool> _write(Future<void> Function() action) async {
138 if (_saving) return false;
139 setState(() => _saving = true);
140 try {
141 await widget.onBeforePlansChange?.call(widget.store);
142 await action();
143 } catch (_) {
144 try {
145 await widget.onPlansChanged?.call(widget.store);
146 } catch (_) {
147 // Restoring old reminders is best effort; the durable error stays visible.
148 }
149 if (mounted) {
150 setState(() => _saving = false);
151 ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
152 content: Text(
153 'تغییر ذخیره نشد. فضای خالی گوشی را بررسی کن و دوباره تلاش کن.')));
154 }
155 return false;
156 }
157 bool reminderFailed = false;
158 try {
159 await widget.onPlansChanged?.call(widget.store);
160 } catch (_) {
161 reminderFailed = true;
162 }
163 if (!mounted) return true;
164 setState(() => _saving = false);
165 await _load();
166 if (!mounted) return true;
167 ScaffoldMessenger.of(context).showSnackBar(SnackBar(
168 content: Text(reminderFailed
169 ? 'برنامه ذخیره شد؛ آماده‌سازی یادآوری را در تنظیمات بررسی کن.'
170 : 'روی این گوشی ذخیره شد.')));
171 return true;
172 }
173
174 Future<void> _openEditor() async {
175 await Navigator.of(context).push<void>(MaterialPageRoute(
176 builder: (_) => Directionality(
177 textDirection: TextDirection.rtl,
178 child: _PlanEditor(
179 date: _tab == 0 ? _day(DateTime.now()) : _selectedDate,
180 onSave: (draft) => _write(() async {
181 await widget.store.createPlan(draft);
182 }),
183 ),
184 )));
185 }
186
187 Future<void> _details(StandaloneOccurrence item) async {
188 await showModalBottomSheet<void>(
189 context: context,
190 isScrollControlled: true,
191 useSafeArea: true,
192 builder: (_) => Directionality(
193 textDirection: TextDirection.rtl,
194 child: _OccurrenceDetails(
195 initial: item,
196 store: widget.store,
197 write: _write,
198 ),
199 ),
200 );
201 }
202
203 Widget _list(List<StandaloneOccurrence> items) => Column(
204 children: items
205 .map((item) => Padding(
206 padding: const EdgeInsets.only(bottom: 12),
207 child: _OccurrenceCard(
208 item: item,
209 enabled: !_saving,
210 onOpen: () => _details(item),
211 onTick: () => _write(() async {
212 await widget.store.updateOccurrence(item.id,
213 completed: !item.completed);
214 }),
215 ),
216 ))
217 .toList(),
218 );
219
220 Widget _empty() => Card(
221 child: Padding(
222 padding: const EdgeInsets.all(24),
223 child: Column(children: [
224 Icon(Icons.edit_calendar_outlined,
225 size: 44, color: Theme.of(context).colorScheme.primary),
226 const SizedBox(height: 16),
227 const Text('برای این روز هنوز برنامه‌ای ننوشته‌ای.'),
228 const SizedBox(height: 12),
229 OutlinedButton.icon(
230 onPressed: _saving ? null : _openEditor,
231 icon: const Icon(Icons.add),
232 label: const Text('یک برنامه اضافه کن')),
233 ]),
234 ),
235 );
236
237 Widget _todayPage() {
238 final completed = _today.where((item) => item.completed).length;
239 final pending = _today.where((item) => !item.completed).take(4).toList();
240 return ListView(
241 padding: const EdgeInsets.all(20),
242 children: [
243 Text('سلام ${widget.profile.displayName}',
244 style: Theme.of(context).textTheme.headlineSmall),
245 const SizedBox(height: 8),
246 Text('${_weekdays[DateTime.now().weekday]}، ${_date(DateTime.now())}'),
247 const SizedBox(height: 20),
248 Card(
249 color: Theme.of(context).colorScheme.primaryContainer,
250 child: Padding(
251 padding: const EdgeInsets.all(20),
252 child: Column(
253 crossAxisAlignment: CrossAxisAlignment.start,
254 children: [
255 Text(
256 _today.isEmpty
257 ? 'امروز را خودت بساز'
258 : 'هر قدم حساب می‌شود',
259 style: Theme.of(context).textTheme.titleLarge),
260 const SizedBox(height: 12),
261 Text(_today.isEmpty
262 ? 'با یک کار کوچک شروع کن.'
263 : '${_digits(completed)} از ${_digits(_today.length)} برنامه انجام شده'),
264 if (_today.isNotEmpty) ...[
265 const SizedBox(height: 12),
266 Semantics(
267 label:
268 '${_digits(completed)} از ${_digits(_today.length)} برنامه انجام شده',
269 child: LinearProgressIndicator(
270 value: completed / _today.length,
271 minHeight: 8,
272 borderRadius: BorderRadius.circular(8),
273 ),
274 ),
275 ],
276 ],
277 ),
278 ),
279 ),
280 const SizedBox(height: 24),
281 Text('قدم‌های امروز', style: Theme.of(context).textTheme.titleLarge),
282 const SizedBox(height: 12),
283 if (_today.isEmpty)
284 _empty()
285 else if (pending.isEmpty)
286 const Card(
287 child: Padding(
288 padding: EdgeInsets.all(20),
289 child: Text(
290 'برنامه‌های امروز انجام شده‌اند. وقت یک نفس تازه است.')))
291 else
292 _list(pending),
293 if (_today.length > pending.length) ...[
294 const SizedBox(height: 12),
295 TextButton(
296 onPressed: () => setState(() {
297 _selectedDate = _day(DateTime.now());
298 _tab = 1;
299 _load();
300 }),
301 child: const Text('دیدن همهٔ برنامه‌های امروز در هفته')),
302 ],
303 const SizedBox(height: 72),
304 ],
305 );
306 }
307
308 Widget _weekPage() {
309 final start = _saturday(_selectedDate);
310 final items =
311 _week.where((item) => _day(item.date) == _selectedDate).toList();
312 return ListView(padding: const EdgeInsets.all(20), children: [
313 Row(children: [
314 Expanded(
315 child: Text('هفتهٔ من',
316 style: Theme.of(context).textTheme.headlineSmall)),
317 TextButton(
318 onPressed: () {
319 _selectedDate = _day(DateTime.now());
320 _load();
321 },
322 child: const Text('امروز')),
323 ]),
324 Row(children: [
325 IconButton(
326 tooltip: 'هفتهٔ قبل',
327 onPressed: () {
328 _selectedDate = _addDays(_selectedDate, -7);
329 _load();
330 },
331 icon: const Icon(Icons.chevron_right)),
332 Expanded(
333 child: Text('${_date(start)} تا ${_date(_addDays(start, 6))}',
334 textAlign: TextAlign.center)),
335 IconButton(
336 tooltip: 'هفتهٔ بعد',
337 onPressed: () {
338 _selectedDate = _addDays(_selectedDate, 7);
339 _load();
340 },
341 icon: const Icon(Icons.chevron_left)),
342 ]),
343 const Text('تاریخ‌ها شمسی‌اند.', textAlign: TextAlign.center),
344 const SizedBox(height: 16),
345 Wrap(spacing: 8, runSpacing: 8, children: [
346 for (int index = 0; index < 7; index++)
347 ChoiceChip(
348 label: Padding(
349 padding: const EdgeInsets.symmetric(vertical: 8),
350 child: Text(
351 '${_weekdays[_addDays(start, index).weekday]}\n${personalDayLabel(_addDays(start, index))}',
352 textAlign: TextAlign.center),
353 ),
354 selected: _addDays(start, index) == _selectedDate,
355 onSelected: (_) =>
356 setState(() => _selectedDate = _addDays(start, index)),
357 ),
358 ]),
359 const SizedBox(height: 24),
360 Text('${_weekdays[_selectedDate.weekday]}، ${_date(_selectedDate)}',
361 style: Theme.of(context).textTheme.titleMedium),
362 const SizedBox(height: 12),
363 if (items.isEmpty) _empty() else _list(items),
364 const SizedBox(height: 72),
365 ]);
366 }
367
368 @override
369 Widget build(BuildContext context) => Scaffold(
370 appBar: AppBar(
371 toolbarHeight: 56 * MediaQuery.textScalerOf(context).scale(1),
372 title: Column(
373 crossAxisAlignment: CrossAxisAlignment.start,
374 children: [
375 Text('برنامهٔ من', style: Theme.of(context).textTheme.titleLarge),
376 Text('فقط این گوشی',
377 style: Theme.of(context).textTheme.bodySmall),
378 ],
379 ),
380 ),
381 body: Center(
382 child: ConstrainedBox(
383 constraints: const BoxConstraints(maxWidth: 760),
384 child: _tab == 2
385 ? StandaloneSettings(
386 key: ValueKey(widget.profile.id),
387 store: widget.store,
388 profile: widget.profile,
389 onSaved: widget.onProfileSaved,
390 onBeforeChange: () async =>
391 widget.onBeforePlansChange?.call(widget.store),
392 onAfterChange: () async =>
393 widget.onPlansChanged?.call(widget.store),
394 reminderSettings: widget.reminderSettingsBuilder
395 ?.call(context, widget.store),
396 )
397 : _loading
398 ? const Center(child: CircularProgressIndicator())
399 : _failed
400 ? Center(
401 child: Padding(
402 padding: const EdgeInsets.all(24),
403 child: Column(
404 mainAxisSize: MainAxisSize.min,
405 children: [
406 const Text(
407 'خواندن برنامه‌ها انجام نشد. داده‌ای پاک نشده است.',
408 textAlign: TextAlign.center),
409 const SizedBox(height: 16),
410 FilledButton(
411 onPressed: _load,
412 child: const Text('تلاش دوباره')),
413 ]),
414 ),
415 )
416 : RefreshIndicator(
417 onRefresh: _load,
418 child: _tab == 0 ? _todayPage() : _weekPage()),
419 ),
420 ),
421 floatingActionButton: _tab == 2 || _loading || _failed
422 ? null
423 : FloatingActionButton.extended(
424 heroTag: null,
425 onPressed: _saving ? null : _openEditor,
426 icon: const Icon(Icons.add),
427 label: const Text('برنامهٔ تازه')),
428 bottomNavigationBar: NavigationBar(
429 selectedIndex: _tab,
430 onDestinationSelected: (value) => setState(() => _tab = value),
431 destinations: const [
432 NavigationDestination(
433 icon: Icon(Icons.wb_sunny_outlined), label: 'امروز'),
434 NavigationDestination(
435 icon: Icon(Icons.calendar_month_outlined), label: 'هفته'),
436 NavigationDestination(icon: Icon(Icons.tune), label: 'تنظیمات'),
437 ],
438 ),
439 );
440 }
441
442 class _OccurrenceCard extends StatelessWidget {
443 const _OccurrenceCard(
444 {required this.item,
445 required this.enabled,
446 required this.onOpen,
447 required this.onTick});
448 final StandaloneOccurrence item;
449 final bool enabled;
450 final VoidCallback onOpen;
451 final VoidCallback onTick;
452
453 @override
454 Widget build(BuildContext context) => Card(
455 margin: EdgeInsets.zero,
456 child: Padding(
457 padding: const EdgeInsets.all(12),
458 child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
459 SizedBox(
460 width: 48,
461 height: 48,
462 child: Checkbox(
463 value: item.completed,
464 semanticLabel: 'انجام ${item.title}',
465 onChanged: enabled ? (_) => onTick() : null,
466 ),
467 ),
468 const SizedBox(width: 8),
469 Expanded(
470 child: Column(
471 crossAxisAlignment: CrossAxisAlignment.start,
472 children: [
473 Text(item.title,
474 style: Theme.of(context).textTheme.titleMedium?.copyWith(
475 decoration: item.completed
476 ? TextDecoration.lineThrough
477 : null)),
478 const SizedBox(height: 4),
479 Text(
480 '${_time(item.startMinute)} تا ${_time(item.endMinute)} · ${_kind(item.kind)}'),
481 const SizedBox(height: 8),
482 OutlinedButton(
483 onPressed: enabled ? onOpen : null,
484 child: Text(item.completed ? 'جزئیات' : 'شروع'),
485 ),
486 ],
487 ),
488 ),
489 ]),
490 ),
491 );
492 }
493
494 class _OccurrenceDetails extends StatefulWidget {
495 const _OccurrenceDetails(
496 {required this.initial, required this.store, required this.write});
497 final StandaloneOccurrence initial;
498 final StandaloneStore store;
499 final Future<bool> Function(Future<void> Function()) write;
500
501 @override
502 State<_OccurrenceDetails> createState() => _OccurrenceDetailsState();
503 }
504
505 class _OccurrenceDetailsState extends State<_OccurrenceDetails> {
506 late StandaloneOccurrence _item = widget.initial;
507 bool _busy = false;
508 String? _error;
509
510 Future<bool> _change(Future<void> Function() action) async {
511 if (_busy) return false;
512 setState(() {
513 _busy = true;
514 _error = null;
515 });
516 final saved = await widget.write(action);
517 if (!mounted) return saved;
518 if (saved) {
519 try {
520 final item = await widget.store.occurrence(_item.id);
521 if (!mounted) return true;
522 if (item == null || item.archived) {
523 Navigator.pop(context);
524 return true;
525 }
526 setState(() => _item = item);
527 } catch (_) {
528 setState(() => _error =
529 'تغییر ذخیره شد؛ بازخوانی جزئیات انجام نشد. این صفحه را ببند و دوباره باز کن.');
530 }
531 } else {
532 setState(() => _error = 'ذخیره انجام نشد. دوباره تلاش کن.');
533 }
534 if (mounted) setState(() => _busy = false);
535 return saved;
536 }
537
538 Future<void> _archive() async {
539 final scope = await showDialog<String>(
540 context: context,
541 builder: (context) => AlertDialog(
542 title: const Text('کدام برنامه بایگانی شود؟'),
543 content: const Text(
544 'بایگانی این نوبت، فقط همین روز را از فهرست کنار می‌گذارد. بایگانی کل برنامه، نوبت‌های آینده و یادآوری‌های آن را متوقف می‌کند؛ سابقهٔ انجام‌شده حفظ می‌شود.'),
545 actions: [
546 TextButton(
547 onPressed: () => Navigator.pop(context),
548 child: const Text('انصراف')),
549 TextButton(
550 onPressed: () => Navigator.pop(context, 'one'),
551 child: const Text('فقط این نوبت')),
552 FilledButton(
553 onPressed: () => Navigator.pop(context, 'all'),
554 child: const Text('کل برنامه و همهٔ نوبت‌های آینده')),
555 ],
556 ));
557 if (scope == null || !mounted) return;
558 final saved = await _change(() async {
559 if (scope == 'all') {
560 await widget.store.archivePlan(_item.planId);
561 } else {
562 await widget.store.archiveOccurrence(_item.id);
563 }
564 });
565 if (saved && scope == 'all' && mounted) Navigator.pop(context);
566 }
567
568 Future<void> _edit() async {
569 await showModalBottomSheet<void>(
570 context: context,
571 isScrollControlled: true,
572 useSafeArea: true,
573 isDismissible: false,
574 enableDrag: false,
575 builder: (_) => _OccurrenceEditor(
576 item: _item,
577 onSave: (edit) => _change(() async {
578 await widget.store.updateOccurrence(_item.id,
579 title: edit.title,
580 startMinute: edit.start,
581 endMinute: edit.end,
582 reminderMinutes: edit.reminder,
583 removeReminder: edit.reminder == null);
584 })));
585 }
586
587 @override
588 Widget build(BuildContext context) => SingleChildScrollView(
589 padding: EdgeInsets.fromLTRB(
590 24, 24, 24, 24 + MediaQuery.viewInsetsOf(context).bottom),
591 child: Column(
592 mainAxisSize: MainAxisSize.min,
593 crossAxisAlignment: CrossAxisAlignment.stretch,
594 children: [
595 Text(_item.title,
596 style: Theme.of(context).textTheme.headlineSmall),
597 const SizedBox(height: 12),
598 Text('${_weekdays[_item.date.weekday]}، ${_date(_item.date)}'),
599 Text(
600 '${_time(_item.startMinute)} تا ${_time(_item.endMinute)} · ${_kind(_item.kind)}'),
601 const SizedBox(height: 8),
602 Text(_item.reminderMinutes == null
603 ? 'برای این نوبت یادآوری انتخاب نشده.'
604 : '${_digits(_item.reminderMinutes!)} دقیقه پیش از شروع؛ وضعیت فعال بودن را در تنظیمات یادآوری بررسی کن.'),
605 const SizedBox(height: 20),
606 const Text('وقتی کارت تمام شد، انجام آن را ثبت کن.'),
607 const SizedBox(height: 16),
608 FilledButton.icon(
609 onPressed: _busy
610 ? null
611 : () => _change(() async {
612 await widget.store.updateOccurrence(_item.id,
613 completed: !_item.completed);
614 }),
615 icon: Icon(_item.completed ? Icons.undo : Icons.check),
616 label: Text(_item.completed
617 ? 'برگرداندن به انجام‌نشده'
618 : 'انجام شد')),
619 const SizedBox(height: 12),
620 OutlinedButton.icon(
621 onPressed: _busy ? null : _edit,
622 icon: const Icon(Icons.edit_outlined),
623 label: const Text('ویرایش همین نوبت')),
624 TextButton.icon(
625 onPressed: _busy ? null : _archive,
626 icon: const Icon(Icons.archive_outlined),
627 label: const Text('بایگانی…')),
628 if (_error != null)
629 Text(_error!,
630 style:
631 TextStyle(color: Theme.of(context).colorScheme.error)),
632 TextButton(
633 onPressed: _busy ? null : () => Navigator.pop(context),
634 child: const Text('بستن')),
635 ]),
636 );
637 }
638
639 class _OccurrenceEdit {
640 const _OccurrenceEdit(this.title, this.start, this.end, this.reminder);
641 final String title;
642 final int start;
643 final int end;
644 final int? reminder;
645 }
646
647 class _OccurrenceEditor extends StatefulWidget {
648 const _OccurrenceEditor({required this.item, required this.onSave});
649 final StandaloneOccurrence item;
650 final Future<bool> Function(_OccurrenceEdit) onSave;
651 @override
652 State<_OccurrenceEditor> createState() => _OccurrenceEditorState();
653 }
654
655 class _OccurrenceEditorState extends State<_OccurrenceEditor> {
656 late final TextEditingController _title =
657 TextEditingController(text: widget.item.title);
658 late int _start = widget.item.startMinute;
659 late int _end = widget.item.endMinute;
660 late int? _reminder = widget.item.reminderMinutes;
661 bool _busy = false;
662 String? _error;
663 @override
664 void dispose() {
665 _title.dispose();
666 super.dispose();
667 }
668
669 @override
670 Widget build(BuildContext context) => PopScope(
671 canPop: !_busy,
672 child: Directionality(
673 textDirection: TextDirection.rtl,
674 child: SingleChildScrollView(
675 padding: EdgeInsets.fromLTRB(
676 24, 24, 24, 24 + MediaQuery.viewInsetsOf(context).bottom),
677 child: Column(
678 mainAxisSize: MainAxisSize.min,
679 crossAxisAlignment: CrossAxisAlignment.stretch,
680 children: [
681 Text('ویرایش همین نوبت',
682 style: Theme.of(context).textTheme.titleLarge),
683 const SizedBox(height: 16),
684 TextField(
685 key: const Key('occurrence-title'),
686 controller: _title,
687 enabled: !_busy,
688 maxLength: 120,
689 decoration: const InputDecoration(labelText: 'عنوان')),
690 const SizedBox(height: 12),
691 _TimeFields(
692 start: _start,
693 end: _end,
694 enabled: !_busy,
695 onChanged: (start, end) => setState(() {
696 _start = start;
697 _end = end;
698 })),
699 const SizedBox(height: 16),
700 _ReminderField(
701 value: _reminder,
702 enabled: !_busy,
703 onChanged: (value) =>
704 setState(() => _reminder = value)),
705 if (_error != null)
706 Padding(
707 padding: const EdgeInsets.only(top: 12),
708 child: Text(_error!,
709 style: TextStyle(
710 color: Theme.of(context).colorScheme.error))),
711 const SizedBox(height: 20),
712 FilledButton(
713 onPressed: _busy
714 ? null
715 : () async {
716 if (_title.text.trim().isEmpty ||
717 _end <= _start) {
718 setState(() => _error =
719 'عنوان را بنویس و پایان را بعد از شروع انتخاب کن.');
720 return;
721 }
722 setState(() {
723 _busy = true;
724 _error = null;
725 });
726 final saved = await widget.onSave(
727 _OccurrenceEdit(_title.text.trim(), _start,
728 _end, _reminder));
729 if (!context.mounted) return;
730 if (saved) {
731 Navigator.pop(context);
732 } else {
733 setState(() {
734 _busy = false;
735 _error =
736 'تغییر ذخیره نشد. می‌توانی دوباره تلاش کنی.';
737 });
738 }
739 },
740 child: Text(
741 _busy ? 'در حال ذخیره…' : 'ثبت تغییر همین نوبت')),
742 TextButton(
743 onPressed: _busy ? null : () => Navigator.pop(context),
744 child: const Text('انصراف')),
745 ]),
746 )),
747 );
748 }
749
750 class _PlanEditor extends StatefulWidget {
751 const _PlanEditor({required this.date, required this.onSave});
752 final DateTime date;
753 final Future<bool> Function(StandalonePlanDraft) onSave;
754 @override
755 State<_PlanEditor> createState() => _PlanEditorState();
756 }
757
758 class _PlanEditorState extends State<_PlanEditor> {
759 final _title = TextEditingController();
760 StandalonePlanKind _kindValue = StandalonePlanKind.task;
761 StandaloneRecurrence _repeat = StandaloneRecurrence.once;
762 late DateTime _startDate = _day(widget.date);
763 DateTime? _until;
764 int _start = 9 * 60;
765 int _end = 10 * 60;
766 int? _reminder;
767 final Map<int, (int, int)> _slots = {};
768 bool _busy = false;
769 String? _error;
770
771 @override
772 void dispose() {
773 _title.dispose();
774 super.dispose();
775 }
776
777 Future<DateTime?> _pickDate(DateTime initial) => showPersonalDatePicker(
778 context: context,
779 initialDate: initial,
780 firstDate: DateTime(2020),
781 lastDate: DateTime(2100));
782
783 Future<void> _save() async {
784 if (_busy) return;
785 if (_title.text.trim().isEmpty) {
786 setState(() => _error = 'یک عنوان برای برنامه بنویس.');
787 return;
788 }
789 if (_repeat == StandaloneRecurrence.weekly && _slots.isEmpty) {
790 setState(() => _error = 'دست‌کم یک روز هفته را انتخاب کن.');
791 return;
792 }
793 if (_end <= _start || _slots.values.any((slot) => slot.$2 <= slot.$1)) {
794 setState(
795 () => _error = 'ساعت پایان هر روز باید بعد از شروع همان روز باشد.');
796 return;
797 }
798 if (_until != null && _until!.isBefore(_startDate)) {
799 setState(() => _error = 'تاریخ پایان تکرار نباید پیش از شروع باشد.');
800 return;
801 }
802 final draft = StandalonePlanDraft(
803 title: _title.text.trim(),
804 kind: _kindValue,
805 recurrence: _repeat,
806 startDate: _startDate,
807 untilDate: _repeat == StandaloneRecurrence.once ? null : _until,
808 startMinute: _start,
809 endMinute: _end,
810 reminderMinutes: _reminder,
811 weeklySlots: _repeat != StandaloneRecurrence.weekly
812 ? const []
813 : _slots.entries
814 .map((entry) => StandaloneWeeklySlot(
815 weekday: entry.key,
816 startMinute: entry.value.$1,
817 endMinute: entry.value.$2))
818 .toList(),
819 );
820 setState(() {
821 _busy = true;
822 _error = null;
823 });
824 final saved = await widget.onSave(draft);
825 if (!mounted) return;
826 if (saved) {
827 Navigator.pop(context);
828 } else {
829 setState(() {
830 _busy = false;
831 _error = 'برنامه ذخیره نشد. می‌توانی دوباره تلاش کنی.';
832 });
833 }
834 }
835
836 @override
837 Widget build(BuildContext context) => PopScope(
838 canPop: !_busy,
839 child: Scaffold(
840 appBar: AppBar(title: const Text('برنامهٔ تازه')),
841 body: Center(
842 child: ConstrainedBox(
843 constraints: const BoxConstraints(maxWidth: 640),
844 child: ListView(
845 padding: const EdgeInsets.all(20),
846 children: [
847 TextField(
848 key: const Key('plan-title'),
849 controller: _title,
850 enabled: !_busy,
851 maxLength: 120,
852 decoration: const InputDecoration(
853 labelText: 'عنوان برنامه',
854 hintText: 'یک قدم مشخص و شدنی')),
855 const SizedBox(height: 16),
856 DropdownButtonFormField<StandalonePlanKind>(
857 initialValue: _kindValue,
858 itemHeight: null,
859 isExpanded: true,
860 decoration:
861 const InputDecoration(labelText: 'نوع برنامه'),
862 items: StandalonePlanKind.values
863 .map((value) => DropdownMenuItem(
864 value: value, child: Text(_kind(value))))
865 .toList(),
866 onChanged: _busy
867 ? null
868 : (value) => setState(() => _kindValue = value!)),
869 const SizedBox(height: 16),
870 DropdownButtonFormField<StandaloneRecurrence>(
871 key: const Key('plan-recurrence'),
872 initialValue: _repeat,
873 itemHeight: null,
874 isExpanded: true,
875 decoration: const InputDecoration(labelText: 'تکرار'),
876 items: StandaloneRecurrence.values
877 .map((value) => DropdownMenuItem(
878 value: value,
879 child: Text(_recurrence(value))))
880 .toList(),
881 onChanged: _busy
882 ? null
883 : (value) => setState(() => _repeat = value!)),
884 const SizedBox(height: 16),
885 OutlinedButton.icon(
886 onPressed: _busy
887 ? null
888 : () async {
889 final picked = await _pickDate(_startDate);
890 if (picked != null && mounted) {
891 setState(() => _startDate = _day(picked));
892 }
893 },
894 icon: const Icon(Icons.calendar_today_outlined),
895 label: Text(
896 '${_repeat == StandaloneRecurrence.once ? 'تاریخ' : 'شروع تکرار'}: ${_date(_startDate)}')),
897 if (_repeat == StandaloneRecurrence.weekly) ...[
898 const SizedBox(height: 20),
899 const Text('روزهای هفته و ساعت مستقل هر روز'),
900 const SizedBox(height: 12),
901 Wrap(spacing: 8, runSpacing: 8, children: [
902 for (final entry in _weekdays.entries)
903 FilterChip(
904 key: ValueKey('plan-weekday-${entry.key}'),
905 label: Padding(
906 padding:
907 const EdgeInsets.symmetric(vertical: 8),
908 child: Text(entry.value)),
909 selected: _slots.containsKey(entry.key),
910 onSelected: _busy
911 ? null
912 : (selected) => setState(() {
913 if (selected) {
914 _slots[entry.key] = (_start, _end);
915 } else {
916 _slots.remove(entry.key);
917 }
918 })),
919 ]),
920 for (final weekday
921 in _weekdays.keys.where(_slots.containsKey)) ...[
922 const SizedBox(height: 16),
923 Text(_weekdays[weekday]!),
924 _TimeFields(
925 key: ValueKey('weekly-hours-$weekday'),
926 start: _slots[weekday]!.$1,
927 end: _slots[weekday]!.$2,
928 enabled: !_busy,
929 onChanged: (start, end) => setState(
930 () => _slots[weekday] = (start, end))),
931 ],
932 ] else ...[
933 const SizedBox(height: 16),
934 _TimeFields(
935 start: _start,
936 end: _end,
937 enabled: !_busy,
938 onChanged: (start, end) => setState(() {
939 _start = start;
940 _end = end;
941 })),
942 ],
943 if (_repeat != StandaloneRecurrence.once) ...[
944 const SizedBox(height: 20),
945 SwitchListTile(
946 contentPadding: EdgeInsets.zero,
947 title: const Text('تکرار تاریخ پایان داشته باشد'),
948 value: _until != null,
949 onChanged: _busy
950 ? null
951 : (value) => setState(() => _until =
952 value ? _addDays(_startDate, 30) : null)),
953 if (_until != null)
954 OutlinedButton(
955 onPressed: _busy
956 ? null
957 : () async {
958 final picked = await _pickDate(_until!);
959 if (picked != null && mounted) {
960 setState(() => _until = _day(picked));
961 }
962 },
963 child: Text('آخرین روز: ${_date(_until!)}')),
964 ],
965 const SizedBox(height: 20),
966 _ReminderField(
967 value: _reminder,
968 enabled: !_busy,
969 onChanged: (value) =>
970 setState(() => _reminder = value)),
971 const SizedBox(height: 8),
972 const Text(
973 'انتخاب زمان یادآوری به‌تنهایی اعلان را فعال نمی‌کند. مجوز و وضعیت آن در تنظیمات یادآوری دیده می‌شود.'),
974 if (_error != null)
975 Padding(
976 padding: const EdgeInsets.only(top: 16),
977 child: Text(_error!,
978 style: TextStyle(
979 color:
980 Theme.of(context).colorScheme.error))),
981 const SizedBox(height: 24),
982 FilledButton(
983 onPressed: _busy ? null : _save,
984 child:
985 Text(_busy ? 'در حال ذخیره…' : 'ذخیرهٔ برنامه')),
986 const SizedBox(height: 24),
987 ],
988 ))),
989 ),
990 );
991 }
992
993 class _TimeFields extends StatelessWidget {
994 const _TimeFields(
995 {super.key,
996 required this.start,
997 required this.end,
998 required this.onChanged,
999 this.enabled = true});
1000 final int start;
1001 final int end;
1002 final bool enabled;
1003 final void Function(int start, int end) onChanged;
1004
1005 Future<int?> _pick(BuildContext context, int minute) async {
1006 final time = await showTimePicker(
1007 context: context,
1008 initialTime: TimeOfDay(hour: (minute ~/ 60) % 24, minute: minute % 60),
1009 initialEntryMode: TimePickerEntryMode.input,
1010 builder: (context, child) => MediaQuery(
1011 data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
1012 child: child!));
1013 return time == null ? null : time.hour * 60 + time.minute;
1014 }
1015
1016 @override
1017 Widget build(BuildContext context) =>
1018 Wrap(spacing: 12, runSpacing: 8, children: [
1019 OutlinedButton(
1020 onPressed: !enabled
1021 ? null
1022 : () async {
1023 final value = await _pick(context, start);
1024 if (value != null) onChanged(value, end);
1025 },
1026 child: Text('شروع: ${_time(start)}')),
1027 OutlinedButton(
1028 onPressed: !enabled
1029 ? null
1030 : () async {
1031 final value = await _pick(context, end);
1032 if (value != null) onChanged(start, value);
1033 },
1034 child: Text('پایان: ${_time(end)}')),
1035 ]);
1036 }
1037
1038 class _ReminderField extends StatelessWidget {
1039 const _ReminderField(
1040 {required this.value, required this.onChanged, this.enabled = true});
1041 final int? value;
1042 final ValueChanged<int?> onChanged;
1043 final bool enabled;
1044
1045 @override
1046 Widget build(BuildContext context) => DropdownButtonFormField<int>(
1047 initialValue: value ?? -1,
1048 itemHeight: null,
1049 isExpanded: true,
1050 decoration: const InputDecoration(labelText: 'زمان یادآوری'),
1051 items: [
1052 const DropdownMenuItem(value: -1, child: Text('بدون یادآوری')),
1053 const DropdownMenuItem(value: 0, child: Text('هنگام شروع')),
1054 for (final minutes in [5, 10, 15, 30])
1055 DropdownMenuItem(
1056 value: minutes,
1057 child: Text('${_digits(minutes)} دقیقه پیش از شروع')),
1058 ],
1059 onChanged: !enabled
1060 ? null
1061 : (selected) => onChanged(selected == -1 ? null : selected),
1062 );
1063 }