@davoodmehraban89 / LifeMate / commits / e7cd624
Fork 0

LifeMate — Personal, Family & Learning Companion

feat(personal): add usable RTL planner entry without a server URL

Quinn White committed Oct 19, 2026 at 13:16 UTC e7cd624245fba0a9cbfb7319513ab70d855d5265
8 files changed +2365
apps/lifemate/lib/standalone/app.dart new
+189
@@ -0,0 +1,189 @@
1 +import 'package:flutter/material.dart';
2 +import 'package:flutter_localizations/flutter_localizations.dart';
3 +
4 +import 'model.dart';
5 +import 'planner_ui.dart';
6 +import 'settings_ui.dart';
7 +import 'store.dart';
8 +
9 +typedef StandaloneStoreOpener = Future<StandaloneStore> Function();
10 +typedef StandaloneReminderSettingsBuilder = Widget Function(
11 + BuildContext context, StandaloneStore store);
12 +
13 +/// This entry point is intentionally independent from identity and HTTP APIs.
14 +class StandaloneApp extends StatefulWidget {
15 + const StandaloneApp({
16 + super.key,
17 + required this.openStore,
18 + this.reminderSettingsBuilder,
19 + this.onPlansChanged,
20 + this.onBeforePlansChange,
21 + this.onResumed,
22 + });
23 +
24 + final StandaloneStoreOpener openStore;
25 + final StandaloneReminderSettingsBuilder? reminderSettingsBuilder;
26 + final Future<void> Function(StandaloneStore store)? onPlansChanged;
27 + final Future<void> Function(StandaloneStore store)? onBeforePlansChange;
28 + final Future<void> Function(StandaloneStore store)? onResumed;
29 +
30 + @override
31 + State<StandaloneApp> createState() => _StandaloneAppState();
32 +}
33 +
34 +class _StandaloneAppState extends State<StandaloneApp> {
35 + StandaloneStore? _store;
36 + StandaloneProfile? _profile;
37 + bool _loading = true;
38 + bool _failed = false;
39 + int _attempt = 0;
40 +
41 + @override
42 + void initState() {
43 + super.initState();
44 + _open();
45 + }
46 +
47 + Future<void> _open() async {
48 + final attempt = ++_attempt;
49 + setState(() {
50 + _loading = true;
51 + _failed = false;
52 + });
53 + try {
54 + final store = _store ?? await widget.openStore();
55 + if (!mounted || attempt != _attempt) return;
56 + _store = store;
57 + final profile = await store.profile();
58 + if (!mounted || attempt != _attempt) return;
59 + setState(() {
60 + _profile = profile;
61 + _loading = false;
62 + });
63 + } catch (_) {
64 + if (!mounted || attempt != _attempt) return;
65 + setState(() {
66 + _loading = false;
67 + _failed = true;
68 + });
69 + }
70 + }
71 +
72 + Future<void> _profileSaved() async {
73 + final profile = await _store!.profile();
74 + if (mounted) setState(() => _profile = profile);
75 + }
76 +
77 + @override
78 + Widget build(BuildContext context) {
79 + final seed = switch (_profile?.themeKey) {
80 + 'blue' => const Color(0xff276e83),
81 + 'mint' => const Color(0xff397b65),
82 + 'coral' => const Color(0xffad5c4c),
83 + _ => const Color(0xff76609a),
84 + };
85 + final colors = ColorScheme.fromSeed(
86 + seedColor: seed,
87 + brightness: Brightness.light,
88 + );
89 + return MaterialApp(
90 + title: 'LifeGuide · برنامهٔ من',
91 + debugShowCheckedModeBanner: false,
92 + locale: const Locale('fa'),
93 + supportedLocales: const [Locale('fa'), Locale('en')],
94 + localizationsDelegates: const [
95 + GlobalMaterialLocalizations.delegate,
96 + GlobalWidgetsLocalizations.delegate,
97 + GlobalCupertinoLocalizations.delegate,
98 + ],
99 + theme: ThemeData(
100 + useMaterial3: true,
101 + fontFamily: 'LifeGuidePersian',
102 + fontFamilyFallback: const ['LifeGuideLatin', 'LifeGuideEmoji'],
103 + colorScheme: colors,
104 + scaffoldBackgroundColor: colors.surface,
105 + textTheme: const TextTheme(
106 + bodySmall: TextStyle(fontSize: 13, height: 1.7),
107 + bodyMedium: TextStyle(fontSize: 15, height: 1.7),
108 + bodyLarge: TextStyle(fontSize: 16, height: 1.7),
109 + labelSmall: TextStyle(fontSize: 12),
110 + labelMedium: TextStyle(fontSize: 13),
111 + labelLarge: TextStyle(fontSize: 14),
112 + ),
113 + inputDecorationTheme: InputDecorationTheme(
114 + border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)),
115 + filled: true,
116 + fillColor: colors.surface,
117 + ),
118 + filledButtonTheme: FilledButtonThemeData(
119 + style: FilledButton.styleFrom(
120 + minimumSize: const Size(48, 52),
121 + shape:
122 + RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
123 + ),
124 + ),
125 + outlinedButtonTheme: OutlinedButtonThemeData(
126 + style: OutlinedButton.styleFrom(minimumSize: const Size(48, 50)),
127 + ),
128 + iconButtonTheme: IconButtonThemeData(
129 + style: IconButton.styleFrom(minimumSize: const Size(48, 48)),
130 + ),
131 + textButtonTheme: TextButtonThemeData(
132 + style: TextButton.styleFrom(minimumSize: const Size(48, 48)),
133 + ),
134 + ),
135 + home: Directionality(
136 + textDirection: TextDirection.rtl,
137 + child: _loading
138 + ? const Scaffold(
139 + body: Center(
140 + child: Column(mainAxisSize: MainAxisSize.min, children: [
141 + CircularProgressIndicator(),
142 + SizedBox(height: 20),
143 + Text('در حال باز کردن برنامهٔ این گوشی…'),
144 + ])))
145 + : _failed
146 + ? Scaffold(
147 + body: SafeArea(
148 + child: Center(
149 + child: Padding(
150 + padding: const EdgeInsets.all(28),
151 + child: Column(
152 + mainAxisSize: MainAxisSize.min,
153 + children: [
154 + const Icon(Icons.folder_off_outlined, size: 48),
155 + const SizedBox(height: 20),
156 + const Text('برنامه‌های این گوشی باز نشد.',
157 + textAlign: TextAlign.center),
158 + const SizedBox(height: 12),
159 + const Text(
160 + 'ممکن است فضای گوشی کافی نباشد یا فایل ذخیره‌سازی خوانده نشود. کمی فضا آزاد کنید و دوباره تلاش کنید. داده‌ها خودکار پاک نمی‌شوند.',
161 + textAlign: TextAlign.center,
162 + ),
163 + const SizedBox(height: 24),
164 + FilledButton(
165 + onPressed: _open,
166 + child: const Text('تلاش دوباره'),
167 + ),
168 + ],
169 + ),
170 + ),
171 + ),
172 + ),
173 + )
174 + : _profile == null
175 + ? StandaloneOnboarding(
176 + store: _store!, onSaved: _profileSaved)
177 + : StandalonePlannerShell(
178 + store: _store!,
179 + profile: _profile!,
180 + onProfileSaved: _profileSaved,
181 + reminderSettingsBuilder: widget.reminderSettingsBuilder,
182 + onPlansChanged: widget.onPlansChanged,
183 + onBeforePlansChange: widget.onBeforePlansChange,
184 + onResumed: widget.onResumed,
185 + ),
186 + ),
187 + );
188 + }
189 +}
apps/lifemate/lib/standalone/planner_ui.dart new
+1062
@@ -0,0 +1,1062 @@
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 +}
apps/lifemate/lib/standalone/reminder_coordinator.dart new
+111
@@ -0,0 +1,111 @@
1 +import 'package:flutter/foundation.dart';
2 +
3 +import 'model.dart';
4 +import 'reminders.dart';
5 +import 'store.dart';
6 +
7 +/// Reads authoritative SQLite before installing any device-only alarms.
8 +class StandaloneReminderCoordinator extends ChangeNotifier {
9 + StandaloneReminderCoordinator(
10 + {StandaloneReminderPort? port, DateTime Function()? now})
11 + : _port = port ?? StandaloneReminderPort(),
12 + _now = now ?? DateTime.now;
13 + final StandaloneReminderPort _port;
14 + final DateTime Function() _now;
15 + StandaloneReminderStatus? status;
16 + String? error;
17 + int _revision = 0;
18 + bool _changing = false;
19 +
20 + Future<(StandaloneProfile, List<LocalPersonalReminder>)> _read(
21 + StandaloneStore store) async {
22 + final profile = await store.profile();
23 + if (profile == null) throw StateError('Create the local profile first.');
24 + final now = _now();
25 + final records = await store.pendingReminders(
26 + from: now, through: now.add(const Duration(days: 28)));
27 + return (
28 + profile,
29 + records
30 + .map((row) => LocalPersonalReminder(
31 + id: row.id,
32 + planItemId: row.id,
33 + profileId: profile.id,
34 + scheduledAt: row.remindAt!.toUtc(),
35 + completed: row.completed,
36 + archived: row.archived))
37 + .toList()
38 + );
39 + }
40 +
41 + Future<void> _guard(Future<void> Function() work) async {
42 + try {
43 + await work();
44 + error = null;
45 + } catch (_) {
46 + status = null;
47 + error =
48 + 'وضعیت یادآوری تأیید نشد. تنظیمات و مجوز اعلان را بررسی کن و دوباره تلاش کن.';
49 + try {
50 + await _port.cancelOnStorageFailure();
51 + } catch (_) {/* Error remains visible. */}
52 + rethrow;
53 + } finally {
54 + notifyListeners();
55 + }
56 + }
57 +
58 + Future<void> refresh(StandaloneStore store) => _guard(() async {
59 + if (_changing) return;
60 + final revision = _revision;
61 + final profile = await store.profile();
62 + if (_changing || revision != _revision) return;
63 + if (profile == null) {
64 + await _port.suspendUntilReconcile();
65 + status = await _port.status();
66 + return;
67 + }
68 + final (owner, rows) = await _read(store);
69 + if (_changing || revision != _revision) return;
70 + status = await _port.reconcile(rows,
71 + companionName: owner.companionName, profileId: owner.id);
72 + });
73 +
74 + Future<void> beforeChange(StandaloneStore store) {
75 + _changing = true;
76 + ++_revision;
77 + return _guard(() async {
78 + final profile = await store.profile();
79 + await _port.suspendUntilReconcile(profileId: profile?.id);
80 + status = null;
81 + });
82 + }
83 +
84 + Future<void> afterChange(StandaloneStore store) {
85 + _changing = false;
86 + ++_revision;
87 + return refresh(store);
88 + }
89 +
90 + Future<void> enable(StandaloneStore store) => _guard(() async {
91 + if (_changing) throw StateError('A planner write is in progress.');
92 + final (owner, rows) = await _read(store);
93 + status = await _port.enable(rows,
94 + companionName: owner.companionName, profileId: owner.id);
95 + });
96 +
97 + Future<void> disable(StandaloneStore store) => _guard(() async {
98 + final profile = await store.profile();
99 + if (profile == null) throw StateError('No local profile.');
100 + await _port.disable(profileId: profile.id);
101 + status = await _port.status(profileId: profile.id);
102 + });
103 +
104 + Future<void> requestExactAccess(StandaloneStore store) => _guard(() async {
105 + await _port.requestExactAlarmAccess();
106 + // Returning from Android settings triggers another fresh read on resume.
107 + await refresh(store);
108 + });
109 +
110 + Future<void> cancelOnStorageFailure() => _port.cancelOnStorageFailure();
111 +}
apps/lifemate/lib/standalone/reminder_settings.dart new
+128
@@ -0,0 +1,128 @@
1 +import 'package:flutter/material.dart';
2 +
3 +import 'reminder_coordinator.dart';
4 +import 'reminders.dart';
5 +import 'store.dart';
6 +
7 +class StandaloneReminderSettings extends StatefulWidget {
8 + const StandaloneReminderSettings(
9 + {super.key, required this.store, required this.coordinator});
10 + final StandaloneStore store;
11 + final StandaloneReminderCoordinator coordinator;
12 + @override
13 + State<StandaloneReminderSettings> createState() =>
14 + _StandaloneReminderSettingsState();
15 +}
16 +
17 +class _StandaloneReminderSettingsState extends State<StandaloneReminderSettings>
18 + with WidgetsBindingObserver {
19 + bool _busy = false;
20 + @override
21 + void initState() {
22 + super.initState();
23 + WidgetsBinding.instance.addObserver(this);
24 + _run(() => widget.coordinator.refresh(widget.store));
25 + }
26 +
27 + @override
28 + void dispose() {
29 + WidgetsBinding.instance.removeObserver(this);
30 + super.dispose();
31 + }
32 +
33 + @override
34 + void didChangeAppLifecycleState(AppLifecycleState state) {
35 + if (state == AppLifecycleState.resumed && !_busy) {
36 + _run(() => widget.coordinator.refresh(widget.store));
37 + }
38 + }
39 +
40 + Future<void> _run(Future<void> Function() work) async {
41 + if (_busy) return;
42 + setState(() => _busy = true);
43 + try {
44 + await work();
45 + } catch (_) {/* Coordinator shows a safe Persian error. */} finally {
46 + if (mounted) setState(() => _busy = false);
47 + }
48 + }
49 +
50 + @override
51 + Widget build(BuildContext context) => AnimatedBuilder(
52 + animation: widget.coordinator,
53 + builder: (context, _) {
54 + final state = widget.coordinator.status;
55 + return Scaffold(
56 + appBar: AppBar(title: const Text('یادآوری‌های من')),
57 + body: SafeArea(
58 + child: ListView(padding: const EdgeInsets.all(20), children: [
59 + const Text('یادآوری روی همین گوشی',
60 + style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
61 + const SizedBox(height: 12),
62 + const Text(
63 + 'با اجازهٔ تو، نام همراهت و یک پیام عمومی نمایش داده می‌شود. عنوان خصوصی برنامه روی اعلان نمی‌آید. اینترنت و سرور لازم نیست.'),
64 + const SizedBox(height: 16),
65 + if (widget.coordinator.error != null)
66 + Card(
67 + child: Padding(
68 + padding: const EdgeInsets.all(16),
69 + child: Text(widget.coordinator.error!))),
70 + if (_busy)
71 + const LinearProgressIndicator(
72 + semanticsLabel: 'در حال بررسی یادآوری'),
73 + if (state != null && !state.supported)
74 + const Text(
75 + 'یادآوری در این محیط در دسترس نیست؛ برنامه‌ها همچنان روی گوشی ذخیره می‌شوند.'),
76 + if (state != null && state.supported) ...[
77 + SwitchListTile.adaptive(
78 + title: const Text('اعلان برنامه‌های من'),
79 + subtitle: Text(
80 + state.enabled ? 'انتخاب تو: روشن' : 'انتخاب تو: خاموش'),
81 + value: state.enabled,
82 + onChanged: _busy
83 + ? null
84 + : (value) => _run(() => value
85 + ? widget.coordinator.enable(widget.store)
86 + : widget.coordinator.disable(widget.store)),
87 + ),
88 + Text(state.permissionGranted
89 + ? 'مجوز اعلان: داده شده'
90 + : 'مجوز اعلان: داده نشده؛ برای اجازه دادن، اعلان را روشن کن.'),
91 + const SizedBox(height: 12),
92 + Text('یادآوری آیندهٔ زمان‌بندی‌شده: ${state.scheduledCount}'),
93 + Text(state.timing == 'exact'
94 + ? 'زمان‌بندی دقیق در دسترس است.'
95 + : 'زمان‌بندی تقریبی است؛ ممکن است اندروید اعلان را با تأخیر نشان دهد.'),
96 + if (state.exactAlarmSupported && !state.canScheduleExactAlarms)
97 + OutlinedButton.icon(
98 + onPressed: _busy
99 + ? null
100 + : () => _run(() => widget.coordinator
101 + .requestExactAccess(widget.store)),
102 + icon: const Icon(Icons.alarm),
103 + label: const Text('بررسی اجازهٔ زمان‌بندی دقیق')),
104 + ],
105 + const SizedBox(height: 20),
106 + const Text('پوشش یادآوری',
107 + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
108 + const Text(
109 + 'تا ۲۸ روز آینده و حداکثر ۱۲۸ نوبت نزدیک‌تر آماده می‌شود. برنامه را مرتب باز کن تا روزهای بعد هم آماده شوند. برای هر برنامه، زمان یادآوری را جدا انتخاب کن.'),
110 + if (state != null &&
111 + state.eligibleCount > StandaloneReminderStatus.maximumReminders)
112 + const Text(
113 + 'تعداد نوبت‌ها بیشتر از ظرفیت است؛ فعلاً فقط ۱۲۸ نوبت نزدیک‌تر آماده شده‌اند.'),
114 + const SizedBox(height: 12),
115 + const Text(
116 + 'خاموش‌کردن اجباری برنامه، تنظیم باتری، بی‌صدا بودن گوشی و مجوزهای اندروید می‌توانند اعلان یا صدای آن را متوقف کنند. اعلان زمان‌بندی‌شده تضمین شنیدن آلارم نیست.'),
117 + const SizedBox(height: 16),
118 + OutlinedButton.icon(
119 + onPressed: _busy
120 + ? null
121 + : () =>
122 + _run(() => widget.coordinator.refresh(widget.store)),
123 + icon: const Icon(Icons.refresh),
124 + label: const Text('بررسی دوباره')),
125 + ])),
126 + );
127 + });
128 +}
apps/lifemate/lib/standalone/settings_ui.dart new
+348
@@ -0,0 +1,348 @@
1 +import 'package:flutter/material.dart';
2 +
3 +import 'model.dart';
4 +import 'store.dart';
5 +
6 +const _localNotice =
7 + 'نسخهٔ شخصی این گوشی · بدون حساب و سرور\nبرنامه‌ها فقط روی همین گوشی نگه‌داری می‌شوند. همگام‌سازی، مشاهدهٔ خانواده و بازیابی از سرور ندارد. حذف برنامه یا پاک کردن داده‌های آن، برنامه‌های ذخیره‌شده را از بین می‌برد.';
8 +
9 +String categoryLabel(StandaloneProfileCategory category) => switch (category) {
10 + StandaloneProfileCategory.girlMinor => 'دختر',
11 + StandaloneProfileCategory.boyMinor => 'پسر',
12 + StandaloneProfileCategory.adult => 'بزرگسال',
13 + };
14 +
15 +class StandaloneOnboarding extends StatefulWidget {
16 + const StandaloneOnboarding(
17 + {super.key, required this.store, required this.onSaved});
18 + final StandaloneStore store;
19 + final Future<void> Function() onSaved;
20 +
21 + @override
22 + State<StandaloneOnboarding> createState() => _StandaloneOnboardingState();
23 +}
24 +
25 +class _StandaloneOnboardingState extends State<StandaloneOnboarding> {
26 + final _name = TextEditingController();
27 + StandaloneProfileCategory? _category;
28 + bool _busy = false;
29 + bool _committed = false;
30 + String? _error;
31 +
32 + @override
33 + void dispose() {
34 + _name.dispose();
35 + super.dispose();
36 + }
37 +
38 + Future<void> _save() async {
39 + if (_busy) return;
40 + if (_name.text.trim().isEmpty || _category == null) {
41 + setState(() => _error = 'نام دلخواه و گروه خودت را انتخاب کن.');
42 + return;
43 + }
44 + setState(() {
45 + _busy = true;
46 + _error = null;
47 + });
48 + try {
49 + if (!_committed) {
50 + await widget.store.createProfile(
51 + displayName: _name.text.trim(), category: _category!);
52 + _committed = true;
53 + }
54 + } catch (_) {
55 + if (mounted) {
56 + setState(() => _error =
57 + 'نام روی این گوشی ذخیره نشد. فضای خالی گوشی را بررسی کن و دوباره تلاش کن.');
58 + }
59 + return;
60 + } finally {
61 + if (mounted) setState(() => _busy = false);
62 + }
63 + try {
64 + await widget.onSaved();
65 + } catch (_) {
66 + if (mounted) {
67 + setState(() => _error =
68 + 'نام روی این گوشی ذخیره شد؛ باز کردن برنامه انجام نشد. دوباره تلاش کن.');
69 + }
70 + }
71 + }
72 +
73 + @override
74 + Widget build(BuildContext context) => Scaffold(
75 + body: SafeArea(
76 + child: Center(
77 + child: ConstrainedBox(
78 + constraints: const BoxConstraints(maxWidth: 560),
79 + child: ListView(
80 + padding: const EdgeInsets.all(24),
81 + children: [
82 + const SizedBox(height: 24),
83 + Icon(Icons.spa_outlined,
84 + size: 56, color: Theme.of(context).colorScheme.primary),
85 + const SizedBox(height: 20),
86 + Text('جای کوچکی برای برنامه‌های تو',
87 + style: Theme.of(context).textTheme.headlineSmall,
88 + textAlign: TextAlign.center),
89 + const SizedBox(height: 12),
90 + const Text(
91 + 'قدم‌های امروزت را بنویس و هر کدام را که انجام دادی تیک بزن.',
92 + textAlign: TextAlign.center),
93 + const SizedBox(height: 24),
94 + const _LocalNoticeCard(),
95 + const SizedBox(height: 24),
96 + TextField(
97 + controller: _name,
98 + enabled: !_busy && !_committed,
99 + maxLength: 60,
100 + textInputAction: TextInputAction.done,
101 + decoration: const InputDecoration(
102 + labelText: 'دوست داری چه صدایت کنیم؟',
103 + hintText: 'نام دلخواه'),
104 + ),
105 + const SizedBox(height: 16),
106 + DropdownButtonFormField<StandaloneProfileCategory>(
107 + initialValue: _category,
108 + itemHeight: null,
109 + isExpanded: true,
110 + decoration: const InputDecoration(labelText: 'گروه من'),
111 + items: StandaloneProfileCategory.values
112 + .map((category) => DropdownMenuItem(
113 + value: category,
114 + child: Text(categoryLabel(category))))
115 + .toList(),
116 + onChanged: _busy || _committed
117 + ? null
118 + : (value) => setState(() => _category = value),
119 + ),
120 + const SizedBox(height: 10),
121 + const Text(
122 + 'این انتخاب فقط برای شخصی‌سازی است؛ نقش خانوادگی یا حساب کاربری ایجاد نمی‌کند.'),
123 + if (_error != null) ...[
124 + const SizedBox(height: 16),
125 + Text(_error!,
126 + key: const Key('onboarding-error'),
127 + style: TextStyle(
128 + color: Theme.of(context).colorScheme.error)),
129 + ],
130 + const SizedBox(height: 24),
131 + FilledButton(
132 + onPressed: _busy ? null : _save,
133 + child: Text(_busy
134 + ? 'در حال ذخیره…'
135 + : _committed
136 + ? 'باز کردن برنامهٔ من'
137 + : 'شروع برنامهٔ من'),
138 + ),
139 + ],
140 + ),
141 + ),
142 + ),
143 + ),
144 + );
145 +}
146 +
147 +class StandaloneSettings extends StatefulWidget {
148 + const StandaloneSettings({
149 + super.key,
150 + required this.store,
151 + required this.profile,
152 + required this.onSaved,
153 + this.reminderSettings,
154 + this.onBeforeChange,
155 + this.onAfterChange,
156 + });
157 + final StandaloneStore store;
158 + final StandaloneProfile profile;
159 + final Future<void> Function() onSaved;
160 + final Widget? reminderSettings;
161 + final Future<void> Function()? onBeforeChange;
162 + final Future<void> Function()? onAfterChange;
163 +
164 + @override
165 + State<StandaloneSettings> createState() => _StandaloneSettingsState();
166 +}
167 +
168 +class _StandaloneSettingsState extends State<StandaloneSettings> {
169 + late final TextEditingController _name;
170 + late final TextEditingController _companion;
171 + late StandaloneProfileCategory _category;
172 + late String _theme;
173 + bool _busy = false;
174 + String? _error;
175 +
176 + @override
177 + void initState() {
178 + super.initState();
179 + _name = TextEditingController(text: widget.profile.displayName);
180 + _companion = TextEditingController(text: widget.profile.companionName);
181 + _category = widget.profile.category;
182 + _theme = StandaloneProfile.themeKeys.contains(widget.profile.themeKey)
183 + ? widget.profile.themeKey
184 + : 'violet';
185 + }
186 +
187 + @override
188 + void dispose() {
189 + _name.dispose();
190 + _companion.dispose();
191 + super.dispose();
192 + }
193 +
194 + Future<void> _save() async {
195 + if (_busy) return;
196 + if (_name.text.trim().isEmpty) {
197 + setState(() => _error = 'نام دلخواهت را بنویس.');
198 + return;
199 + }
200 + if (_companion.text.trim().isEmpty) {
201 + setState(() => _error = 'یک نام برای همراه انتخاب کن.');
202 + return;
203 + }
204 + setState(() {
205 + _busy = true;
206 + _error = null;
207 + });
208 + try {
209 + await widget.onBeforeChange?.call();
210 + await widget.store.updateProfile(
211 + displayName: _name.text.trim(),
212 + companionName: _companion.text.trim(),
213 + category: _category,
214 + themeKey: _theme,
215 + );
216 + } catch (_) {
217 + try {
218 + await widget.onAfterChange?.call();
219 + } catch (_) {/* Original save error remains visible. */}
220 + if (mounted) {
221 + setState(() {
222 + _busy = false;
223 + _error = 'تغییرها ذخیره نشد. فضای گوشی را بررسی کن و دوباره تلاش کن.';
224 + });
225 + }
226 + return;
227 + }
228 + // A reminder failure after the durable write must never invite duplicate saves.
229 + bool reminderFailed = false;
230 + try {
231 + await widget.onAfterChange?.call();
232 + } catch (_) {
233 + reminderFailed = true;
234 + }
235 + bool refreshFailed = false;
236 + try {
237 + await widget.onSaved();
238 + } catch (_) {
239 + refreshFailed = true;
240 + }
241 + if (!mounted) return;
242 + setState(() => _busy = false);
243 + ScaffoldMessenger.of(context).showSnackBar(SnackBar(
244 + content: Text(refreshFailed
245 + ? 'تغییرها ذخیره شد؛ برای دیدن تغییرها برنامه را دوباره باز کن.'
246 + : reminderFailed
247 + ? 'تغییرها ذخیره شد؛ وضعیت یادآوری را در تنظیمات بررسی کن.'
248 + : 'تغییرها روی این گوشی ذخیره شد.')));
249 + }
250 +
251 + @override
252 + Widget build(BuildContext context) => ListView(
253 + padding: const EdgeInsets.all(20),
254 + children: [
255 + Text('تنظیمات من', style: Theme.of(context).textTheme.headlineSmall),
256 + const SizedBox(height: 16),
257 + const _LocalNoticeCard(),
258 + const SizedBox(height: 24),
259 + TextField(
260 + controller: _name,
261 + enabled: !_busy,
262 + maxLength: 60,
263 + decoration: const InputDecoration(labelText: 'نام من')),
264 + const SizedBox(height: 16),
265 + TextField(
266 + controller: _companion,
267 + enabled: !_busy,
268 + maxLength: 40,
269 + decoration: const InputDecoration(
270 + labelText: 'نام دلخواه همراه',
271 + helperText: 'فقط یک نام شخصی روی همین گوشی است.')),
272 + const SizedBox(height: 16),
273 + DropdownButtonFormField<StandaloneProfileCategory>(
274 + initialValue: _category,
275 + itemHeight: null,
276 + isExpanded: true,
277 + decoration: const InputDecoration(labelText: 'گروه من'),
278 + items: StandaloneProfileCategory.values
279 + .map((category) => DropdownMenuItem(
280 + value: category, child: Text(categoryLabel(category))))
281 + .toList(),
282 + onChanged:
283 + _busy ? null : (value) => setState(() => _category = value!),
284 + ),
285 + const SizedBox(height: 20),
286 + const Text('رنگ دلخواه؛ برای همهٔ گروه‌ها'),
287 + const SizedBox(height: 8),
288 + Wrap(spacing: 12, runSpacing: 8, children: [
289 + ChoiceChip(
290 + avatar: const CircleAvatar(backgroundColor: Color(0xff76609a)),
291 + label: const Text('بنفش آرام'),
292 + selected: _theme == 'violet',
293 + onSelected:
294 + _busy ? null : (_) => setState(() => _theme = 'violet')),
295 + ChoiceChip(
296 + avatar: const CircleAvatar(backgroundColor: Color(0xff276e83)),
297 + label: const Text('آبی دریا'),
298 + selected: _theme == 'blue',
299 + onSelected:
300 + _busy ? null : (_) => setState(() => _theme = 'blue')),
301 + ChoiceChip(
302 + avatar: const CircleAvatar(backgroundColor: Color(0xff397b65)),
303 + label: const Text('سبز نعنایی'),
304 + selected: _theme == 'mint',
305 + onSelected:
306 + _busy ? null : (_) => setState(() => _theme = 'mint')),
307 + ChoiceChip(
308 + avatar: const CircleAvatar(backgroundColor: Color(0xffad5c4c)),
309 + label: const Text('مرجانی گرم'),
310 + selected: _theme == 'coral',
311 + onSelected:
312 + _busy ? null : (_) => setState(() => _theme = 'coral')),
313 + ]),
314 + if (_error != null) ...[
315 + const SizedBox(height: 16),
316 + Text(_error!,
317 + style: TextStyle(color: Theme.of(context).colorScheme.error)),
318 + ],
319 + const SizedBox(height: 20),
320 + FilledButton(
321 + onPressed: _busy ? null : _save,
322 + child: Text(_busy ? 'در حال ذخیره…' : 'ذخیرهٔ تغییرها')),
323 + const SizedBox(height: 24),
324 + if (widget.reminderSettings != null) widget.reminderSettings!,
325 + const SizedBox(height: 24),
326 + const Text(
327 + 'تغییر نام، گروه یا رنگ، برنامه‌های قبلی را پاک نمی‌کند. برای حفظ داده‌ها، برنامه یا داده‌های آن را از تنظیمات گوشی حذف نکن.'),
328 + ],
329 + );
330 +}
331 +
332 +class _LocalNoticeCard extends StatelessWidget {
333 + const _LocalNoticeCard();
334 +
335 + @override
336 + Widget build(BuildContext context) => Card(
337 + margin: EdgeInsets.zero,
338 + child: Padding(
339 + padding: const EdgeInsets.all(16),
340 + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
341 + Icon(Icons.phone_android_outlined,
342 + color: Theme.of(context).colorScheme.primary),
343 + const SizedBox(width: 12),
344 + const Expanded(child: Text(_localNotice)),
345 + ]),
346 + ),
347 + );
348 +}
apps/lifemate/lib/standalone_main.dart new
+46
@@ -0,0 +1,46 @@
1 +import 'package:flutter/foundation.dart';
2 +import 'package:flutter/material.dart';
3 +
4 +import 'standalone/app.dart';
5 +import 'standalone/reminder_coordinator.dart';
6 +import 'standalone/reminder_settings.dart';
7 +import 'standalone/store.dart';
8 +
9 +/// Separate debug-only device edition. No HTTP/auth/runtime-URL imports.
10 +void main() {
11 + WidgetsFlutterBinding.ensureInitialized();
12 + if (!const bool.fromEnvironment('LIFEGUIDE_STANDALONE') ||
13 + !kDebugMode ||
14 + kIsWeb ||
15 + defaultTargetPlatform != TargetPlatform.android) {
16 + runApp(const MaterialApp(
17 + home: Scaffold(
18 + body: Center(
19 + child: Text(
20 + 'این ورودی فقط برای بستهٔ آزمایشی لایف‌گاید شخصی است.')))));
21 + return;
22 + }
23 + final reminders = StandaloneReminderCoordinator();
24 + runApp(StandaloneApp(
25 + openStore: () async {
26 + StandaloneStore store;
27 + try {
28 + store = await StandaloneStore.open();
29 + } catch (_) {
30 + try {
31 + await reminders.cancelOnStorageFailure();
32 + } catch (_) {/* No success claimed. */}
33 + rethrow;
34 + }
35 + try {
36 + await reminders.refresh(store);
37 + } catch (_) {/* Planner remains usable; settings shows the failure. */}
38 + return store;
39 + },
40 + onBeforePlansChange: reminders.beforeChange,
41 + onPlansChanged: reminders.afterChange,
42 + onResumed: reminders.refresh,
43 + reminderSettingsBuilder: (context, store) =>
44 + StandaloneReminderSettings(store: store, coordinator: reminders),
45 + ));
46 +}
apps/lifemate/test/standalone_coordinator_test.dart new
+118
@@ -0,0 +1,118 @@
1 +import 'dart:io';
2 +
3 +import 'package:flutter/foundation.dart';
4 +import 'package:flutter/services.dart';
5 +import 'package:flutter_test/flutter_test.dart';
6 +import 'package:lifemate/standalone/model.dart';
7 +import 'package:lifemate/standalone/reminder_coordinator.dart';
8 +import 'package:lifemate/standalone/reminders.dart';
9 +import 'package:lifemate/standalone/store.dart';
10 +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
11 +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
12 +import 'package:sqflite_common_ffi/sqflite_ffi.dart';
13 +
14 +void main() {
15 + TestWidgetsFlutterBinding.ensureInitialized();
16 + setUpAll(sqfliteFfiInit);
17 + late Directory directory;
18 + late StandaloneStore store;
19 + late StandaloneReminderCoordinator coordinator;
20 + final now = DateTime(2026, 10, 19, 8);
21 + final calls = <String>[];
22 + bool enabled = false, active = false;
23 + List<dynamic> rows = [];
24 + setUp(() async {
25 + debugDefaultTargetPlatformOverride = TargetPlatform.android;
26 + SharedPreferencesAsyncPlatform.instance =
27 + InMemorySharedPreferencesAsync.empty();
28 + calls.clear();
29 + enabled = false;
30 + active = false;
31 + rows = [];
32 + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
33 + .setMockMethodCallHandler(
34 + const MethodChannel('lifeguide/device_planner_reminders'),
35 + (call) async {
36 + calls.add(call.method);
37 + if (call.method == 'setEnabled') {
38 + enabled = (call.arguments as Map)['enabled'] == true;
39 + }
40 + if (call.method == 'activate') active = true;
41 + if (call.method == 'deactivate') {
42 + active = false;
43 + rows = [];
44 + }
45 + if (call.method == 'replace') {
46 + rows = (call.arguments as Map)['reminders'] as List;
47 + }
48 + if (['status', 'requestPermission', 'requestExactAlarmAccess']
49 + .contains(call.method)) {
50 + return {
51 + 'supported': true,
52 + 'enabled': enabled,
53 + 'permissionGranted': true,
54 + 'active': active,
55 + 'scheduledCount': rows.length,
56 + 'timing': 'approximate'
57 + };
58 + }
59 + return true;
60 + });
61 + directory = await Directory.systemTemp.createTemp('lifeguide-coordinator-');
62 + store = await StandaloneStore.open(
63 + path: '${directory.path}/planner.sqlite', factory: databaseFactoryFfi);
64 + await store.createProfile(
65 + displayName: 'نمونه ساختگی',
66 + category: StandaloneProfileCategory.girlMinor);
67 + await store.createPlan(StandalonePlanDraft(
68 + title: 'عنوان خصوصی ساختگی',
69 + kind: StandalonePlanKind.task,
70 + recurrence: StandaloneRecurrence.once,
71 + startDate: now,
72 + startMinute: 600,
73 + endMinute: 660,
74 + reminderMinutes: 5));
75 + coordinator = StandaloneReminderCoordinator(
76 + port: StandaloneReminderPort(now: () => now), now: () => now);
77 + });
78 + tearDown(() async {
79 + coordinator.dispose();
80 + await store.close();
81 + await directory.delete(recursive: true);
82 + debugDefaultTargetPlatformOverride = null;
83 + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
84 + .setMockMethodCallHandler(
85 + const MethodChannel('lifeguide/device_planner_reminders'), null);
86 + });
87 + test(
88 + 'startup is OFF; committed row schedules without private title; completion cancels',
89 + () async {
90 + await coordinator.refresh(store);
91 + expect(coordinator.status!.enabled, isFalse);
92 + expect(calls, isNot(contains('requestPermission')));
93 + await coordinator.enable(store);
94 + expect(rows, hasLength(1));
95 + expect(rows.single.toString(), isNot(contains('عنوان خصوصی')));
96 + final occurrence =
97 + (await store.occurrences(from: now, through: now)).single;
98 + expect((rows.single as Map)['id'], occurrence.id);
99 + await coordinator.beforeChange(store);
100 + expect(active, isFalse);
101 + await coordinator.refresh(store);
102 + expect(active, isFalse,
103 + reason: 'resume cannot restore alarms during a write');
104 + await store.updateOccurrence(occurrence.id, completed: true);
105 + await coordinator.afterChange(store);
106 + expect(rows, isEmpty);
107 + expect(coordinator.status!.enabled, isTrue);
108 + });
109 + test('failed authoritative read cancels old alarms and exposes an error',
110 + () async {
111 + await coordinator.enable(store);
112 + expect(rows, hasLength(1));
113 + await store.close();
114 + await expectLater(coordinator.refresh(store), throwsA(anything));
115 + expect(active, isFalse);
116 + expect(coordinator.error, isNotNull);
117 + });
118 +}
apps/lifemate/test/standalone_ui_test.dart new
+363
@@ -0,0 +1,363 @@
1 +import 'dart:io';
2 +
3 +import 'package:flutter/material.dart';
4 +import 'package:flutter/services.dart';
5 +import 'package:flutter_test/flutter_test.dart';
6 +import 'package:lifemate/standalone/app.dart';
7 +import 'package:lifemate/standalone/model.dart';
8 +import 'package:lifemate/standalone/settings_ui.dart';
9 +import 'package:lifemate/standalone/store.dart';
10 +import 'package:sqflite_common_ffi/sqflite_ffi.dart';
11 +
12 +void main() {
13 + late Directory directory;
14 + late String path;
15 + late StandaloneStore store;
16 +
17 + setUpAll(() async {
18 + sqfliteFfiInit();
19 + await (FontLoader('LifeGuidePersian')
20 + ..addFont(rootBundle.load('assets/fonts/LifeGuidePersian.ttf')))
21 + .load();
22 + });
23 + setUp(() async {
24 + directory = await Directory.systemTemp.createTemp('lifeguide-ui-');
25 + path = '${directory.path}/planner.sqlite';
26 + // The same SQLite engine and schema as Android, without a background
27 + // isolate so widget-test fake time does not stall a database message.
28 + store = await StandaloneStore.open(
29 + path: path, factory: databaseFactoryFfiNoIsolate);
30 + });
31 + tearDown(() async {
32 + await store.close();
33 + await directory.delete(recursive: true);
34 + });
35 +
36 + Future<void> idle(WidgetTester tester) async {
37 + var idleFrames = 0;
38 + for (var i = 0; i < 500; i++) {
39 + await Future<void>.delayed(const Duration(milliseconds: 10));
40 + await tester.pumpAndSettle();
41 + final busy =
42 + find.byType(CircularProgressIndicator).evaluate().isNotEmpty ||
43 + find.text('در حال ذخیره…').evaluate().isNotEmpty;
44 + idleFrames = busy ? 0 : idleFrames + 1;
45 + if (idleFrames >= 3) return;
46 + }
47 + fail('SQLite-backed UI did not become idle.');
48 + }
49 +
50 + Future<void> open(WidgetTester tester,
51 + {Future<void> Function(StandaloneStore)? before,
52 + Future<void> Function(StandaloneStore)? after}) async {
53 + await tester.pumpWidget(StandaloneApp(
54 + openStore: () async => store,
55 + onBeforePlansChange: before,
56 + onPlansChanged: after));
57 + await idle(tester);
58 + }
59 +
60 + Future<void> tap(WidgetTester tester, Finder target) async {
61 + FocusManager.instance.primaryFocus?.unfocus();
62 + if (find.byType(SnackBar).evaluate().isNotEmpty) {
63 + // Dismiss the prior transient result before the next independent action.
64 + ScaffoldMessenger.of(tester.element(find.byType(SnackBar)))
65 + .removeCurrentSnackBar();
66 + }
67 + await tester.pumpAndSettle();
68 + if (target.evaluate().isEmpty) {
69 + await tester.scrollUntilVisible(target, 200,
70 + scrollable: find.byType(Scrollable).first, maxScrolls: 30);
71 + }
72 + await tester.ensureVisible(target);
73 + await tester.pumpAndSettle();
74 + await tester.tap(target);
75 + await idle(tester);
76 + }
77 +
78 + Future<void> chooseRepeat(WidgetTester tester, String label) async {
79 + await tap(tester, find.byKey(const Key('plan-recurrence')));
80 + await tap(tester, find.text(label).last);
81 + }
82 +
83 + Future<void> profile() => store.createProfile(
84 + displayName: 'کاربر ساختگی',
85 + category: StandaloneProfileCategory.girlMinor);
86 +
87 + Future<void> seedDaily() async {
88 + await profile();
89 + await store.createPlan(StandalonePlanDraft(
90 + title: 'برنامهٔ آزمایشی',
91 + kind: StandalonePlanKind.task,
92 + recurrence: StandaloneRecurrence.daily,
93 + startDate: StandaloneDate.only(DateTime.now()),
94 + startMinute: 540,
95 + endMinute: 600));
96 + }
97 +
98 + testWidgets('onboarding and daily save commit before reminder reconciliation',
99 + (tester) async {
100 + await tester.runAsync(() async {
101 + final events = <String>[];
102 + await open(tester, before: (actual) async {
103 + events.add('invalidate:${(await actual.listPlans()).length}');
104 + }, after: (actual) async {
105 + events.add('reconcile:${(await actual.listPlans()).length}');
106 + });
107 + expect(find.textContaining('بدون حساب و سرور'), findsOneWidget);
108 + expect(await store.profile(), isNull);
109 + await tester.enterText(find.byType(TextField), 'نام ساختگی');
110 + await tap(tester,
111 + find.byType(DropdownButtonFormField<StandaloneProfileCategory>));
112 + await tap(tester, find.text('دختر').last);
113 + await tap(tester, find.text('شروع برنامهٔ من'));
114 + expect(find.text('سلام نام ساختگی'), findsOneWidget);
115 + expect(await store.listPlans(), isEmpty);
116 + await tap(tester, find.text('برنامهٔ تازه'));
117 + await tester.enterText(
118 + find.byKey(const Key('plan-title')), 'قدم روزانهٔ ساختگی');
119 + await chooseRepeat(tester, 'هر روز');
120 + await tap(tester, find.text('ذخیرهٔ برنامه'));
121 + expect(events, ['invalidate:0', 'reconcile:1']);
122 + expect((await store.listPlans()).single.recurrence,
123 + StandaloneRecurrence.daily);
124 + await tap(tester, find.byType(Checkbox));
125 + final today = StandaloneDate.only(DateTime.now());
126 + final occurrences = await store.occurrences(
127 + from: today, through: StandaloneDate.addDays(today, 1));
128 + expect(occurrences.first.completed, isTrue);
129 + expect(occurrences.last.completed, isFalse);
130 + await tester.pumpWidget(const SizedBox());
131 + await store.close();
132 + store = await StandaloneStore.open(
133 + path: path, factory: databaseFactoryFfiNoIsolate);
134 + await open(tester);
135 + expect(find.text('سلام نام ساختگی'), findsOneWidget);
136 + expect(find.textContaining('۱ از ۱'), findsOneWidget);
137 + expect(tester.takeException(), isNull);
138 + });
139 + });
140 +
141 + testWidgets('one occurrence edit and whole-plan archive preserve other dates',
142 + (tester) async {
143 + await tester.runAsync(() async {
144 + await seedDaily();
145 + await open(tester);
146 + await tap(tester, find.text('شروع'));
147 + await tap(tester, find.text('ویرایش همین نوبت'));
148 + await tester.enterText(
149 + find.byKey(const Key('occurrence-title')), 'عنوان مستقل');
150 + await tap(tester, find.text('ثبت تغییر همین نوبت'));
151 + final today = StandaloneDate.only(DateTime.now());
152 + var items = await store.occurrences(
153 + from: today, through: StandaloneDate.addDays(today, 1));
154 + expect(items.first.title, 'عنوان مستقل');
155 + expect(items.last.title, 'برنامهٔ آزمایشی');
156 + await tap(tester, find.text('انجام شد'));
157 + await tap(tester, find.text('بایگانی…'));
158 + await tap(tester, find.text('کل برنامه و همهٔ نوبت‌های آینده'));
159 + expect(await store.listPlans(), isEmpty);
160 + items = await store.occurrences(
161 + from: today,
162 + through: StandaloneDate.addDays(today, 1),
163 + includeArchived: true);
164 + expect(items.first.completed, isTrue);
165 + expect(items.last.completed, isFalse);
166 + expect(
167 + find.text('برای این روز هنوز برنامه‌ای ننوشته‌ای.'), findsOneWidget);
168 + expect(tester.takeException(), isNull);
169 + });
170 + });
171 +
172 + testWidgets('weekly editor persists different hours for selected weekdays',
173 + (tester) async {
174 + await tester.runAsync(() async {
175 + await profile();
176 + await open(tester);
177 + await tap(tester, find.text('برنامهٔ تازه'));
178 + await tester.enterText(
179 + find.byKey(const Key('plan-title')), 'هفتهٔ ساختگی');
180 + await chooseRepeat(tester, 'روزهای انتخابی هفته');
181 + await tap(tester, find.byKey(const Key('plan-weekday-6')));
182 + await tap(tester, find.byKey(const Key('plan-weekday-7')));
183 + final saturdayHours = find.byKey(const Key('weekly-hours-6'));
184 + await tap(
185 + tester,
186 + find
187 + .descendant(
188 + of: saturdayHours, matching: find.byType(OutlinedButton))
189 + .last);
190 + final fields = find.descendant(
191 + of: find.byType(TimePickerDialog), matching: find.byType(TextField));
192 + await tester.enterText(fields.at(0), '11');
193 + await tester.enterText(fields.at(1), '30');
194 + await tap(tester, find.widgetWithText(TextButton, 'تأیید'));
195 + await tap(tester, find.text('ذخیرهٔ برنامه'));
196 + final plan = (await store.listPlans()).single;
197 + expect(plan.recurrence, StandaloneRecurrence.weekly);
198 + expect(plan.weeklySlots.map((slot) => slot.weekday), [6, 7]);
199 + expect(plan.weeklySlots.map((slot) => slot.endMinute), [690, 600]);
200 + expect(tester.takeException(), isNull);
201 + });
202 + });
203 +
204 + testWidgets(
205 + 'SQLite failure retains editor; committed reminder failure does not',
206 + (tester) async {
207 + await tester.runAsync(() async {
208 + await profile();
209 + final db = await databaseFactoryFfiNoIsolate.openDatabase(path);
210 + await db.execute('''CREATE TRIGGER synthetic_write_failure
211 + BEFORE INSERT ON local_plans BEGIN
212 + SELECT RAISE(ABORT, 'synthetic disk-write failure'); END''');
213 + await open(tester,
214 + after: (_) async => throw StateError('synthetic alarm'));
215 + await tap(tester, find.text('برنامهٔ تازه'));
216 + await tester.enterText(find.byKey(const Key('plan-title')), 'حفظ فرم');
217 + await chooseRepeat(tester, 'یک روز در میان');
218 + await tap(tester, find.text('ذخیرهٔ برنامه'));
219 + expect(await store.listPlans(), isEmpty);
220 + await tester.scrollUntilVisible(find.byKey(const Key('plan-title')), -200,
221 + scrollable: find.byType(Scrollable).first);
222 + expect(
223 + tester
224 + .widget<TextField>(find.byKey(const Key('plan-title')))
225 + .controller!
226 + .text,
227 + 'حفظ فرم');
228 + await tester.scrollUntilVisible(
229 + find.text('برنامه ذخیره نشد. می‌توانی دوباره تلاش کنی.'), 200,
230 + scrollable: find.byType(Scrollable).first);
231 + expect(find.text('برنامه ذخیره نشد. می‌توانی دوباره تلاش کنی.'),
232 + findsOneWidget);
233 + await db.execute('DROP TRIGGER synthetic_write_failure');
234 + await tap(tester, find.text('ذخیرهٔ برنامه'));
235 + expect((await store.listPlans()).single.recurrence,
236 + StandaloneRecurrence.everyTwoDays);
237 + expect(find.byKey(const Key('plan-title')), findsNothing);
238 + expect(
239 + find.text(
240 + 'برنامه ذخیره شد؛ آماده‌سازی یادآوری را در تنظیمات بررسی کن.'),
241 + findsOneWidget);
242 + expect(tester.takeException(), isNull);
243 + });
244 + });
245 +
246 + testWidgets('onboarding reload failure never recreates a committed profile',
247 + (tester) async {
248 + await tester.runAsync(() async {
249 + var reloads = 0;
250 + await tester.pumpWidget(MaterialApp(
251 + home: StandaloneOnboarding(
252 + store: store,
253 + onSaved: () async {
254 + reloads++;
255 + if (reloads == 1) throw StateError('synthetic read failure');
256 + })));
257 + await tester.pumpAndSettle();
258 + await tester.enterText(find.byType(TextField), 'نام محفوظ');
259 + await tap(tester,
260 + find.byType(DropdownButtonFormField<StandaloneProfileCategory>));
261 + await tap(tester, find.text('بزرگسال').last);
262 + await tap(tester, find.text('شروع برنامهٔ من'));
263 + final id = (await store.profile())!.id;
264 + expect(find.textContaining('نام روی این گوشی ذخیره شد'), findsOneWidget);
265 + await tap(tester, find.text('باز کردن برنامهٔ من'));
266 + expect((await store.profile())!.id, id);
267 + expect(reloads, 2);
268 + expect(tester.takeException(), isNull);
269 + });
270 + });
271 +
272 + testWidgets(
273 + '320 wide at 200 percent keeps onboarding, pages and settings usable',
274 + (tester) async {
275 + await tester.runAsync(() async {
276 + tester.view.physicalSize = const Size(320, 740);
277 + tester.view.devicePixelRatio = 1;
278 + tester.platformDispatcher.textScaleFactorTestValue = 2;
279 + addTearDown(tester.view.resetPhysicalSize);
280 + addTearDown(tester.view.resetDevicePixelRatio);
281 + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
282 + await open(tester);
283 + await tester.scrollUntilVisible(find.byType(TextField), 180,
284 + scrollable: find.byType(Scrollable).first);
285 + await tester.enterText(find.byType(TextField), 'نام ساختگی');
286 + await tap(tester,
287 + find.byType(DropdownButtonFormField<StandaloneProfileCategory>));
288 + await tap(tester, find.text('پسر').last);
289 + await tap(tester, find.text('شروع برنامهٔ من'));
290 + expect(tester.takeException(), isNull);
291 + await tap(
292 + tester,
293 + find.descendant(
294 + of: find.byType(NavigationBar), matching: find.text('هفته')));
295 + expect(tester.takeException(), isNull);
296 + await tap(
297 + tester,
298 + find.descendant(
299 + of: find.byType(NavigationBar), matching: find.text('تنظیمات')));
300 + await tap(tester, find.text('سبز نعنایی'));
301 + await tap(tester, find.text('ذخیرهٔ تغییرها'));
302 + expect((await store.profile())!.themeKey, 'mint');
303 + await tap(tester, find.text('مرجانی گرم'));
304 + await tap(tester, find.text('ذخیرهٔ تغییرها'));
305 + expect((await store.profile())!.themeKey, 'coral');
306 + expect(tester.takeException(), isNull);
307 + await tap(
308 + tester,
309 + find.descendant(
310 + of: find.byType(NavigationBar), matching: find.text('امروز')));
311 + await tap(tester, find.text('برنامهٔ تازه'));
312 + await chooseRepeat(tester, 'روزهای انتخابی هفته');
313 + await tap(tester, find.byKey(const Key('plan-weekday-6')));
314 + await tap(tester, find.text('ذخیرهٔ برنامه'));
315 + expect(find.text('یک عنوان برای برنامه بنویس.'), findsOneWidget);
316 + expect(tester.takeException(), isNull);
317 + });
318 + });
319 + testWidgets('resume reads committed plans before reminder reconciliation',
320 + (tester) async {
321 + await tester.runAsync(() async {
322 + await seedDaily();
323 + var resumed = 0;
324 + await tester.pumpWidget(StandaloneApp(
325 + openStore: () async => store,
326 + onResumed: (actual) async {
327 + expect(await actual.listPlans(), hasLength(1));
328 + resumed++;
329 + }));
330 + await idle(tester);
331 + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
332 + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
333 + await idle(tester);
334 + expect(resumed, 1);
335 + expect(tester.takeException(), isNull);
336 + });
337 + });
338 +
339 + testWidgets('failed profile write restores reminders from unchanged SQLite',
340 + (tester) async {
341 + await tester.runAsync(() async {
342 + await profile();
343 + final db = await databaseFactoryFfiNoIsolate.openDatabase(path);
344 + await db.execute(
345 + "CREATE TRIGGER reject_profile BEFORE UPDATE ON local_profiles BEGIN SELECT RAISE(ABORT, 'synthetic write failure'); END");
346 + final events = <String>[];
347 + await open(tester,
348 + before: (_) async => events.add('suspend'),
349 + after: (actual) async =>
350 + events.add('restore:${(await actual.profile())!.displayName}'));
351 + await tap(
352 + tester,
353 + find.descendant(
354 + of: find.byType(NavigationBar), matching: find.text('تنظیمات')));
355 + await tester.enterText(find.byType(TextField).first, 'نام ذخیره نشده');
356 + await tap(tester, find.text('ذخیرهٔ تغییرها'));
357 + expect(events, ['suspend', 'restore:کاربر ساختگی']);
358 + expect((await store.profile())!.displayName, 'کاربر ساختگی');
359 + expect(find.textContaining('تغییرها ذخیره نشد'), findsOneWidget);
360 + expect(tester.takeException(), isNull);
361 + });
362 + });
363 +}