Options fix

clean up and fixes

- Heute gefixt
- Code Cleanup

NotificationScheduleItemViewModel

-fixed NotificationScheduleItemViewModel for Windows compat

push implementation

Push fixes

Push benachrichtungen eingebaut
- Status bei push
- Push auch in background
- Toggle für symtome angepasst

push system change

exporter update

Optionen fix

- Optionen aufgeteilt auf 3 tabs
- Anpassungen haben jetzt Farbslider

Optimierung fix
This commit is contained in:
2026-03-24 23:35:01 +01:00
parent d85f2e0fb3
commit d11f0e46c0
46 changed files with 2362 additions and 517 deletions
+3 -1
View File
@@ -45,6 +45,9 @@ public partial class App : Application
{
window.Page = shell;
});
var navigator = _serviceProvider.GetRequiredService<NotificationNavigationService>();
await navigator.FlushAsync();
}
catch (Exception ex)
{
@@ -56,7 +59,6 @@ public partial class App : Application
});
}
}
private static Page CreateLoadingPage()
{
return new ContentPage
-1
View File
@@ -1,7 +1,6 @@
using cfs_tracker.Models;
using cfs_tracker.Services;
using SQLite;
using System.Threading;
namespace cfs_tracker.Data;
+29 -4
View File
@@ -16,6 +16,7 @@ public class HealthEntryRepository
public async Task<int> AddQuickEntryAsync(
HealthState state,
int? activityId = null,
int? activityDurationMinutes = null,
IEnumerable<int>? symptomIds = null,
DateTime? timestamp = null,
EntrySource source = EntrySource.App)
@@ -23,6 +24,7 @@ public class HealthEntryRepository
await _database.InitAsync();
var effectiveTimestamp = timestamp ?? DateTime.Now;
var entry = new HealthEntry
{
EntryDate = effectiveTimestamp.Date,
@@ -31,12 +33,14 @@ public class HealthEntryRepository
Source = source,
DayPart = null,
ActivityId = NormalizeActivityId(activityId),
ActivityDurationMinutes = NormalizeActivityDuration(activityDurationMinutes),
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now
};
await _database.Connection.InsertAsync(entry);
await _symptomRepository.SetSymptomsForEntryAsync(entry.Id, symptomIds);
return entry.Id;
}
@@ -45,12 +49,14 @@ public class HealthEntryRepository
DayPart part = DayPart.Morning,
HealthState state = HealthState.Gray,
int? activityId = null,
int? activityDurationMinutes = null,
IEnumerable<int>? symptomIds = null,
EntrySource source = EntrySource.Backfill)
{
await _database.InitAsync();
var slotTimestamp = BuildBackfillTimestamp(date, part);
var existing = await _database.Connection.Table<HealthEntry>()
.FirstOrDefaultAsync(x => x.Timestamp == slotTimestamp);
@@ -64,12 +70,14 @@ public class HealthEntryRepository
Source = source,
DayPart = part,
ActivityId = NormalizeActivityId(activityId),
ActivityDurationMinutes = NormalizeActivityDuration(activityDurationMinutes),
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now
};
await _database.Connection.InsertAsync(entry);
await _symptomRepository.SetSymptomsForEntryAsync(entry.Id, symptomIds);
return entry.Id;
}
@@ -79,10 +87,12 @@ public class HealthEntryRepository
existing.Source = source;
existing.DayPart = part;
existing.ActivityId = NormalizeActivityId(activityId);
existing.ActivityDurationMinutes = NormalizeActivityDuration(activityDurationMinutes);
existing.UpdatedAt = DateTime.Now;
await _database.Connection.UpdateAsync(existing);
await _symptomRepository.SetSymptomsForEntryAsync(existing.Id, symptomIds);
return existing.Id;
}
@@ -91,6 +101,7 @@ public class HealthEntryRepository
DateTime date,
HealthState state,
int? activityId = null,
int? activityDurationMinutes = null,
IEnumerable<int>? symptomIds = null,
DayPart? part = null,
EntrySource? source = null)
@@ -103,16 +114,23 @@ public class HealthEntryRepository
if (entry is null)
return;
var originalTimestamp = entry.Timestamp;
entry.EntryDate = date.Date;
entry.State = state;
entry.ActivityId = NormalizeActivityId(activityId);
entry.ActivityDurationMinutes = NormalizeActivityDuration(activityDurationMinutes);
entry.Source = source ?? entry.Source;
entry.DayPart = part;
if (part.HasValue)
{
entry.Timestamp = BuildBackfillTimestamp(date, part.Value);
else if (date.Date != entry.EntryDate.Date)
entry.Timestamp = date.Date + entry.Timestamp.TimeOfDay;
}
else if (originalTimestamp.Date != date.Date)
{
entry.Timestamp = date.Date + originalTimestamp.TimeOfDay;
}
entry.UpdatedAt = DateTime.Now;
@@ -189,5 +207,12 @@ public class HealthEntryRepository
};
private static int? NormalizeActivityId(int? activityId) =>
activityId.HasValue && activityId.Value > 0 ? activityId : null;
}
activityId.HasValue && activityId.Value > 0
? activityId
: null;
private static int? NormalizeActivityDuration(int? activityDurationMinutes) =>
activityDurationMinutes.HasValue && activityDurationMinutes.Value > 0
? activityDurationMinutes
: null;
}
+150 -21
View File
@@ -15,31 +15,160 @@ public class NotificationScheduleRepository
{
await _database.InitAsync();
return await _database.Connection.Table<NotificationSchedule>()
.OrderBy(x => x.DayOfWeekValue)
.ThenBy(x => x.Hour)
.ThenBy(x => x.Minute)
var list = await _database.Connection.Table<NotificationSchedule>()
.ToListAsync();
return list
.OrderBy(x => x.Hour)
.ThenBy(x => x.Minute)
.ThenBy(x => x.Id)
.ToList();
}
public async Task ReplaceAllAsync(IEnumerable<NotificationSchedule> schedules)
public async Task<NotificationSchedule?> GetByIdAsync(int id)
{
await _database.InitAsync();
await _database.Connection.DeleteAllAsync<NotificationSchedule>();
foreach (var schedule in schedules
.OrderBy(x => x.DayOfWeekValue)
.ThenBy(x => x.Hour)
.ThenBy(x => x.Minute))
{
await _database.Connection.InsertAsync(new NotificationSchedule
{
DayOfWeekValue = schedule.DayOfWeekValue,
Hour = schedule.Hour,
Minute = schedule.Minute,
IsEnabled = schedule.IsEnabled
});
}
return await _database.Connection.Table<NotificationSchedule>()
.FirstOrDefaultAsync(x => x.Id == id);
}
}
public async Task<int> AddAsync(
int weekdayMask,
int hour,
int minute,
bool isEnabled = true)
{
await _database.InitAsync();
var item = new NotificationSchedule
{
WeekdayMask = NormalizeWeekdayMask(weekdayMask),
Hour = NormalizeHour(hour),
Minute = NormalizeMinute(minute),
IsEnabled = isEnabled
};
await _database.Connection.InsertAsync(item);
return item.Id;
}
public async Task SaveAsync(NotificationSchedule item)
{
await _database.InitAsync();
if (item is null)
return;
item.WeekdayMask = NormalizeWeekdayMask(item.WeekdayMask);
item.Hour = NormalizeHour(item.Hour);
item.Minute = NormalizeMinute(item.Minute);
if (item.Id <= 0)
{
await _database.Connection.InsertAsync(item);
return;
}
var existing = await _database.Connection.Table<NotificationSchedule>()
.FirstOrDefaultAsync(x => x.Id == item.Id);
if (existing is null)
{
await _database.Connection.InsertAsync(item);
return;
}
existing.WeekdayMask = item.WeekdayMask;
existing.Hour = item.Hour;
existing.Minute = item.Minute;
existing.IsEnabled = item.IsEnabled;
await _database.Connection.UpdateAsync(existing);
}
public async Task DeleteAsync(int id)
{
await _database.InitAsync();
var existing = await _database.Connection.Table<NotificationSchedule>()
.FirstOrDefaultAsync(x => x.Id == id);
if (existing is not null)
await _database.Connection.DeleteAsync(existing);
}
public async Task DeleteAllAsync()
{
await _database.InitAsync();
await _database.Connection.DeleteAllAsync<NotificationSchedule>();
}
public async Task ReplaceAllAsync(IEnumerable<NotificationSchedule>? items)
{
await _database.InitAsync();
var normalized = (items ?? Enumerable.Empty<NotificationSchedule>())
.Select(x => new NotificationSchedule
{
Id = x.Id,
WeekdayMask = NormalizeWeekdayMask(x.WeekdayMask),
Hour = NormalizeHour(x.Hour),
Minute = NormalizeMinute(x.Minute),
IsEnabled = x.IsEnabled
})
.Where(x => x.WeekdayMask != 0)
.OrderBy(x => x.Hour)
.ThenBy(x => x.Minute)
.ThenBy(x => x.Id)
.ToList();
await _database.Connection.RunInTransactionAsync(connection =>
{
connection.DeleteAll<NotificationSchedule>();
foreach (var item in normalized)
{
item.Id = 0;
connection.Insert(item);
}
});
}
private static int NormalizeWeekdayMask(int mask)
{
const int allDaysMask =
(int)(
NotificationWeekdays.Monday |
NotificationWeekdays.Tuesday |
NotificationWeekdays.Wednesday |
NotificationWeekdays.Thursday |
NotificationWeekdays.Friday |
NotificationWeekdays.Saturday |
NotificationWeekdays.Sunday);
return mask & allDaysMask;
}
private static int NormalizeHour(int hour)
{
if (hour < 0)
return 0;
if (hour > 23)
return 23;
return hour;
}
private static int NormalizeMinute(int minute)
{
if (minute < 0)
return 0;
if (minute > 59)
return 59;
return minute;
}
}
-1
View File
@@ -1,5 +1,4 @@
using cfs_tracker.Models;
using System.Linq;
namespace cfs_tracker.Data;
-2
View File
@@ -1,5 +1,3 @@
using Microsoft.Maui.Graphics;
namespace cfs_tracker.Helpers;
public static class ColorUtility
+24
View File
@@ -0,0 +1,24 @@
using cfs_tracker.Models;
namespace cfs_tracker.Helpers;
public static class NotificationWeekdayHelper
{
public static NotificationWeekdays ToFlag(DayOfWeek day) => day switch
{
DayOfWeek.Monday => NotificationWeekdays.Monday,
DayOfWeek.Tuesday => NotificationWeekdays.Tuesday,
DayOfWeek.Wednesday => NotificationWeekdays.Wednesday,
DayOfWeek.Thursday => NotificationWeekdays.Thursday,
DayOfWeek.Friday => NotificationWeekdays.Friday,
DayOfWeek.Saturday => NotificationWeekdays.Saturday,
DayOfWeek.Sunday => NotificationWeekdays.Sunday,
_ => NotificationWeekdays.None
};
public static bool ContainsDay(int mask, DayOfWeek day)
{
var flags = (NotificationWeekdays)mask;
return (flags & ToFlag(day)) != 0;
}
}
+8 -1
View File
@@ -2,9 +2,9 @@ using cfs_tracker.Data;
using cfs_tracker.Services;
using cfs_tracker.ViewModels;
using cfs_tracker.Views;
using Microsoft.Extensions.Logging;
using SQLitePCL;
using System.Text;
using Microsoft.Extensions.Logging;
namespace cfs_tracker;
@@ -41,9 +41,16 @@ public static class MauiProgram
builder.Services.AddSingleton<CalendarStateService>();
builder.Services.AddSingleton<AppearanceService>();
builder.Services.AddSingleton<AggregationService>();
#if ANDROID
builder.Services.AddSingleton<INotificationScheduler, cfs_tracker.Platforms.Android.AndroidNotificationScheduler>();
#elif WINDOWS
builder.Services.AddSingleton<INotificationScheduler, cfs_tracker.Platforms.Windows.WindowsNotificationScheduler>();
#else
builder.Services.AddSingleton<INotificationScheduler, NoOpNotificationScheduler>();
#endif
builder.Services.AddSingleton<IPdfExportService, PdfExportService>();
builder.Services.AddSingleton<AppBootstrapService>();
builder.Services.AddSingleton<NotificationNavigationService>();
// Shell / Pages
builder.Services.AddSingleton<AppShell>();
+1
View File
@@ -25,6 +25,7 @@ public class HealthEntry
[Indexed]
public int? ActivityId { get; set; }
public int? ActivityDurationMinutes { get; set; }
public DateTime CreatedAt { get; set; }
+3 -11
View File
@@ -2,24 +2,16 @@ using SQLite;
namespace cfs_tracker.Models;
[Table("NotificationSchedules")]
public class NotificationSchedule
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int DayOfWeekValue { get; set; }
public int WeekdayMask { get; set; }
public int Hour { get; set; }
public int Minute { get; set; }
public bool IsEnabled { get; set; } = true;
[Ignore]
public DayOfWeek DayOfWeek
{
get => (DayOfWeek)DayOfWeekValue;
set => DayOfWeekValue = (int)value;
}
}
public bool IsEnabled { get; set; }
}
+14
View File
@@ -0,0 +1,14 @@
namespace cfs_tracker.Models;
[Flags]
public enum NotificationWeekdays
{
None = 0,
Monday = 1 << 0,
Tuesday = 1 << 1,
Wednesday = 1 << 2,
Thursday = 1 << 3,
Friday = 1 << 4,
Saturday = 1 << 5,
Sunday = 1 << 6
}
+2 -1
View File
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true"></application>
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:supportsRtl="true"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
</manifest>
@@ -0,0 +1,297 @@
using Android.App;
using Android.Content;
using AndroidX.Core.App;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services;
namespace cfs_tracker.Platforms.Android;
public sealed class AndroidNotificationScheduler : INotificationScheduler
{
private const string ChannelId = "cfs_tracker_reminders";
private const string ChannelName = "Erinnerungen";
private const string ChannelDescription = "Wie geht es dir? Erinnerungen";
private const string PrefScheduledIds = "notification_schedule_ids";
private const string PrefYellowLabel = "notification_label_yellow";
private const string PrefRedLabel = "notification_label_red";
private const string PrefGrayLabel = "notification_label_gray";
public const string ExtraScheduleId = "schedule_id";
public const string ExtraDayOfWeek = "day_of_week";
public const string ExtraHour = "hour";
public const string ExtraMinute = "minute";
public const string ExtraRoute = "route";
public const string ExtraDate = "date";
public const string ExtraStatus = "status";
public const string ExtraCommit = "commit";
private readonly NotificationScheduleRepository _notificationScheduleRepository;
private readonly AppearanceService _appearanceService;
public AndroidNotificationScheduler(
NotificationScheduleRepository notificationScheduleRepository,
AppearanceService appearanceService)
{
_notificationScheduleRepository = notificationScheduleRepository;
_appearanceService = appearanceService;
}
public async Task<bool> EnsurePermissionAsync()
{
var permission = await Permissions.RequestAsync<NotificationPermission>();
return permission == PermissionStatus.Granted;
}
public async Task SyncAsync()
{
var context = Platform.AppContext;
EnsureChannel(context);
var granted = await EnsurePermissionAsync();
if (!granted)
return;
SaveActionLabelsToPreferences();
CancelAllScheduled(context);
var schedules = await _notificationScheduleRepository.GetAllAsync();
var requestKeys = new List<string>();
foreach (var item in schedules.Where(x => x.IsEnabled && x.WeekdayMask != 0))
{
foreach (var day in GetScheduledDays(item.WeekdayMask))
{
ScheduleNextAlarm(context, item.Id, day, item.Hour, item.Minute);
requestKeys.Add($"{item.Id}:{(int)day}");
}
}
Preferences.Default.Set(PrefScheduledIds, string.Join(",", requestKeys));
}
private void SaveActionLabelsToPreferences()
{
Preferences.Default.Set(
PrefYellowLabel,
_appearanceService.GetText(AppearanceKeys.StatusYellowText, "Gelb"));
Preferences.Default.Set(
PrefRedLabel,
_appearanceService.GetText(AppearanceKeys.StatusRedText, "Rot"));
Preferences.Default.Set(
PrefGrayLabel,
_appearanceService.GetText(AppearanceKeys.StatusGrayText, "Schwarz"));
}
internal static void ScheduleNextAlarm(
Context context,
int scheduleId,
DayOfWeek dayOfWeek,
int hour,
int minute)
{
var triggerAt = ComputeNextOccurrence(dayOfWeek, hour, minute);
var alarmManager = (AlarmManager?)context.GetSystemService(Context.AlarmService);
if (alarmManager is null)
return;
var intent = new Intent(context, typeof(CfsNotificationReceiver));
intent.PutExtra(ExtraScheduleId, scheduleId);
intent.PutExtra(ExtraDayOfWeek, (int)dayOfWeek);
intent.PutExtra(ExtraHour, hour);
intent.PutExtra(ExtraMinute, minute);
var requestCode = BuildAlarmRequestCode(scheduleId, dayOfWeek);
var pendingIntent = PendingIntent.GetBroadcast(
context,
requestCode,
intent,
BuildPendingIntentFlags());
var when = triggerAt.ToUnixTimeMilliseconds();
if (OperatingSystem.IsAndroidVersionAtLeast(23))
alarmManager.SetAndAllowWhileIdle(AlarmType.RtcWakeup, when, pendingIntent);
else
alarmManager.Set(AlarmType.RtcWakeup, when, pendingIntent);
}
internal static void ShowNotification(
Context context,
int scheduleId,
string title,
string message)
{
EnsureChannel(context);
var today = DateTime.Today.ToString("yyyy-MM-dd");
var openQuickEntryIntent = BuildLaunchIntent(context, today, null, false);
var yellowIntent = BuildLaunchIntent(context, today, "yellow", true);
var redIntent = BuildLaunchIntent(context, today, "red", true);
var grayIntent = BuildLaunchIntent(context, today, "gray", true);
var openPendingIntent = PendingIntent.GetActivity(
context,
scheduleId * 10 + 1,
openQuickEntryIntent,
BuildPendingIntentFlags());
var yellowPendingIntent = PendingIntent.GetActivity(
context,
scheduleId * 10 + 2,
yellowIntent,
BuildPendingIntentFlags());
var redPendingIntent = PendingIntent.GetActivity(
context,
scheduleId * 10 + 3,
redIntent,
BuildPendingIntentFlags());
var grayPendingIntent = PendingIntent.GetActivity(
context,
scheduleId * 10 + 4,
grayIntent,
BuildPendingIntentFlags());
var yellowLabel = Preferences.Default.Get(PrefYellowLabel, "Gelb");
var redLabel = Preferences.Default.Get(PrefRedLabel, "Rot");
var grayLabel = Preferences.Default.Get(PrefGrayLabel, "Schwarz");
var smallIcon = context.ApplicationInfo?.Icon ?? global::Android.Resource.Drawable.IcDialogInfo;
var builder = new NotificationCompat.Builder(context, ChannelId)
.SetSmallIcon(smallIcon)
.SetContentTitle(title)
.SetContentText(message)
.SetPriority((int)NotificationPriority.High)
.SetAutoCancel(true)
.SetContentIntent(openPendingIntent)
.AddAction(0, yellowLabel, yellowPendingIntent)
.AddAction(0, redLabel, redPendingIntent)
.AddAction(0, grayLabel, grayPendingIntent);
NotificationManagerCompat.From(context).Notify(scheduleId, builder.Build());
}
private static Intent BuildLaunchIntent(Context context, string date, string? status, bool commit)
{
var launchIntent = context.PackageManager?.GetLaunchIntentForPackage(context.PackageName)
?? new Intent(context, typeof(MainActivity));
launchIntent.AddFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop | ActivityFlags.NewTask);
launchIntent.PutExtra(ExtraRoute, "quickentry");
launchIntent.PutExtra(ExtraDate, date);
if (!string.IsNullOrWhiteSpace(status))
launchIntent.PutExtra(ExtraStatus, status);
launchIntent.PutExtra(ExtraCommit, commit);
return launchIntent;
}
internal static void EnsureChannel(Context context)
{
if (!OperatingSystem.IsAndroidVersionAtLeast(26))
return;
var manager = (NotificationManager?)context.GetSystemService(Context.NotificationService);
if (manager is null)
return;
var channel = new NotificationChannel(ChannelId, ChannelName, NotificationImportance.Default)
{
Description = ChannelDescription
};
manager.CreateNotificationChannel(channel);
}
private void CancelAllScheduled(Context context)
{
var stored = Preferences.Default.Get(PrefScheduledIds, string.Empty);
if (string.IsNullOrWhiteSpace(stored))
return;
var alarmManager = (AlarmManager?)context.GetSystemService(Context.AlarmService);
if (alarmManager is null)
return;
foreach (var raw in stored.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var parts = raw.Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length != 2)
continue;
if (!int.TryParse(parts[0], out var scheduleId))
continue;
if (!int.TryParse(parts[1], out var dayValue))
continue;
var day = (DayOfWeek)dayValue;
var requestCode = BuildAlarmRequestCode(scheduleId, day);
var intent = new Intent(context, typeof(CfsNotificationReceiver));
var pendingIntent = PendingIntent.GetBroadcast(
context,
requestCode,
intent,
BuildPendingIntentFlags());
alarmManager.Cancel(pendingIntent);
NotificationManagerCompat.From(context).Cancel(scheduleId);
}
Preferences.Default.Remove(PrefScheduledIds);
}
private static PendingIntentFlags BuildPendingIntentFlags()
{
var flags = PendingIntentFlags.UpdateCurrent;
if (OperatingSystem.IsAndroidVersionAtLeast(23))
flags |= PendingIntentFlags.Immutable;
return flags;
}
private static DateTimeOffset ComputeNextOccurrence(DayOfWeek targetDay, int hour, int minute)
{
var now = DateTimeOffset.Now;
var todayAtTime = new DateTimeOffset(now.Year, now.Month, now.Day, hour, minute, 0, now.Offset);
var days = ((int)targetDay - (int)now.DayOfWeek + 7) % 7;
var target = todayAtTime.AddDays(days);
if (target <= now)
target = target.AddDays(7);
return target;
}
private static int BuildAlarmRequestCode(int scheduleId, DayOfWeek day)
{
return scheduleId * 10 + (int)day;
}
private static IEnumerable<DayOfWeek> GetScheduledDays(int mask)
{
var flags = (NotificationWeekdays)mask;
if (flags.HasFlag(NotificationWeekdays.Monday)) yield return DayOfWeek.Monday;
if (flags.HasFlag(NotificationWeekdays.Tuesday)) yield return DayOfWeek.Tuesday;
if (flags.HasFlag(NotificationWeekdays.Wednesday)) yield return DayOfWeek.Wednesday;
if (flags.HasFlag(NotificationWeekdays.Thursday)) yield return DayOfWeek.Thursday;
if (flags.HasFlag(NotificationWeekdays.Friday)) yield return DayOfWeek.Friday;
if (flags.HasFlag(NotificationWeekdays.Saturday)) yield return DayOfWeek.Saturday;
if (flags.HasFlag(NotificationWeekdays.Sunday)) yield return DayOfWeek.Sunday;
}
}
@@ -0,0 +1,31 @@
using Android.Content;
namespace cfs_tracker.Platforms.Android;
[BroadcastReceiver(Enabled = true, Exported = false)]
public sealed class CfsNotificationReceiver : BroadcastReceiver
{
public override void OnReceive(Context? context, Intent? intent)
{
if (context is null || intent is null)
return;
var scheduleId = intent.GetIntExtra(AndroidNotificationScheduler.ExtraScheduleId, 0);
var dayOfWeek = (DayOfWeek)intent.GetIntExtra(AndroidNotificationScheduler.ExtraDayOfWeek, (int)DayOfWeek.Monday);
var hour = intent.GetIntExtra(AndroidNotificationScheduler.ExtraHour, 9);
var minute = intent.GetIntExtra(AndroidNotificationScheduler.ExtraMinute, 0);
AndroidNotificationScheduler.ShowNotification(
context,
scheduleId,
"Wie geht es dir?",
"Tippe, um deinen Status einzutragen.");
AndroidNotificationScheduler.ScheduleNextAlarm(
context,
scheduleId,
dayOfWeek,
hour,
minute);
}
}
+51 -3
View File
@@ -1,9 +1,57 @@
using Android.App;
using Android.Content.PM;
using Android.OS;
using cfs_tracker.Services;
namespace cfs_tracker;
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
[Activity(
Theme = "@style/Maui.SplashTheme",
MainLauncher = true,
LaunchMode = LaunchMode.SingleTop,
ConfigurationChanges = ConfigChanges.ScreenSize
| ConfigChanges.Orientation
| ConfigChanges.UiMode
| ConfigChanges.ScreenLayout
| ConfigChanges.SmallestScreenSize
| ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle? savedInstanceState){ base.OnCreate(savedInstanceState); }
}
protected override void OnCreate(Bundle? savedInstanceState)
{
base.OnCreate(savedInstanceState);
HandleNotificationIntent(Intent);
}
protected override void OnNewIntent(Android.Content.Intent? intent)
{
base.OnNewIntent(intent);
if (intent is not null)
HandleNotificationIntent(intent);
}
private static void HandleNotificationIntent(Android.Content.Intent? intent)
{
if (intent is null)
return;
var route = intent.GetStringExtra(Platforms.Android.AndroidNotificationScheduler.ExtraRoute);
if (!string.Equals(route, "quickentry", StringComparison.OrdinalIgnoreCase))
return;
var dateText = intent.GetStringExtra(Platforms.Android.AndroidNotificationScheduler.ExtraDate);
var status = intent.GetStringExtra(Platforms.Android.AndroidNotificationScheduler.ExtraStatus);
var commit = intent.GetBooleanExtra(Platforms.Android.AndroidNotificationScheduler.ExtraCommit, false);
if (!DateTime.TryParse(dateText, out var date))
date = DateTime.Today;
var services = IPlatformApplication.Current?.Services;
var navigator = services?.GetService(typeof(NotificationNavigationService)) as NotificationNavigationService;
if (navigator is null)
return;
navigator.QueueQuickEntry(date, status, commit);
_ = navigator.FlushAsync();
}
}
@@ -0,0 +1,19 @@
using Android;
namespace cfs_tracker.Platforms.Android;
public class NotificationPermission : Permissions.BasePlatformPermission
{
public override (string androidPermission, bool isRuntime)[] RequiredPermissions
{
get
{
var result = new List<(string androidPermission, bool isRuntime)>();
if (OperatingSystem.IsAndroidVersionAtLeast(33))
result.Add((Manifest.Permission.PostNotifications, true));
return result.ToArray();
}
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
using Microsoft.UI.Xaml;
using System.Diagnostics;
using System.Diagnostics;
namespace cfs_tracker.WinUI;
@@ -0,0 +1,112 @@
using cfs_tracker.Data;
using cfs_tracker.Models;
using cfs_tracker.Services;
using Microsoft.Toolkit.Uwp.Notifications;
using Windows.UI.Notifications;
namespace cfs_tracker.Platforms.Windows;
public sealed class WindowsNotificationScheduler : INotificationScheduler
{
private const string GroupName = "cfs_tracker_weekly";
private readonly NotificationScheduleRepository _notificationScheduleRepository;
public WindowsNotificationScheduler(NotificationScheduleRepository notificationScheduleRepository)
{
_notificationScheduleRepository = notificationScheduleRepository;
}
public Task<bool> EnsurePermissionAsync()
{
return Task.FromResult(true);
}
public async Task SyncAsync()
{
try
{
CancelExisting();
var schedules = await _notificationScheduleRepository.GetAllAsync();
var notifier = ToastNotificationManagerCompat.CreateToastNotifier();
foreach (var item in schedules.Where(x => x.IsEnabled && x.WeekdayMask != 0))
{
foreach (var day in GetScheduledDays(item.WeekdayMask))
{
var when = ComputeNextOccurrence(day, item.Hour, item.Minute);
var content = new ToastContentBuilder()
.AddArgument("route", "day")
.AddText("Wie geht es dir?")
.AddText("Tippe, um deinen Status einzutragen.")
.GetToastContent();
var scheduled = new ScheduledToastNotification(content.GetXml(), when)
{
Tag = BuildTag(item.Id, day),
Group = GroupName
};
notifier.AddToSchedule(scheduled);
}
}
}
catch
{
// Windows darf hier still ins Leere laufen.
}
}
private static string BuildTag(int id, DayOfWeek day) => $"schedule-{id}-{(int)day}";
private static DateTimeOffset ComputeNextOccurrence(DayOfWeek targetDay, int hour, int minute)
{
var now = DateTimeOffset.Now;
var todayAtTime = new DateTimeOffset(
now.Year,
now.Month,
now.Day,
hour,
minute,
0,
now.Offset);
var days = ((int)targetDay - (int)now.DayOfWeek + 7) % 7;
var target = todayAtTime.AddDays(days);
if (target <= now)
target = target.AddDays(7);
return target;
}
private static void CancelExisting()
{
try
{
var notifier = ToastNotificationManagerCompat.CreateToastNotifier();
var scheduled = notifier.GetScheduledToastNotifications();
foreach (var toast in scheduled.Where(x => x.Group == GroupName).ToList())
notifier.RemoveFromSchedule(toast);
}
catch
{
// bewusst no-op
}
}
private static IEnumerable<DayOfWeek> GetScheduledDays(int mask)
{
var flags = (NotificationWeekdays)mask;
if (flags.HasFlag(NotificationWeekdays.Monday)) yield return DayOfWeek.Monday;
if (flags.HasFlag(NotificationWeekdays.Tuesday)) yield return DayOfWeek.Tuesday;
if (flags.HasFlag(NotificationWeekdays.Wednesday)) yield return DayOfWeek.Wednesday;
if (flags.HasFlag(NotificationWeekdays.Thursday)) yield return DayOfWeek.Thursday;
if (flags.HasFlag(NotificationWeekdays.Friday)) yield return DayOfWeek.Friday;
if (flags.HasFlag(NotificationWeekdays.Saturday)) yield return DayOfWeek.Saturday;
if (flags.HasFlag(NotificationWeekdays.Sunday)) yield return DayOfWeek.Sunday;
}
}
-2
View File
@@ -1,7 +1,5 @@
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Graphics;
namespace cfs_tracker.Services;
-2
View File
@@ -1,5 +1,3 @@
using Microsoft.Maui.Storage;
namespace cfs_tracker.Services;
public class DatabaseLocationService
+1 -3
View File
@@ -1,6 +1,4 @@
using Microsoft.Maui.ApplicationModel;
namespace cfs_tracker.Services;
namespace cfs_tracker.Services;
public static class ExportUiHelper
{
+2 -1
View File
@@ -2,5 +2,6 @@ namespace cfs_tracker.Services;
public interface INotificationScheduler
{
Task SyncAsync(CancellationToken cancellationToken = default);
Task<bool> EnsurePermissionAsync();
Task SyncAsync();
}
+2 -4
View File
@@ -2,8 +2,6 @@ namespace cfs_tracker.Services;
public sealed class NoOpNotificationScheduler : INotificationScheduler
{
public Task SyncAsync(CancellationToken cancellationToken = default)
{
return Task.CompletedTask;
}
public Task<bool> EnsurePermissionAsync() => Task.FromResult(true);
public Task SyncAsync() => Task.CompletedTask;
}
+41
View File
@@ -0,0 +1,41 @@
using cfs_tracker.Views;
namespace cfs_tracker.Services;
public sealed class NotificationNavigationService
{
private string? _pendingDate;
private string? _pendingStatus;
private bool _pendingCommit;
public void QueueQuickEntry(DateTime date, string? status = null, bool commit = false)
{
_pendingDate = date.ToString("yyyy-MM-dd");
_pendingStatus = status;
_pendingCommit = commit;
}
public async Task FlushAsync()
{
if (Shell.Current is null || string.IsNullOrWhiteSpace(_pendingDate))
return;
var date = _pendingDate;
var status = _pendingStatus;
var commit = _pendingCommit;
_pendingDate = null;
_pendingStatus = null;
_pendingCommit = false;
var route = $"{nameof(QuickEntryPage)}?date={Uri.EscapeDataString(date)}";
if (!string.IsNullOrWhiteSpace(status))
route += $"&status={Uri.EscapeDataString(status)}";
if (commit)
route += "&commit=true";
await MainThread.InvokeOnMainThreadAsync(() => Shell.Current.GoToAsync(route));
}
}
+108 -11
View File
@@ -1,8 +1,6 @@
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Storage;
using System.Net;
using System.Text;
@@ -47,16 +45,21 @@ public sealed class PdfExportService : IPdfExportService
var entries = await _healthEntryRepository.GetEntriesForDateAsync(date);
var activityNames = await GetActivityNamesAsync();
var symptomNamesByEntry = await GetSymptomNamesByEntryAsync(entries.Select(x => x.Id));
var conflicts = DetectDayExportConflicts(entries);
var sb = new StringBuilder();
sb.AppendLine($"<h1>Tagesübersicht – {Encode(date.ToString("dd.MM.yyyy"))}</h1>");
if (conflicts.Count > 0)
sb.AppendLine(BuildConflictHtml(conflicts));
sb.AppendLine("<table>");
sb.AppendLine("<thead><tr><th>Uhrzeit</th><th>Status</th><th>Tätigkeit</th><th>Symptome</th></tr></thead>");
sb.AppendLine("<thead><tr><th>Zeit</th><th>Status</th><th>Tätigkeit</th><th>Dauer</th><th>Symptome</th></tr></thead>");
sb.AppendLine("<tbody>");
foreach (var entry in entries.OrderBy(x => x.Timestamp).ThenBy(x => x.Id))
{
var symptoms = symptomNamesByEntry.TryGetValue(entry.Id, out var symptomList)
var symptoms = symptomNamesByEntry.TryGetValue(entry.Id, out var symptomList) && symptomList.Count > 0
? string.Join(", ", symptomList)
: "—";
@@ -65,15 +68,16 @@ public sealed class PdfExportService : IPdfExportService
: "—";
sb.AppendLine("<tr>");
sb.AppendLine($"<td>{Encode(entry.Timestamp.ToString("HH:mm"))}</td>");
sb.AppendLine($"<td>{Encode(GetDayTimeLabel(entry))}</td>");
sb.AppendLine(StateCell(entry.State, GetStateText(entry.State)));
sb.AppendLine($"<td>{Encode(activity)}</td>");
sb.AppendLine($"<td>{Encode(FormatDuration(entry.ActivityDurationMinutes))}</td>");
sb.AppendLine($"<td>{Encode(symptoms)}</td>");
sb.AppendLine("</tr>");
}
if (entries.Count == 0)
sb.AppendLine("<tr><td colspan=\"4\">Keine Einträge vorhanden.</td></tr>");
sb.AppendLine("<tr><td colspan=\"5\">Keine Einträge vorhanden.</td></tr>");
sb.AppendLine("</tbody></table>");
@@ -310,6 +314,7 @@ public sealed class PdfExportService : IPdfExportService
.Distinct()
.ToList());
}
private async Task<ExportResult> SaveHtmlAsync(
string fileName,
string title,
@@ -319,17 +324,20 @@ public sealed class PdfExportService : IPdfExportService
var folder = GetExportFolderPath();
Directory.CreateDirectory(folder);
var path = Path.Combine(folder, fileName);
var html = WrapHtml(title, bodyHtml, compactA4);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
var extension = Path.GetExtension(fileName);
var path = GetUniqueFilePath(folder, fileNameWithoutExtension, extension);
var html = WrapHtml(title, bodyHtml, compactA4);
await File.WriteAllTextAsync(path, html, Encoding.UTF8);
return new ExportResult
{
FilePath = path,
FileName = fileName
FileName = Path.GetFileName(path)
};
}
private string StateCell(HealthState state, string text)
{
var background = GetStateBackgroundCss(state);
@@ -436,8 +444,6 @@ public sealed class PdfExportService : IPdfExportService
}
catch
{
// absichtlich ignorieren, damit eine einzelne blockierte Datei
// nicht den ganzen Vorgang abbricht
}
}
@@ -514,6 +520,18 @@ public sealed class PdfExportService : IPdfExportService
.compact-symptoms {
width: 32%;
}
.conflict-box {
border: 1px solid #000000;
background: #fff8e1;
padding: {{(compactA4 ? "6px" : "10px")}};
margin-bottom: {{(compactA4 ? "8px" : "14px")}};
}
.conflict-box ul {
margin: 6px 0 0 18px;
padding: 0;
}
</style>
</head>
<body>
@@ -521,4 +539,83 @@ public sealed class PdfExportService : IPdfExportService
</body>
</html>
""";
private static string GetUniqueFilePath(string directory, string fileNameWithoutExtension, string extension)
{
Directory.CreateDirectory(directory);
var safeExtension = string.IsNullOrWhiteSpace(extension)
? ".html"
: (extension.StartsWith('.') ? extension : "." + extension);
var basePath = Path.Combine(directory, fileNameWithoutExtension + safeExtension);
if (!File.Exists(basePath))
return basePath;
var counter = 1;
while (true)
{
var candidate = Path.Combine(directory, $"{fileNameWithoutExtension} ({counter}){safeExtension}");
if (!File.Exists(candidate))
return candidate;
counter++;
}
}
private static string GetDayTimeLabel(HealthEntry entry)
{
if (entry.DayPart == DayPart.Morning)
return "Vormittag";
if (entry.DayPart == DayPart.Afternoon)
return "Nachmittag";
return entry.Timestamp.ToString("HH:mm");
}
private static string FormatDuration(int? durationMinutes)
{
if (!durationMinutes.HasValue || durationMinutes.Value <= 0)
return "—";
var duration = TimeSpan.FromMinutes(durationMinutes.Value);
return duration.ToString(@"hh\:mm");
}
private static List<string> DetectDayExportConflicts(IEnumerable<HealthEntry> entries)
{
var result = new List<string>();
var morningCount = entries.Count(x => x.DayPart == DayPart.Morning);
var afternoonCount = entries.Count(x => x.DayPart == DayPart.Afternoon);
if (morningCount > 1)
result.Add("Mehrere Vormittag-Einträge gefunden.");
if (afternoonCount > 1)
result.Add("Mehrere Nachmittag-Einträge gefunden.");
return result;
}
private static string BuildConflictHtml(IEnumerable<string> conflicts)
{
var list = conflicts.ToList();
if (list.Count == 0)
return string.Empty;
var sb = new StringBuilder();
sb.AppendLine("<div class=\"conflict-box\">");
sb.AppendLine("<strong>Hinweis auf mögliche Konflikte:</strong>");
sb.AppendLine("<ul>");
foreach (var item in list)
sb.AppendLine($"<li>{Encode(item)}</li>");
sb.AppendLine("</ul>");
sb.AppendLine("</div>");
return sb.ToString();
}
}
+1 -2
View File
@@ -1,6 +1,5 @@
using CommunityToolkit.Mvvm.ComponentModel;
using cfs_tracker.Helpers;
using Microsoft.Maui.Graphics;
using CommunityToolkit.Mvvm.ComponentModel;
namespace cfs_tracker.ViewModels;
+4 -3
View File
@@ -1,6 +1,5 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Maui.Graphics;
namespace cfs_tracker.ViewModels;
@@ -11,14 +10,16 @@ public partial class DayEntryItemViewModel : ObservableObject
public string SlotText { get; init; } = string.Empty;
public string StateText { get; init; } = string.Empty;
public string ActivityText { get; init; } = string.Empty;
public string DurationText { get; init; } = string.Empty;
public string SymptomsText { get; init; } = string.Empty;
public bool IsBackfill { get; init; }
public Color StateColor { get; init; } = Colors.Transparent;
public Color ForegroundColor { get; init; } = Colors.White;
public bool HasActivity => !string.IsNullOrWhiteSpace(ActivityText);
public bool HasDuration => !string.IsNullOrWhiteSpace(DurationText);
public bool HasSymptoms => !string.IsNullOrWhiteSpace(SymptomsText);
public bool HasDetails => HasActivity || HasSymptoms;
public bool HasDetails => HasActivity || HasDuration || HasSymptoms;
public string DetailsButtonText => IsExpanded ? "Details ausblenden" : "Details anzeigen";
[ObservableProperty]
@@ -43,4 +44,4 @@ public partial class DayEntryItemViewModel : ObservableObject
IsExpanded = !IsExpanded;
}
}
}
+11 -6
View File
@@ -1,13 +1,11 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.Globalization;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Storage;
namespace cfs_tracker.ViewModels;
@@ -189,7 +187,8 @@ public partial class DayViewModel : ObservableObject
};
var activityText = string.Empty;
if (entry.ActivityId.HasValue && activityMap.TryGetValue(entry.ActivityId.Value, out var activityName) &&
if (entry.ActivityId.HasValue &&
activityMap.TryGetValue(entry.ActivityId.Value, out var activityName) &&
!string.Equals(activityName, "Keine Tätigkeit", StringComparison.OrdinalIgnoreCase))
{
activityText = activityName;
@@ -200,6 +199,10 @@ public partial class DayViewModel : ObservableObject
? string.Join(", ", symptoms)
: string.Empty;
var durationText = entry.ActivityDurationMinutes.HasValue && entry.ActivityDurationMinutes.Value > 0
? TimeSpan.FromMinutes(entry.ActivityDurationMinutes.Value).ToString(@"hh\:mm")
: string.Empty;
Entries.Add(new DayEntryItemViewModel
{
Id = entry.Id,
@@ -209,6 +212,7 @@ public partial class DayViewModel : ObservableObject
entry.State.ToAppearanceTextKey(),
entry.State.ToFallbackText()),
ActivityText = activityText,
DurationText = durationText,
SymptomsText = symptomText,
IsBackfill = entry.DayPart.HasValue,
StateColor = _appearanceService.GetColor(entry.State.ToAppearanceColorKey(), "#1F242B"),
@@ -231,6 +235,7 @@ public partial class DayViewModel : ObservableObject
await _healthEntryRepository.AddQuickEntryAsync(
state: state,
activityId: null,
activityDurationMinutes: null,
symptomIds: null,
timestamp: DateTime.Now,
source: EntrySource.App);
@@ -347,4 +352,4 @@ public partial class DayViewModel : ObservableObject
}
private static string BuildCounterText(string label, int count) => $"{label}\n{count}";
}
}
-1
View File
@@ -1,5 +1,4 @@
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Maui.Graphics;
namespace cfs_tracker.ViewModels;
+41 -20
View File
@@ -1,9 +1,9 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Services;
using Microsoft.Maui.Storage;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Maui.ApplicationModel;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels;
@@ -50,25 +50,31 @@ public partial class MonthViewModel : ObservableObject
OpenDayCommand = new AsyncRelayCommand<MonthCellViewModel>(OpenDayAsync);
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
SelectedDate = _calendarStateService.SelectedDate;
SelectedDate = _calendarStateService.SelectedDate.Date;
UpdateHeader();
}
partial void OnSelectedDateChanged(DateTime value)
{
UpdateHeader();
}
public async Task RefreshAsync()
{
SelectedDate = _calendarStateService.SelectedDate;
var month = new DateTime(SelectedDate.Year, SelectedDate.Month, 1);
HeaderText = DateHelper.ToGermanMonthYear(month);
SelectedDate = _calendarStateService.SelectedDate.Date;
UpdateHeader();
var monthEnd = month.AddMonths(1);
var monthStart = new DateTime(SelectedDate.Year, SelectedDate.Month, 1);
var monthEnd = monthStart.AddMonths(1);
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(month, monthEnd);
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(monthStart, monthEnd);
Cells.Clear();
var daysInMonth = DateTime.DaysInMonth(month.Year, month.Month);
var daysInMonth = DateTime.DaysInMonth(monthStart.Year, monthStart.Month);
for (var day = 1; day <= daysInMonth; day++)
{
var date = new DateTime(month.Year, month.Month, day);
var date = new DateTime(monthStart.Year, monthStart.Month, day);
var dayEntries = entries.Where(x => x.EntryDate.Date == date.Date).ToList();
var average = _aggregationService.CalculateAverage(dayEntries);
@@ -88,12 +94,20 @@ public partial class MonthViewModel : ObservableObject
});
}
}
private void UpdateHeader()
{
var month = new DateTime(SelectedDate.Year, SelectedDate.Month, 1);
HeaderText = DateHelper.ToGermanMonthYear(month);
}
private async Task OpenDayAsync(MonthCellViewModel? item)
{
if (item is null)
return;
_calendarStateService.SelectedDate = item.Date;
SelectedDate = item.Date.Date;
_calendarStateService.SelectedDate = SelectedDate;
await Shell.Current.GoToAsync("//day");
}
@@ -105,25 +119,32 @@ public partial class MonthViewModel : ObservableObject
private async Task PreviousMonthAsync()
{
_calendarStateService.SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(-1);
SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(-1);
_calendarStateService.SelectedDate = SelectedDate;
await RefreshAsync();
}
private async Task NextMonthAsync()
{
_calendarStateService.SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(1);
SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(1);
_calendarStateService.SelectedDate = SelectedDate;
await RefreshAsync();
}
private async Task TodayAsync()
{
_calendarStateService.ResetToToday();
await RefreshAsync();
var today = DateTime.Today;
SelectedDate = today;
_calendarStateService.SelectedDate = today;
await Shell.Current.GoToAsync("//day");
}
private async void HandleSharedDateChanged(DateTime date)
private void HandleSharedDateChanged(DateTime date)
{
SelectedDate = date;
await RefreshAsync();
MainThread.BeginInvokeOnMainThread(async () =>
{
SelectedDate = date.Date;
await RefreshAsync();
});
}
}
}
@@ -1,20 +1,84 @@
using cfs_tracker.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.Input;
namespace cfs_tracker.ViewModels;
public partial class NotificationScheduleItemViewModel : ObservableObject
{
public int Id { get; init; }
public ObservableCollection<WeekdayOptionItemViewModel> WeekdayOptions { get; } = new();
public int Id { get; set; }
[ObservableProperty]
private WeekdayOptionItemViewModel? selectedWeekday;
private TimeSpan selectedTime;
[ObservableProperty]
private TimeSpan selectedTime = new(9, 0, 0);
private bool isEnabled;
[ObservableProperty]
private bool isEnabled = true;
}
private bool monday;
[ObservableProperty]
private bool tuesday;
[ObservableProperty]
private bool wednesday;
[ObservableProperty]
private bool thursday;
[ObservableProperty]
private bool friday;
[ObservableProperty]
private bool saturday;
[ObservableProperty]
private bool sunday;
public IRelayCommand ToggleMondayCommand { get; }
public IRelayCommand ToggleTuesdayCommand { get; }
public IRelayCommand ToggleWednesdayCommand { get; }
public IRelayCommand ToggleThursdayCommand { get; }
public IRelayCommand ToggleFridayCommand { get; }
public IRelayCommand ToggleSaturdayCommand { get; }
public IRelayCommand ToggleSundayCommand { get; }
public NotificationScheduleItemViewModel()
{
ToggleMondayCommand = new RelayCommand(() => Monday = !Monday);
ToggleTuesdayCommand = new RelayCommand(() => Tuesday = !Tuesday);
ToggleWednesdayCommand = new RelayCommand(() => Wednesday = !Wednesday);
ToggleThursdayCommand = new RelayCommand(() => Thursday = !Thursday);
ToggleFridayCommand = new RelayCommand(() => Friday = !Friday);
ToggleSaturdayCommand = new RelayCommand(() => Saturday = !Saturday);
ToggleSundayCommand = new RelayCommand(() => Sunday = !Sunday);
}
public int ToWeekdayMask()
{
var mask = NotificationWeekdays.None;
if (Monday) mask |= NotificationWeekdays.Monday;
if (Tuesday) mask |= NotificationWeekdays.Tuesday;
if (Wednesday) mask |= NotificationWeekdays.Wednesday;
if (Thursday) mask |= NotificationWeekdays.Thursday;
if (Friday) mask |= NotificationWeekdays.Friday;
if (Saturday) mask |= NotificationWeekdays.Saturday;
if (Sunday) mask |= NotificationWeekdays.Sunday;
return (int)mask;
}
public void LoadFromWeekdayMask(int mask)
{
var flags = (NotificationWeekdays)mask;
Monday = flags.HasFlag(NotificationWeekdays.Monday);
Tuesday = flags.HasFlag(NotificationWeekdays.Tuesday);
Wednesday = flags.HasFlag(NotificationWeekdays.Wednesday);
Thursday = flags.HasFlag(NotificationWeekdays.Thursday);
Friday = flags.HasFlag(NotificationWeekdays.Friday);
Saturday = flags.HasFlag(NotificationWeekdays.Saturday);
Sunday = flags.HasFlag(NotificationWeekdays.Sunday);
}
}
+88 -37
View File
@@ -1,10 +1,13 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
namespace cfs_tracker.ViewModels;
@@ -42,12 +45,19 @@ public partial class OptionsViewModel : ObservableObject
[ObservableProperty]
private string currentDatabasePath = string.Empty;
[ObservableProperty]
private OptionsTab selectedTab = OptionsTab.Notifications;
public ObservableCollection<AppearanceColorItemViewModel> AppearanceColors { get; } = new();
public ObservableCollection<AppearanceTextItemViewModel> StatusTexts { get; } = new();
public ObservableCollection<ActivityManageItemViewModel> Activities { get; } = new();
public ObservableCollection<SymptomManageItemViewModel> Symptoms { get; } = new();
public ObservableCollection<NotificationScheduleItemViewModel> NotificationSchedules { get; } = new();
public bool IsAppearanceTabSelected => SelectedTab == OptionsTab.Appearance;
public bool IsNotificationsTabSelected => SelectedTab == OptionsTab.Notifications;
public bool IsDataManagementTabSelected => SelectedTab == OptionsTab.DataManagement;
public IAsyncRelayCommand DeleteAllDataCommand { get; }
public IAsyncRelayCommand SaveAppearanceCommand { get; }
public IAsyncRelayCommand ResetAppearanceCommand { get; }
@@ -64,6 +74,9 @@ public partial class OptionsViewModel : ObservableObject
public IAsyncRelayCommand<NotificationScheduleItemViewModel> DeleteScheduleCommand { get; }
public IAsyncRelayCommand SaveDatabaseLocationCommand { get; }
public IAsyncRelayCommand ClearExportsCommand { get; }
public IRelayCommand ShowAppearanceTabCommand { get; }
public IRelayCommand ShowNotificationsTabCommand { get; }
public IRelayCommand ShowDataManagementTabCommand { get; }
public OptionsViewModel(
HealthEntryRepository healthEntryRepository,
@@ -104,6 +117,10 @@ public partial class OptionsViewModel : ObservableObject
DeleteScheduleCommand = new AsyncRelayCommand<NotificationScheduleItemViewModel>(DeleteScheduleAsync);
SaveDatabaseLocationCommand = new AsyncRelayCommand(SaveDatabaseLocationAsync);
ClearExportsCommand = new AsyncRelayCommand(ClearExportsAsync);
ShowAppearanceTabCommand = new RelayCommand(() => SelectedTab = OptionsTab.Appearance);
ShowNotificationsTabCommand = new RelayCommand(() => SelectedTab = OptionsTab.Notifications);
ShowDataManagementTabCommand = new RelayCommand(() => SelectedTab = OptionsTab.DataManagement);
}
partial void OnDeleteConfirmationTextChanged(string value)
@@ -111,6 +128,13 @@ public partial class OptionsViewModel : ObservableObject
DeleteAllDataCommand.NotifyCanExecuteChanged();
}
partial void OnSelectedTabChanged(OptionsTab value)
{
OnPropertyChanged(nameof(IsAppearanceTabSelected));
OnPropertyChanged(nameof(IsNotificationsTabSelected));
OnPropertyChanged(nameof(IsDataManagementTabSelected));
}
public async Task LoadAsync()
{
await LoadAppearanceAsync();
@@ -177,14 +201,15 @@ public partial class OptionsViewModel : ObservableObject
{
var fallback = AppearanceDefaults.All[key];
var value = map.TryGetValue(key, out var stored) ? stored : fallback;
var preview = ColorUtility.ParseColor(value, fallback);
AppearanceColors.Add(new AppearanceColorItemViewModel
{
Key = key,
Title = title,
Fallback = fallback,
Value = value,
PreviewColor = ColorUtility.ParseColor(value, fallback)
Value = ToHex(preview),
PreviewColor = preview
});
}
@@ -239,23 +264,37 @@ public partial class OptionsViewModel : ObservableObject
private async Task LoadSchedulesAsync()
{
NotificationSchedules.Clear();
var schedules = await _notificationScheduleRepository.GetAllAsync();
foreach (var schedule in schedules)
NotificationSchedules.Add(CreateScheduleVm(schedule.Id, schedule.DayOfWeek, new TimeSpan(schedule.Hour, schedule.Minute, 0), schedule.IsEnabled));
{
var vm = new NotificationScheduleItemViewModel
{
Id = schedule.Id,
SelectedTime = new TimeSpan(schedule.Hour, schedule.Minute, 0),
IsEnabled = schedule.IsEnabled
};
vm.LoadFromWeekdayMask(schedule.WeekdayMask);
NotificationSchedules.Add(vm);
}
}
private async Task SaveAppearanceAsync()
{
foreach (var item in AppearanceColors)
{
item.PreviewColor = ColorUtility.ParseColor(item.Value, item.Fallback);
await _appearanceService.SaveColorAsync(item.Key, item.Value);
var normalized = ToHex(ColorUtility.ParseColor(item.Value, item.Fallback));
item.Value = normalized;
item.PreviewColor = ColorUtility.ParseColor(normalized, item.Fallback);
await _appearanceService.SaveColorAsync(item.Key, normalized);
}
foreach (var item in StatusTexts)
await _appearanceService.SaveTextAsync(item.Key, item.Value);
await _notificationScheduler.SyncAsync();
StatusText = "Aussehen gespeichert.";
}
@@ -263,6 +302,7 @@ public partial class OptionsViewModel : ObservableObject
{
await _appearanceService.ResetAsync();
await LoadAppearanceAsync();
await _notificationScheduler.SyncAsync();
StatusText = "Aussehen auf Standard zurückgesetzt.";
}
@@ -384,17 +424,40 @@ public partial class OptionsViewModel : ObservableObject
private Task AddScheduleAsync()
{
NotificationSchedules.Add(CreateScheduleVm(0, DayOfWeek.Monday, new TimeSpan(9, 0, 0), true));
NotificationSchedules.Add(new NotificationScheduleItemViewModel
{
SelectedTime = new TimeSpan(14, 0, 0),
IsEnabled = true,
Monday = true,
Tuesday = true,
Wednesday = true,
Thursday = true,
Friday = true
});
StatusText = "Benachrichtigungszeit hinzugefügt.";
return Task.CompletedTask;
}
private async Task SaveSchedulesAsync()
{
var granted = await _notificationScheduler.EnsurePermissionAsync();
if (!granted)
{
StatusText = "Benachrichtigungsberechtigung wurde nicht erlaubt.";
return;
}
if (NotificationSchedules.Any(x => x.ToWeekdayMask() == 0))
{
StatusText = "Bitte pro Benachrichtigungszeit mindestens einen Wochentag auswählen.";
return;
}
var items = NotificationSchedules.Select(x => new NotificationSchedule
{
Id = x.Id,
DayOfWeek = x.SelectedWeekday?.Value ?? DayOfWeek.Monday,
WeekdayMask = x.ToWeekdayMask(),
Hour = x.SelectedTime.Hours,
Minute = x.SelectedTime.Minutes,
IsEnabled = x.IsEnabled
@@ -404,7 +467,7 @@ public partial class OptionsViewModel : ObservableObject
await _notificationScheduler.SyncAsync();
await LoadSchedulesAsync();
StatusText = "Benachrichtigungszeiten gespeichert. Text: 'Wie geht es dir?' mit Gelb/Rot/Grau als Schnellwahl.";
StatusText = "Benachrichtigungszeiten gespeichert.";
}
private Task DeleteScheduleAsync(NotificationScheduleItemViewModel? item)
@@ -425,24 +488,6 @@ public partial class OptionsViewModel : ObservableObject
return Task.CompletedTask;
}
private static NotificationScheduleItemViewModel CreateScheduleVm(int id, DayOfWeek dayOfWeek, TimeSpan time, bool isEnabled)
{
var vm = new NotificationScheduleItemViewModel
{
Id = id,
SelectedTime = time,
IsEnabled = isEnabled
};
foreach (var option in BuildWeekdayOptions())
vm.WeekdayOptions.Add(option);
vm.SelectedWeekday = vm.WeekdayOptions.FirstOrDefault(x => x.Value == dayOfWeek)
?? vm.WeekdayOptions.First();
return vm;
}
private async Task ClearExportsAsync()
{
var confirm = await Shell.Current.DisplayAlertAsync(
@@ -464,14 +509,20 @@ public partial class OptionsViewModel : ObservableObject
"OK");
}
private static IEnumerable<WeekdayOptionItemViewModel> BuildWeekdayOptions()
private static string ToHex(Color color)
{
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Monday, Name = "Montag" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Tuesday, Name = "Dienstag" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Wednesday, Name = "Mittwoch" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Thursday, Name = "Donnerstag" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Friday, Name = "Freitag" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Saturday, Name = "Samstag" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Sunday, Name = "Sonntag" };
var red = ClampByte(color.Red * 255d);
var green = ClampByte(color.Green * 255d);
var blue = ClampByte(color.Blue * 255d);
return $"#{red:X2}{green:X2}{blue:X2}";
}
}
private static int ClampByte(double value) => Math.Clamp((int)Math.Round(value), 0, 255);
public enum OptionsTab
{
Appearance,
Notifications,
DataManagement
}
}
+93 -9
View File
@@ -1,13 +1,11 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services;
using Microsoft.Maui.Graphics;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
namespace cfs_tracker.ViewModels;
@@ -20,6 +18,8 @@ public partial class QuickEntryViewModel : ObservableObject
private readonly CalendarStateService _calendarStateService;
private string _dateQuery = string.Empty;
private string _statusQuery = string.Empty;
private bool _commitFromNotification;
private int? _entryId;
[ObservableProperty]
@@ -67,6 +67,9 @@ public partial class QuickEntryViewModel : ObservableObject
[ObservableProperty]
private ActivityPickerItemViewModel? selectedActivity;
[ObservableProperty]
private TimeSpan activityDuration = TimeSpan.Zero;
[ObservableProperty]
private DayPartOptionItemViewModel? selectedPart;
@@ -95,6 +98,7 @@ public partial class QuickEntryViewModel : ObservableObject
public IAsyncRelayCommand SaveGrayCommand { get; }
public IAsyncRelayCommand SaveCommand { get; }
public IAsyncRelayCommand CancelCommand { get; }
public IRelayCommand<SelectableSymptomItemViewModel> ToggleSymptomCommand { get; }
public QuickEntryViewModel(
HealthEntryRepository healthEntryRepository,
@@ -115,6 +119,7 @@ public partial class QuickEntryViewModel : ObservableObject
SaveGrayCommand = new AsyncRelayCommand(() => SelectOrSaveAsync(HealthState.Gray));
SaveCommand = new AsyncRelayCommand(SaveSelectedAsync);
CancelCommand = new AsyncRelayCommand(CancelAsync);
ToggleSymptomCommand = new RelayCommand<SelectableSymptomItemViewModel>(ToggleSymptom);
}
partial void OnIsTodayChanged(bool value) => RaiseModeChanged();
@@ -134,14 +139,22 @@ public partial class QuickEntryViewModel : ObservableObject
OnPropertyChanged(nameof(SelectedStateSummaryText));
}
public void ApplyQuery(string date, string entryId)
public void ApplyQuery(string date, string? entryId, string? status, string? commit)
{
_dateQuery = date ?? string.Empty;
_entryId = int.TryParse(entryId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedId)
_statusQuery = status ?? string.Empty;
_commitFromNotification = string.Equals(commit, "true", StringComparison.OrdinalIgnoreCase);
_entryId = int.TryParse(entryId, out var parsedId)
? parsedId
: null;
}
public void ApplyQuery(string date, string? entryId)
{
ApplyQuery(date, entryId, null, null);
}
public async Task InitializeAsync()
{
SelectedDate = DateTime.TryParseExact(
@@ -156,15 +169,36 @@ public partial class QuickEntryViewModel : ObservableObject
UpdateDateMode();
SelectedDateText = DateHelper.ToGermanDateText(SelectedDate);
IsEditing = false;
SelectedState = null;
ActivityDuration = TimeSpan.Zero;
LoadAppearance();
await LoadActivitiesAsync();
await LoadSymptomsAsync();
LoadDayParts();
SelectedActivity = Activities.FirstOrDefault();
SelectedPart = Parts.FirstOrDefault(x => x.Value == DayPart.Morning) ?? Parts.FirstOrDefault();
foreach (var symptom in Symptoms)
symptom.IsSelected = false;
if (_entryId.HasValue)
{
await LoadExistingEntryAsync();
}
else
SelectedPart = Parts.FirstOrDefault(x => x.Value == DayPart.Morning);
{
if (TryParseNotificationState(_statusQuery, out var notificationState))
SelectedState = notificationState;
if (_commitFromNotification && IsToday && TryParseNotificationState(_statusQuery, out var quickState))
{
await SaveAsync(quickState);
return;
}
}
OnPropertyChanged(nameof(ModeText));
OnPropertyChanged(nameof(CanSave));
@@ -192,8 +226,6 @@ public partial class QuickEntryViewModel : ObservableObject
Name = item.Name
});
}
SelectedActivity ??= Activities.FirstOrDefault();
}
private async Task LoadSymptomsAsync()
@@ -246,6 +278,7 @@ public partial class QuickEntryViewModel : ObservableObject
SelectedActivity = Activities.FirstOrDefault(x => x.Id == entry.ActivityId)
?? Activities.FirstOrDefault();
ActivityDuration = TimeSpan.FromMinutes(entry.ActivityDurationMinutes ?? 0);
SelectedState = entry.State;
var symptomIds = await _symptomRepository.GetSymptomIdsForEntryAsync(entry.Id);
@@ -280,6 +313,7 @@ public partial class QuickEntryViewModel : ObservableObject
return;
var activityId = SelectedActivity?.Id;
var activityDurationMinutes = ParseActivityDurationMinutes();
var symptomIds = Symptoms.Where(x => x.IsSelected).Select(x => x.Id).ToList();
if (IsEditing && _entryId.HasValue)
@@ -289,6 +323,7 @@ public partial class QuickEntryViewModel : ObservableObject
date: SelectedDate,
state: state,
activityId: activityId,
activityDurationMinutes: activityDurationMinutes,
symptomIds: symptomIds,
part: IsPastDate ? SelectedPart?.Value ?? DayPart.Morning : null,
source: IsPastDate ? EntrySource.Backfill : EntrySource.App);
@@ -300,6 +335,7 @@ public partial class QuickEntryViewModel : ObservableObject
part: SelectedPart?.Value ?? DayPart.Morning,
state: state,
activityId: activityId,
activityDurationMinutes: activityDurationMinutes,
symptomIds: symptomIds,
source: EntrySource.Backfill);
}
@@ -308,6 +344,7 @@ public partial class QuickEntryViewModel : ObservableObject
await _healthEntryRepository.AddQuickEntryAsync(
state: state,
activityId: activityId,
activityDurationMinutes: activityDurationMinutes,
symptomIds: symptomIds,
timestamp: DateTime.Now,
source: EntrySource.App);
@@ -357,4 +394,51 @@ public partial class QuickEntryViewModel : ObservableObject
HealthState.Gray => GrayStatusText,
_ => string.Empty
};
private static bool TryParseNotificationState(string? value, out HealthState state)
{
switch ((value ?? string.Empty).Trim().ToLowerInvariant())
{
case "green":
case "gruen":
case "grün":
state = HealthState.Green;
return true;
case "yellow":
case "gelb":
state = HealthState.Yellow;
return true;
case "red":
case "rot":
state = HealthState.Red;
return true;
case "gray":
case "grey":
case "grau":
case "schwarz":
state = HealthState.Gray;
return true;
default:
state = default;
return false;
}
}
private int? ParseActivityDurationMinutes()
{
var minutes = (int)Math.Round(ActivityDuration.TotalMinutes, MidpointRounding.AwayFromZero);
return minutes > 0 ? minutes : null;
}
private void ToggleSymptom(SelectableSymptomItemViewModel? item)
{
if (item is null)
return;
item.IsSelected = !item.IsSelected;
}
}
-1
View File
@@ -1,6 +1,5 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Maui.Graphics;
namespace cfs_tracker.ViewModels;
+35 -17
View File
@@ -1,10 +1,10 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services;
using Microsoft.Maui.Storage;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Maui.ApplicationModel;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels;
@@ -60,14 +60,19 @@ public partial class WeekViewModel : ObservableObject
OpenDayCommand = new AsyncRelayCommand<WeekDaySummaryViewModel>(OpenDayAsync);
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
SelectedDate = _calendarStateService.SelectedDate;
SelectedDate = _calendarStateService.SelectedDate.Date;
UpdateHeader();
}
partial void OnSelectedDateChanged(DateTime value)
{
UpdateHeader();
}
public async Task RefreshAsync()
{
SelectedDate = _calendarStateService.SelectedDate;
WeekStart = DateHelper.StartOfWeekMonday(SelectedDate);
HeaderText = $"Woche {WeekStart:dd.MM.yyyy} - {WeekStart.AddDays(6):dd.MM.yyyy}";
SelectedDate = _calendarStateService.SelectedDate.Date;
UpdateHeader();
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(WeekStart, WeekStart.AddDays(7));
var activityMap = await _activityRepository.GetNameMapAsync();
@@ -97,12 +102,19 @@ public partial class WeekViewModel : ObservableObject
}
}
private void UpdateHeader()
{
WeekStart = DateHelper.StartOfWeekMonday(SelectedDate.Date);
HeaderText = $"Woche {WeekStart:dd.MM.yyyy} - {WeekStart.AddDays(6):dd.MM.yyyy}";
}
private async Task OpenDayAsync(WeekDaySummaryViewModel? item)
{
if (item is null)
return;
_calendarStateService.SelectedDate = item.Date;
SelectedDate = item.Date.Date;
_calendarStateService.SelectedDate = SelectedDate;
await Shell.Current.GoToAsync("//day");
}
@@ -114,25 +126,31 @@ public partial class WeekViewModel : ObservableObject
private async Task PreviousWeekAsync()
{
_calendarStateService.SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(-7);
SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(-7);
_calendarStateService.SelectedDate = SelectedDate;
await RefreshAsync();
}
private async Task NextWeekAsync()
{
_calendarStateService.SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(7);
SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(7);
_calendarStateService.SelectedDate = SelectedDate;
await RefreshAsync();
}
private async Task TodayAsync()
{
_calendarStateService.ResetToToday();
await RefreshAsync();
var today = DateTime.Today;
SelectedDate = today;
_calendarStateService.SelectedDate = today;
await Shell.Current.GoToAsync("//day");
}
private async void HandleSharedDateChanged(DateTime date)
private void HandleSharedDateChanged(DateTime date)
{
SelectedDate = date;
await RefreshAsync();
MainThread.BeginInvokeOnMainThread(async () =>
{
SelectedDate = date.Date;
await RefreshAsync();
});
}
}
}
+34 -15
View File
@@ -1,9 +1,8 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Services;
using Microsoft.Maui.Storage;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels;
@@ -50,13 +49,19 @@ public partial class YearViewModel : ObservableObject
OpenDayCommand = new AsyncRelayCommand<MonthCellViewModel>(OpenDayAsync);
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
SelectedDate = _calendarStateService.SelectedDate;
SelectedDate = _calendarStateService.SelectedDate.Date;
UpdateHeader();
}
partial void OnSelectedDateChanged(DateTime value)
{
UpdateHeader();
}
public async Task RefreshAsync()
{
SelectedDate = _calendarStateService.SelectedDate;
HeaderText = DateHelper.ToGermanYear(SelectedDate);
SelectedDate = _calendarStateService.SelectedDate.Date;
UpdateHeader();
var yearStart = new DateTime(SelectedDate.Year, 1, 1);
var yearEnd = yearStart.AddYears(1);
@@ -99,12 +104,19 @@ public partial class YearViewModel : ObservableObject
Months.Add(section);
}
}
private void UpdateHeader()
{
HeaderText = DateHelper.ToGermanYear(SelectedDate);
}
private async Task OpenDayAsync(MonthCellViewModel? item)
{
if (item is null)
return;
_calendarStateService.SelectedDate = item.Date;
SelectedDate = item.Date.Date;
_calendarStateService.SelectedDate = SelectedDate;
await Shell.Current.GoToAsync("//day");
}
@@ -116,25 +128,32 @@ public partial class YearViewModel : ObservableObject
private async Task PreviousYearAsync()
{
_calendarStateService.SelectedDate = new DateTime(SelectedDate.Year - 1, SelectedDate.Month, 1);
SelectedDate = new DateTime(SelectedDate.Year - 1, SelectedDate.Month, 1);
_calendarStateService.SelectedDate = SelectedDate;
await RefreshAsync();
}
private async Task NextYearAsync()
{
_calendarStateService.SelectedDate = new DateTime(SelectedDate.Year + 1, SelectedDate.Month, 1);
SelectedDate = new DateTime(SelectedDate.Year + 1, SelectedDate.Month, 1);
_calendarStateService.SelectedDate = SelectedDate;
await RefreshAsync();
}
private async Task TodayAsync()
{
_calendarStateService.ResetToToday();
await RefreshAsync();
var today = DateTime.Today;
SelectedDate = today;
_calendarStateService.SelectedDate = today;
await Shell.Current.GoToAsync("//day");
}
private async void HandleSharedDateChanged(DateTime date)
private void HandleSharedDateChanged(DateTime date)
{
SelectedDate = date;
await RefreshAsync();
MainThread.BeginInvokeOnMainThread(async () =>
{
SelectedDate = date.Date;
await RefreshAsync();
});
}
}
}
+6 -3
View File
@@ -111,13 +111,13 @@
<Button Grid.Column="1"
Text="Bearbeiten"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.EditEntryCommand}"
Command="{Binding Source={RelativeSource AncestorType={x:Type viewModels:DayViewModel}}, Path=EditEntryCommand, x:DataType='viewModels:DayViewModel'}"
CommandParameter="{Binding .}" />
<Button Grid.Column="2"
Text="Löschen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteEntryCommand}"
Command="{Binding Source={RelativeSource AncestorType={x:Type viewModels:DayViewModel}}, Path=DeleteEntryCommand, x:DataType='viewModels:DayViewModel'}"
CommandParameter="{Binding .}" />
</Grid>
@@ -140,6 +140,9 @@
<Label Text="{Binding ActivityText, StringFormat='Tätigkeit: {0}'}"
IsVisible="{Binding HasActivity}"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="{Binding DurationText, StringFormat='Dauer: {0}'}"
IsVisible="{Binding HasDuration}"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="{Binding SymptomsText, StringFormat='Symptome: {0}'}"
IsVisible="{Binding HasSymptoms}"
TextColor="{DynamicResource TextPrimary}" />
@@ -151,4 +154,4 @@
</CollectionView>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
</ContentPage>
+1 -1
View File
@@ -65,7 +65,7 @@
StrokeShape="RoundRectangle 10">
<Border.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.OpenDayCommand}"
Command="{Binding Source={RelativeSource AncestorType={x:Type viewModels:MonthViewModel}}, Path=OpenDayCommand, x:DataType='viewModels:MonthViewModel'}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
+594 -287
View File
@@ -8,6 +8,25 @@
Title="Optionen"
BackgroundColor="{DynamicResource AppBackground}">
<ContentPage.Resources>
<Style x:Key="DayToggleButtonStyle" TargetType="Button">
<Setter Property="CornerRadius" Value="10" />
<Setter Property="Padding" Value="8,6" />
<Setter Property="FontSize" Value="12" />
<Setter Property="TextColor" Value="{DynamicResource ButtonPrimaryText}" />
<Setter Property="BackgroundColor" Value="{DynamicResource ButtonPrimaryBackground}" />
</Style>
<Style x:Key="OptionsTabButtonStyle" TargetType="Button">
<Setter Property="CornerRadius" Value="14" />
<Setter Property="Padding" Value="12,10" />
<Setter Property="TextColor" Value="{DynamicResource ButtonPrimaryText}" />
<Setter Property="BackgroundColor" Value="{DynamicResource ButtonPrimaryBackground}" />
<Setter Property="FontAttributes" Value="Bold" />
</Style>
</ContentPage.Resources>
<Grid>
<ScrollView>
<VerticalStackLayout Padding="16" Spacing="16">
<Label Text="Optionen"
@@ -20,299 +39,587 @@
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Aussehen"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
BackgroundColor="{DynamicResource SurfaceBackground}">
<Grid ColumnDefinitions="*,*,*"
ColumnSpacing="10">
<Button Text="Aussehen"
Style="{StaticResource OptionsTabButtonStyle}"
Command="{Binding ShowAppearanceTabCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding IsAppearanceTabSelected}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Button.Triggers>
</Button>
<VerticalStackLayout BindableLayout.ItemsSource="{Binding AppearanceColors}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:AppearanceColorItemViewModel">
<Grid ColumnDefinitions="*,120"
ColumnSpacing="10"
Padding="0,6">
<VerticalStackLayout>
<Label Text="{Binding Title}"
TextColor="{DynamicResource TextPrimary}" />
<Entry Text="{Binding Value}"
Placeholder="#112233" />
</VerticalStackLayout>
<Button Grid.Column="1"
Text="Push-Nachrichten"
Style="{StaticResource OptionsTabButtonStyle}"
Command="{Binding ShowNotificationsTabCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding IsNotificationsTabSelected}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Button.Triggers>
</Button>
<Border Grid.Column="1"
Padding="8"
<Button Grid.Column="2"
Text="Datenverwaltung"
Style="{StaticResource OptionsTabButtonStyle}"
Command="{Binding ShowDataManagementTabCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding IsDataManagementTabSelected}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Button.Triggers>
</Button>
</Grid>
</Border>
<VerticalStackLayout IsVisible="{Binding IsAppearanceTabSelected}"
Spacing="16">
<Border Padding="12"
Stroke="{DynamicResource Border}"
StrokeShape="RoundRectangle 8"
BackgroundColor="{Binding PreviewColor}">
<Label Text="{Binding Value}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
TextColor="{DynamicResource TextPrimary}" />
</Border>
</Grid>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
<VerticalStackLayout BindableLayout.ItemsSource="{Binding StatusTexts}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:AppearanceTextItemViewModel">
<VerticalStackLayout Spacing="4"
Padding="0,6">
<Label Text="{Binding Title}"
TextColor="{DynamicResource TextPrimary}" />
<Entry Text="{Binding Value}" />
</VerticalStackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
<Grid ColumnDefinitions="*,*"
ColumnSpacing="12">
<Button Text="Speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding SaveAppearanceCommand}" />
<Button Grid.Column="1"
Text="Zurücksetzen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding ResetAppearanceCommand}" />
</Grid>
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Tätigkeiten"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Grid ColumnDefinitions="*,Auto"
ColumnSpacing="10">
<Entry Text="{Binding NewActivityName}"
Placeholder="Neue Tätigkeit" />
<Button Grid.Column="1"
Text="Hinzufügen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding AddActivityCommand}" />
</Grid>
<VerticalStackLayout BindableLayout.ItemsSource="{Binding Activities}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:ActivityManageItemViewModel">
<Border Padding="10"
Stroke="{DynamicResource Border}"
StrokeShape="RoundRectangle 10"
BackgroundColor="{DynamicResource SurfaceBackgroundAlt}">
<VerticalStackLayout Spacing="8">
<Entry Text="{Binding Name}" />
<Label Text="{Binding UsageHint}"
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="*,*,*"
ColumnSpacing="8">
<Button Text="Speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.SaveActivityCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="1"
Text="Aktiv/Inaktiv"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.ToggleActivityActiveCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="2"
Text="Entfernen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteActivityCommand}"
CommandParameter="{Binding .}" />
</Grid>
</VerticalStackLayout>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Symptome"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Grid ColumnDefinitions="*,Auto"
ColumnSpacing="10">
<Entry Text="{Binding NewSymptomName}"
Placeholder="Neues Symptom" />
<Button Grid.Column="1"
Text="Hinzufügen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding AddSymptomCommand}" />
</Grid>
<VerticalStackLayout BindableLayout.ItemsSource="{Binding Symptoms}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:SymptomManageItemViewModel">
<Border Padding="10"
Stroke="{DynamicResource Border}"
StrokeShape="RoundRectangle 10"
BackgroundColor="{DynamicResource SurfaceBackgroundAlt}">
<VerticalStackLayout Spacing="8">
<Entry Text="{Binding Name}" />
<Label Text="{Binding UsageHint}"
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="*,*,*"
ColumnSpacing="8">
<Button Text="Speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.SaveSymptomCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="1"
Text="Aktiv/Inaktiv"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.ToggleSymptomActiveCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="2"
Text="Entfernen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteSymptomCommand}"
CommandParameter="{Binding .}" />
</Grid>
</VerticalStackLayout>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Push-Benachrichtigungen"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="Text: 'Wie geht es dir?' mit Schnellwahl für Gelb, Rot und Grau/Schwarz."
TextColor="{DynamicResource TextMuted}" />
<Button Text="Zeit hinzufügen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding AddScheduleCommand}" />
<VerticalStackLayout BindableLayout.ItemsSource="{Binding NotificationSchedules}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:NotificationScheduleItemViewModel">
<Border Padding="10"
Stroke="{DynamicResource Border}"
StrokeShape="RoundRectangle 10"
BackgroundColor="{DynamicResource SurfaceBackgroundAlt}">
<VerticalStackLayout Spacing="8">
<Picker Title="Wochentag"
ItemsSource="{Binding WeekdayOptions}"
ItemDisplayBinding="{Binding Name}"
SelectedItem="{Binding SelectedWeekday}" />
<TimePicker Time="{Binding SelectedTime}" />
<Grid ColumnDefinitions="Auto,*"
ColumnSpacing="8">
<CheckBox IsChecked="{Binding IsEnabled}" />
<Label Grid.Column="1"
Text="Aktiv"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
</Grid>
<Button Text="Entfernen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteScheduleCommand}"
CommandParameter="{Binding .}" />
</VerticalStackLayout>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
<Button Text="Benachrichtigungszeiten speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding SaveSchedulesCommand}" />
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Datenbank"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="{Binding CurrentDatabasePath, StringFormat='Aktiver Pfad: {0}'}"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="Auto,*"
ColumnSpacing="8">
<CheckBox IsChecked="{Binding UseExternalDatabase}" />
<Label Grid.Column="1"
Text="Externe Datenbank verwenden"
VerticalOptions="Center"
BackgroundColor="{DynamicResource SurfaceBackground}">
<VerticalStackLayout Spacing="12">
<Label Text="Aussehen"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
</Grid>
<Entry Text="{Binding ExternalDatabasePath}"
Placeholder="Ordner oder Dateipfad für externe DB" />
<Button Text="Datenbankpfad speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding SaveDatabaseLocationCommand}" />
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Alle Einträge löschen"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="Zum Bestätigen 'löschen' eingeben."
TextColor="{DynamicResource TextMuted}" />
<Entry Text="{Binding DeleteConfirmationText}"
Placeholder="löschen" />
<Button Text="Alles löschen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding DeleteAllDataCommand}" />
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="10">
<Label Text="Export"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="Farben werden direkt im Feld angezeigt. Über &#34;Farbe wählen&#34; öffnet sich ein einzelner Farbdialog mit Zurücksetzen, Abbrechen und Übernehmen."
TextColor="{DynamicResource TextMuted}" />
<Button Text="Export entleeren"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding ClearExportsCommand}" />
</VerticalStackLayout>
</Border>
<VerticalStackLayout x:Name="AppearanceColorsHost"
Spacing="10" />
<VerticalStackLayout BindableLayout.ItemsSource="{Binding StatusTexts}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:AppearanceTextItemViewModel">
<VerticalStackLayout Spacing="4"
Padding="0,6">
<Label Text="{Binding Title}"
TextColor="{DynamicResource TextPrimary}" />
<Entry Text="{Binding Value}" />
</VerticalStackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
<Grid ColumnDefinitions="*,*"
ColumnSpacing="12">
<Button Text="Speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding SaveAppearanceCommand}" />
<Button Grid.Column="1"
Text="Zurücksetzen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding ResetAppearanceCommand}" />
</Grid>
</VerticalStackLayout>
</Border>
</VerticalStackLayout>
<VerticalStackLayout IsVisible="{Binding IsNotificationsTabSelected}"
Spacing="16">
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}">
<VerticalStackLayout Spacing="12">
<Label Text="Push-Benachrichtigungen"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="Ein Zeitblock kann auf mehreren Wochentagen aktiv sein."
TextColor="{DynamicResource TextMuted}" />
<Button Text="Zeit hinzufügen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding AddScheduleCommand}" />
<VerticalStackLayout BindableLayout.ItemsSource="{Binding NotificationSchedules}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:NotificationScheduleItemViewModel">
<Border Padding="10"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackgroundAlt}">
<VerticalStackLayout Spacing="10">
<Grid ColumnDefinitions="*,Auto,Auto"
ColumnSpacing="8">
<TimePicker Time="{Binding SelectedTime}" />
<CheckBox Grid.Column="1"
IsChecked="{Binding IsEnabled}"
VerticalOptions="Center" />
<Label Grid.Column="2"
Text="Aktiv"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
</Grid>
<Grid ColumnDefinitions="*,*,*,*,*,*,*"
ColumnSpacing="6">
<Button Text="Mo"
Style="{StaticResource DayToggleButtonStyle}"
Command="{Binding ToggleMondayCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding Monday}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Button.Triggers>
</Button>
<Button Grid.Column="1"
Text="Di"
Style="{StaticResource DayToggleButtonStyle}"
Command="{Binding ToggleTuesdayCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding Tuesday}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Button.Triggers>
</Button>
<Button Grid.Column="2"
Text="Mi"
Style="{StaticResource DayToggleButtonStyle}"
Command="{Binding ToggleWednesdayCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding Wednesday}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Button.Triggers>
</Button>
<Button Grid.Column="3"
Text="Do"
Style="{StaticResource DayToggleButtonStyle}"
Command="{Binding ToggleThursdayCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding Thursday}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Button.Triggers>
</Button>
<Button Grid.Column="4"
Text="Fr"
Style="{StaticResource DayToggleButtonStyle}"
Command="{Binding ToggleFridayCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding Friday}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Button.Triggers>
</Button>
<Button Grid.Column="5"
Text="Sa"
Style="{StaticResource DayToggleButtonStyle}"
Command="{Binding ToggleSaturdayCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding Saturday}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Button.Triggers>
</Button>
<Button Grid.Column="6"
Text="So"
Style="{StaticResource DayToggleButtonStyle}"
Command="{Binding ToggleSundayCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding Sunday}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Button.Triggers>
</Button>
</Grid>
<Button Text="Entfernen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteScheduleCommand}"
CommandParameter="{Binding .}" />
</VerticalStackLayout>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
<Button Text="Benachrichtigungszeiten speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding SaveSchedulesCommand}" />
</VerticalStackLayout>
</Border>
</VerticalStackLayout>
<VerticalStackLayout IsVisible="{Binding IsDataManagementTabSelected}"
Spacing="16">
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}">
<VerticalStackLayout Spacing="12">
<Label Text="Tätigkeiten"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Grid ColumnDefinitions="*,Auto"
ColumnSpacing="10">
<Entry Text="{Binding NewActivityName}"
Placeholder="Neue Tätigkeit" />
<Button Grid.Column="1"
Text="Hinzufügen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding AddActivityCommand}" />
</Grid>
<VerticalStackLayout BindableLayout.ItemsSource="{Binding Activities}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:ActivityManageItemViewModel">
<Border Padding="10"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackgroundAlt}">
<VerticalStackLayout Spacing="8">
<Entry Text="{Binding Name}" />
<Label Text="{Binding UsageHint}"
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="*,*,*"
ColumnSpacing="8">
<Button Text="Speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.SaveActivityCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="1"
Text="Aktiv/Inaktiv"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.ToggleActivityActiveCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="2"
Text="Entfernen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteActivityCommand}"
CommandParameter="{Binding .}" />
</Grid>
</VerticalStackLayout>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}">
<VerticalStackLayout Spacing="12">
<Label Text="Symptome"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Grid ColumnDefinitions="*,Auto"
ColumnSpacing="10">
<Entry Text="{Binding NewSymptomName}"
Placeholder="Neues Symptom" />
<Button Grid.Column="1"
Text="Hinzufügen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding AddSymptomCommand}" />
</Grid>
<VerticalStackLayout BindableLayout.ItemsSource="{Binding Symptoms}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:SymptomManageItemViewModel">
<Border Padding="10"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackgroundAlt}">
<VerticalStackLayout Spacing="8">
<Entry Text="{Binding Name}" />
<Label Text="{Binding UsageHint}"
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="*,*,*"
ColumnSpacing="8">
<Button Text="Speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.SaveSymptomCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="1"
Text="Aktiv/Inaktiv"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.ToggleSymptomActiveCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="2"
Text="Entfernen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteSymptomCommand}"
CommandParameter="{Binding .}" />
</Grid>
</VerticalStackLayout>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}">
<VerticalStackLayout Spacing="12">
<Label Text="Datenbank"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="{Binding CurrentDatabasePath, StringFormat='Aktiver Pfad: {0}'}"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="Auto,*"
ColumnSpacing="8">
<CheckBox IsChecked="{Binding UseExternalDatabase}" />
<Label Grid.Column="1"
Text="Externe Datenbank verwenden"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
</Grid>
<Entry Text="{Binding ExternalDatabasePath}"
Placeholder="Ordner oder Dateipfad für externe DB" />
<Label Text="Für SQLite ist ein externer Dateipfad sinnvoll. Für echte Mehrbenutzer-Synchronisierung ist später eher ein eigener Server oder eine API-Schicht besser geeignet."
TextColor="{DynamicResource TextMuted}" />
<Button Text="Datenbankpfad speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding SaveDatabaseLocationCommand}" />
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}">
<VerticalStackLayout Spacing="12">
<Label Text="Alle Einträge löschen"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="Zum Bestätigen 'löschen' eingeben."
TextColor="{DynamicResource TextMuted}" />
<Entry Text="{Binding DeleteConfirmationText}"
Placeholder="löschen" />
<Button Text="Alles löschen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding DeleteAllDataCommand}" />
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}">
<VerticalStackLayout Spacing="10">
<Label Text="Export"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Button Text="Export entleeren"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding ClearExportsCommand}" />
</VerticalStackLayout>
</Border>
</VerticalStackLayout>
</VerticalStackLayout>
</ScrollView>
<Grid x:Name="ColorDialogOverlay"
IsVisible="False"
BackgroundColor="#99000000"
Padding="20"
InputTransparent="False">
<Border Padding="16"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
HorizontalOptions="Center"
VerticalOptions="Center"
MaximumWidthRequest="560">
<VerticalStackLayout Spacing="14">
<Label x:Name="ColorDialogTitleLabel"
Text="Farbe bearbeiten"
FontSize="22"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label x:Name="ColorDialogDefaultLabel"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="*,110"
ColumnSpacing="10">
<Entry x:Name="DialogHexEntry"
Placeholder="#112233"
TextChanged="OnDialogHexEntryTextChanged"
Unfocused="OnDialogHexEntryUnfocused" />
<Border Grid.Column="1"
x:Name="DialogPreviewBorder"
Padding="8"
Stroke="{DynamicResource Border}">
<Label x:Name="DialogPreviewLabel"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
LineBreakMode="NoWrap"
FontSize="12" />
</Border>
</Grid>
<Grid ColumnDefinitions="80,*,56"
ColumnSpacing="10">
<Label Text="Rot"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
<Slider x:Name="DialogRedSlider"
Grid.Column="1"
Minimum="0"
Maximum="255"
ValueChanged="OnDialogSliderValueChanged" />
<Label x:Name="DialogRedValueLabel"
Grid.Column="2"
HorizontalTextAlignment="End"
VerticalTextAlignment="Center"
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
</Grid>
<Grid ColumnDefinitions="80,*,56"
ColumnSpacing="10">
<Label Text="Grün"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
<Slider x:Name="DialogGreenSlider"
Grid.Column="1"
Minimum="0"
Maximum="255"
ValueChanged="OnDialogSliderValueChanged" />
<Label x:Name="DialogGreenValueLabel"
Grid.Column="2"
HorizontalTextAlignment="End"
VerticalTextAlignment="Center"
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
</Grid>
<Grid ColumnDefinitions="80,*,56"
ColumnSpacing="10">
<Label Text="Blau"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
<Slider x:Name="DialogBlueSlider"
Grid.Column="1"
Minimum="0"
Maximum="255"
ValueChanged="OnDialogSliderValueChanged" />
<Label x:Name="DialogBlueValueLabel"
Grid.Column="2"
HorizontalTextAlignment="End"
VerticalTextAlignment="Center"
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
</Grid>
<Grid ColumnDefinitions="80,*,56"
ColumnSpacing="10">
<Label Text="Hell"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
<Slider x:Name="DialogBrightnessSlider"
Grid.Column="1"
Minimum="0"
Maximum="200"
Value="100"
ValueChanged="OnDialogSliderValueChanged" />
<Label x:Name="DialogBrightnessValueLabel"
Grid.Column="2"
HorizontalTextAlignment="End"
VerticalTextAlignment="Center"
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
</Grid>
<Label Text="Zurücksetzen lädt nur den Standardwert in den Dialog. Erst Übernehmen speichert die Änderung. Abbrechen verwirft alles aus diesem Dialog wieder."
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="*,*,*"
ColumnSpacing="10">
<Button Text="Zurücksetzen"
Style="{StaticResource SecondaryButtonStyle}"
Clicked="OnResetColorDialogClicked" />
<Button Grid.Column="1"
Text="Abbrechen"
Style="{StaticResource SecondaryButtonStyle}"
Clicked="OnCancelColorDialogClicked" />
<Button Grid.Column="2"
Text="Übernehmen"
Style="{StaticResource PrimaryButtonStyle}"
Clicked="OnApplyColorDialogClicked" />
</Grid>
</VerticalStackLayout>
</Border>
</Grid>
</Grid>
</ContentPage>
+374
View File
@@ -1,20 +1,394 @@
using cfs_tracker.Helpers;
using cfs_tracker.ViewModels;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Graphics;
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace cfs_tracker.Views;
public partial class OptionsPage : ContentPage
{
private static readonly Regex HexColorRegex = new("^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$", RegexOptions.Compiled);
private readonly OptionsViewModel _viewModel;
private bool _isLoading;
private bool _appearanceEditorsBuilt;
private bool _appearanceEditorsDirty = true;
private AppearanceColorItemViewModel? _dialogItem;
private string _dialogInitialHex = string.Empty;
private string _dialogWorkingHex = string.Empty;
private bool _dialogIsUpdating;
public OptionsPage(OptionsViewModel viewModel)
{
InitializeComponent();
BindingContext = _viewModel = viewModel;
_viewModel.AppearanceColors.CollectionChanged += OnAppearanceColorsCollectionChanged;
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
}
protected override async void OnAppearing()
{
base.OnAppearing();
await LoadPageAsync();
}
private async Task LoadPageAsync()
{
_isLoading = true;
_appearanceEditorsDirty = true;
_appearanceEditorsBuilt = false;
CloseColorDialog();
if (AppearanceColorsHost is not null)
AppearanceColorsHost.Children.Clear();
await _viewModel.LoadAsync();
_isLoading = false;
EnsureAppearanceEditorsIfNeeded();
}
private void OnAppearanceColorsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
_appearanceEditorsDirty = true;
if (_isLoading)
return;
Dispatcher.Dispatch(EnsureAppearanceEditorsIfNeeded);
}
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(OptionsViewModel.SelectedTab))
Dispatcher.Dispatch(EnsureAppearanceEditorsIfNeeded);
}
private void EnsureAppearanceEditorsIfNeeded()
{
if (AppearanceColorsHost is null)
return;
if (!_viewModel.IsAppearanceTabSelected)
return;
if (_appearanceEditorsBuilt && !_appearanceEditorsDirty)
return;
BuildAppearanceEditors();
}
private void BuildAppearanceEditors()
{
if (AppearanceColorsHost is null)
return;
AppearanceColorsHost.Children.Clear();
foreach (var item in _viewModel.AppearanceColors)
AppearanceColorsHost.Children.Add(CreateColorEditor(item));
_appearanceEditorsBuilt = true;
_appearanceEditorsDirty = false;
}
private View CreateColorEditor(AppearanceColorItemViewModel item)
{
var normalizedHex = NormalizeHex(item.Value, item.Fallback);
item.Value = normalizedHex;
item.PreviewColor = ColorUtility.ParseColor(normalizedHex, item.Fallback);
var lastValidHex = normalizedHex;
var isUpdating = false;
var titleLabel = new Label
{
Text = item.Title,
FontAttributes = FontAttributes.Bold,
FontSize = 15
};
titleLabel.SetDynamicResource(Label.TextColorProperty, "TextPrimary");
var defaultLabel = new Label
{
Text = $"Standard: {NormalizeHex(item.Fallback, item.Fallback)}",
FontSize = 12
};
defaultLabel.SetDynamicResource(Label.TextColorProperty, "TextMuted");
var hexEntry = new Entry
{
Placeholder = "#112233",
HorizontalOptions = LayoutOptions.Fill,
ClearButtonVisibility = ClearButtonVisibility.WhileEditing,
BindingContext = item
};
hexEntry.SetBinding(Entry.TextProperty, nameof(AppearanceColorItemViewModel.Value), mode: BindingMode.TwoWay);
var previewBox = new BoxView
{
WidthRequest = 64,
HeightRequest = 34,
CornerRadius = 6,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
BindingContext = item
};
previewBox.SetBinding(BoxView.ColorProperty, nameof(AppearanceColorItemViewModel.PreviewColor));
var chooseButton = new Button
{
Text = "Farbe wählen"
};
chooseButton.SetDynamicResource(Button.BackgroundColorProperty, "ButtonSecondaryBackground");
chooseButton.SetDynamicResource(Button.TextColorProperty, "ButtonSecondaryText");
chooseButton.Clicked += (_, _) => OpenColorDialog(item);
var editorGrid = new Grid
{
ColumnSpacing = 10,
RowSpacing = 10,
ColumnDefinitions = new ColumnDefinitionCollection
{
new ColumnDefinition { Width = GridLength.Star },
new ColumnDefinition { Width = new GridLength(80) },
new ColumnDefinition { Width = new GridLength(140) }
}
};
editorGrid.Add(hexEntry);
editorGrid.Add(previewBox, 1, 0);
editorGrid.Add(chooseButton, 2, 0);
if (item is INotifyPropertyChanged notify)
{
notify.PropertyChanged += (_, args) =>
{
if (args.PropertyName == nameof(AppearanceColorItemViewModel.Value))
lastValidHex = NormalizeHex(item.Value, item.Fallback);
};
}
hexEntry.TextChanged += (_, args) =>
{
if (isUpdating)
return;
var text = args.NewTextValue?.Trim() ?? string.Empty;
if (!HexColorRegex.IsMatch(text))
return;
lastValidHex = NormalizeHex(text, item.Fallback);
item.PreviewColor = ColorUtility.ParseColor(lastValidHex, item.Fallback);
};
hexEntry.Unfocused += (_, _) =>
{
var text = hexEntry.Text?.Trim() ?? string.Empty;
isUpdating = true;
if (HexColorRegex.IsMatch(text))
{
lastValidHex = NormalizeHex(text, item.Fallback);
item.Value = lastValidHex;
item.PreviewColor = ColorUtility.ParseColor(lastValidHex, item.Fallback);
}
else
{
item.Value = lastValidHex;
item.PreviewColor = ColorUtility.ParseColor(lastValidHex, item.Fallback);
}
isUpdating = false;
};
var content = new VerticalStackLayout
{
Spacing = 8,
Children =
{
titleLabel,
defaultLabel,
editorGrid
}
};
var outerBorder = new Border
{
Padding = new Thickness(10),
StrokeThickness = 1,
Content = content
};
outerBorder.SetDynamicResource(Border.StrokeProperty, "Border");
outerBorder.SetDynamicResource(VisualElement.BackgroundColorProperty, "SurfaceBackgroundAlt");
return outerBorder;
}
private void OpenColorDialog(AppearanceColorItemViewModel item)
{
_dialogItem = item;
_dialogInitialHex = NormalizeHex(item.Value, item.Fallback);
_dialogWorkingHex = _dialogInitialHex;
ColorDialogTitleLabel.Text = item.Title;
ColorDialogDefaultLabel.Text = $"Standardwert: {NormalizeHex(item.Fallback, item.Fallback)}";
ApplyDialogHex(_dialogWorkingHex, resetBrightness: true);
ColorDialogOverlay.IsVisible = true;
DialogHexEntry.Focus();
}
private void CloseColorDialog()
{
_dialogItem = null;
_dialogInitialHex = string.Empty;
_dialogWorkingHex = string.Empty;
_dialogIsUpdating = false;
if (ColorDialogOverlay is not null)
ColorDialogOverlay.IsVisible = false;
}
private void ApplyDialogHex(string hex, bool resetBrightness)
{
if (_dialogItem is null)
return;
var normalizedHex = NormalizeHex(hex, _dialogItem.Fallback);
var parsed = ColorUtility.ParseColor(normalizedHex, _dialogItem.Fallback);
_dialogIsUpdating = true;
DialogHexEntry.Text = normalizedHex;
DialogRedSlider.Value = ClampByte(parsed.Red * 255d);
DialogGreenSlider.Value = ClampByte(parsed.Green * 255d);
DialogBlueSlider.Value = ClampByte(parsed.Blue * 255d);
if (resetBrightness)
DialogBrightnessSlider.Value = 100;
UpdateDialogPreview(normalizedHex);
UpdateDialogValueLabels();
_dialogIsUpdating = false;
_dialogWorkingHex = normalizedHex;
}
private void UpdateDialogHexFromSliders()
{
if (_dialogItem is null || _dialogIsUpdating)
return;
_dialogIsUpdating = true;
var brightnessFactor = DialogBrightnessSlider.Value / 100d;
var red = ClampByte(DialogRedSlider.Value * brightnessFactor);
var green = ClampByte(DialogGreenSlider.Value * brightnessFactor);
var blue = ClampByte(DialogBlueSlider.Value * brightnessFactor);
_dialogWorkingHex = $"#{red:X2}{green:X2}{blue:X2}";
DialogHexEntry.Text = _dialogWorkingHex;
UpdateDialogPreview(_dialogWorkingHex);
UpdateDialogValueLabels();
_dialogIsUpdating = false;
}
private void UpdateDialogPreview(string hex)
{
if (_dialogItem is null)
return;
var normalizedHex = NormalizeHex(hex, _dialogItem.Fallback);
var parsed = ColorUtility.ParseColor(normalizedHex, _dialogItem.Fallback);
DialogPreviewBorder.BackgroundColor = parsed;
DialogPreviewLabel.Text = normalizedHex.ToUpperInvariant();
DialogPreviewLabel.TextColor = GetContrastColor(parsed);
}
private void UpdateDialogValueLabels()
{
DialogRedValueLabel.Text = $"{Math.Round(DialogRedSlider.Value):0}";
DialogGreenValueLabel.Text = $"{Math.Round(DialogGreenSlider.Value):0}";
DialogBlueValueLabel.Text = $"{Math.Round(DialogBlueSlider.Value):0}";
DialogBrightnessValueLabel.Text = $"{Math.Round(DialogBrightnessSlider.Value):0}%";
}
private void OnDialogHexEntryTextChanged(object? sender, TextChangedEventArgs e)
{
if (_dialogItem is null || _dialogIsUpdating)
return;
var text = e.NewTextValue?.Trim() ?? string.Empty;
if (!HexColorRegex.IsMatch(text))
return;
ApplyDialogHex(text, resetBrightness: true);
}
private void OnDialogHexEntryUnfocused(object? sender, FocusEventArgs e)
{
if (_dialogItem is null || _dialogIsUpdating)
return;
var text = DialogHexEntry.Text?.Trim() ?? string.Empty;
if (HexColorRegex.IsMatch(text))
{
ApplyDialogHex(text, resetBrightness: true);
return;
}
ApplyDialogHex(_dialogWorkingHex, resetBrightness: false);
}
private void OnDialogSliderValueChanged(object? sender, ValueChangedEventArgs e)
{
UpdateDialogHexFromSliders();
}
private void OnResetColorDialogClicked(object? sender, EventArgs e)
{
if (_dialogItem is null)
return;
ApplyDialogHex(_dialogItem.Fallback, resetBrightness: true);
}
private void OnCancelColorDialogClicked(object? sender, EventArgs e)
{
if (_dialogItem is not null)
ApplyDialogHex(_dialogInitialHex, resetBrightness: true);
CloseColorDialog();
}
private void OnApplyColorDialogClicked(object? sender, EventArgs e)
{
if (_dialogItem is null)
return;
var finalHex = NormalizeHex(_dialogWorkingHex, _dialogItem.Fallback);
_dialogItem.Value = finalHex;
_dialogItem.PreviewColor = ColorUtility.ParseColor(finalHex, _dialogItem.Fallback);
CloseColorDialog();
}
private string NormalizeHex(string? value, string fallback)
{
var parsed = ColorUtility.ParseColor(value, fallback);
var red = ClampByte(parsed.Red * 255d);
var green = ClampByte(parsed.Green * 255d);
var blue = ClampByte(parsed.Blue * 255d);
return $"#{red:X2}{green:X2}{blue:X2}";
}
private static int ClampByte(double value) => Math.Clamp((int)Math.Round(value), 0, 255);
private static Color GetContrastColor(Color color)
{
var luminance = (0.299 * color.Red) + (0.587 * color.Green) + (0.114 * color.Blue);
return luminance >= 0.6 ? Colors.Black : Colors.White;
}
}
+94 -25
View File
@@ -1,12 +1,42 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
x:DataType="viewModels:QuickEntryViewModel"
x:Class="cfs_tracker.Views.QuickEntryPage"
Title="Eintrag"
BackgroundColor="{DynamicResource AppBackground}">
<ContentPage
x:Class="cfs_tracker.Views.QuickEntryPage"
x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
x:DataType="viewModels:QuickEntryViewModel"
Title="Eintrag"
BackgroundColor="{DynamicResource AppBackground}">
<ContentPage.Resources>
<Style x:Key="SymptomToggleBorderStyle" TargetType="Border">
<Setter Property="Padding" Value="12,10" />
<Setter Property="StrokeThickness" Value="1" />
<Setter Property="Stroke" Value="{DynamicResource Border}" />
<Setter Property="StrokeShape" Value="RoundRectangle 12" />
<Setter Property="BackgroundColor" Value="{DynamicResource ButtonPrimaryBackground}" />
<Style.Triggers>
<DataTrigger TargetType="Border"
Binding="{Binding IsSelected}"
Value="True">
<Setter Property="BackgroundColor" Value="{DynamicResource ButtonSecondaryBackground}" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="SymptomToggleLabelStyle" TargetType="Label">
<Setter Property="VerticalOptions" Value="Center" />
<Setter Property="TextColor" Value="{DynamicResource ButtonPrimaryText}" />
<Style.Triggers>
<DataTrigger TargetType="Label"
Binding="{Binding IsSelected}"
Value="True">
<Setter Property="TextColor" Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentPage.Resources>
<ScrollView>
<VerticalStackLayout Padding="16" Spacing="16">
@@ -33,7 +63,7 @@
TextColor="{DynamicResource TextPrimary}" />
<Picker Title="Tageszeit"
ItemsSource="{Binding Parts}"
ItemDisplayBinding="{Binding Name}"
ItemDisplayBinding="{Binding Name, x:DataType={x:Null}}"
SelectedItem="{Binding SelectedPart}" />
</VerticalStackLayout>
</Border>
@@ -48,33 +78,72 @@
TextColor="{DynamicResource TextPrimary}" />
<Picker Title="Tätigkeit"
ItemsSource="{Binding Activities}"
ItemDisplayBinding="{Binding Name}"
ItemDisplayBinding="{Binding Name, x:DataType={x:Null}}"
SelectedItem="{Binding SelectedActivity}" />
<Label Text="Dauer (HH:mm)"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<TimePicker Time="{Binding ActivityDuration}"
Format="HH:mm" />
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="8">
<Label Text="Symptome"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<VerticalStackLayout BindableLayout.ItemsSource="{Binding Symptoms}"
Spacing="6">
Spacing="8">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:SelectableSymptomItemViewModel">
<Grid ColumnDefinitions="Auto,*"
ColumnSpacing="10"
Padding="0,4">
<CheckBox IsChecked="{Binding IsSelected}" />
<Label Grid.Column="1"
Text="{Binding Name}"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
</Grid>
<Border Padding="12,10"
StrokeThickness="1"
Stroke="{DynamicResource Border}"
StrokeShape="RoundRectangle 12"
BackgroundColor="{DynamicResource ButtonPrimaryBackground}">
<Border.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.ToggleSymptomCommand}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
<Border.Triggers>
<DataTrigger TargetType="Border"
Binding="{Binding IsSelected}"
Value="True">
<Setter Property="BackgroundColor"
Value="{DynamicResource ButtonSecondaryBackground}" />
</DataTrigger>
</Border.Triggers>
<Grid ColumnDefinitions="Auto,*"
ColumnSpacing="12">
<CheckBox IsChecked="{Binding IsSelected}"
InputTransparent="True"
Color="White"
VerticalOptions="Center" />
<Label Grid.Column="1"
Text="{Binding Name}"
VerticalOptions="Center"
TextColor="{DynamicResource ButtonPrimaryText}">
<Label.Triggers>
<DataTrigger TargetType="Label"
Binding="{Binding IsSelected}"
Value="True">
<Setter Property="TextColor"
Value="{DynamicResource ButtonSecondaryText}" />
</DataTrigger>
</Label.Triggers>
</Label>
</Grid>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
+5 -7
View File
@@ -5,7 +5,6 @@ namespace cfs_tracker.Views;
public partial class QuickEntryPage : ContentPage, IQueryAttributable
{
private readonly QuickEntryViewModel _vm;
private bool _initialized;
public QuickEntryPage(QuickEntryViewModel vm)
{
@@ -16,11 +15,6 @@ public partial class QuickEntryPage : ContentPage, IQueryAttributable
protected override async void OnAppearing()
{
base.OnAppearing();
if (_initialized)
return;
_initialized = true;
await _vm.InitializeAsync();
}
@@ -28,9 +22,13 @@ public partial class QuickEntryPage : ContentPage, IQueryAttributable
{
query.TryGetValue("date", out var dateValue);
query.TryGetValue("entryId", out var entryIdValue);
query.TryGetValue("status", out var statusValue);
query.TryGetValue("commit", out var commitValue);
_vm.ApplyQuery(
dateValue?.ToString() ?? string.Empty,
entryIdValue?.ToString());
entryIdValue?.ToString(),
statusValue?.ToString(),
commitValue?.ToString());
}
}
+1 -1
View File
@@ -50,7 +50,7 @@
StrokeShape="RoundRectangle 14">
<Border.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.OpenDayCommand}"
Command="{Binding Source={RelativeSource AncestorType={x:Type viewModels:WeekViewModel}}, Path=OpenDayCommand, x:DataType='viewModels:WeekViewModel'}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
+1 -1
View File
@@ -77,7 +77,7 @@
StrokeShape="RoundRectangle 8">
<Border.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.OpenDayCommand}"
Command="{Binding Source={RelativeSource AncestorType={x:Type viewModels:YearViewModel}}, Path=OpenDayCommand, x:DataType='viewModels:YearViewModel'}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
+1 -1
View File
@@ -1,5 +1,5 @@
using System.Diagnostics;
using cfs_tracker.ViewModels;
using System.Diagnostics;
namespace cfs_tracker.Views;
+7 -1
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net10.0-android;net10.0-windows10.0.19041.0</TargetFrameworks>
<OutputType>Exe</OutputType>
@@ -12,6 +12,7 @@
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
<ApplicationVersion>1</ApplicationVersion>
<WindowsPackageType>None</WindowsPackageType>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion>
</PropertyGroup>
<PropertyGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">
<SupportedOSPlatformVersion>21.0</SupportedOSPlatformVersion>
@@ -36,8 +37,13 @@
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="10.0.5" />
<PackageReference Include="sqlite-net-pcl" Version="1.9.172" />
<PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.11" />
<PackageReference Include="System.Formats.Nrbf" Version="10.0.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="SQLitePCLRaw.lib.e_sqlite3.android" Version="2.1.11" />
</ItemGroup>
<ItemGroup Condition="$([System.String]::Copy('$(TargetFramework)').Contains('-windows'))">
<PackageReference Include="System.Drawing.Common" Version="10.0.5" />
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.3" />
</ItemGroup>
</Project>