LifeMate — Personal, Family & Learning Companion

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