using cfs_tracker.Helpers; using cfs_tracker.ViewModels; using Microsoft.Maui.Layouts; using System.Collections.Specialized; using System.ComponentModel; using System.Text.RegularExpressions; 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 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 previewBox = new BoxView { WidthRequest = 84, HeightRequest = 42, CornerRadius = 8, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center, BindingContext = item, Margin = new Thickness(0, 0, 10, 10) }; previewBox.SetBinding(BoxView.ColorProperty, nameof(AppearanceColorItemViewModel.PreviewColor)); var chooseButton = new Button { Text = "Farbe wählen", LineBreakMode = LineBreakMode.WordWrap, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center, Margin = new Thickness(0, 0, 0, 10) }; chooseButton.SetDynamicResource(Button.BackgroundColorProperty, "ButtonSecondaryBackground"); chooseButton.SetDynamicResource(Button.TextColorProperty, "ButtonSecondaryText"); chooseButton.Clicked += (_, _) => OpenColorDialog(item); var actionLayout = new FlexLayout { Direction = FlexDirection.Row, Wrap = FlexWrap.Wrap, AlignItems = FlexAlignItems.Center, JustifyContent = FlexJustify.Start, Children = { previewBox, chooseButton } }; var content = new VerticalStackLayout { Spacing = 8, Children = { titleLabel, defaultLabel, actionLayout } }; 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; } }