Improved Edit profile state management, by putting warnings in a lambda dict, to reduce nesting

This commit is contained in:
SimplifiedPrivacy 2026-11-08 20:22:30 -05:00
parent 302eea9945
commit 39d554be4b
2 changed files with 86 additions and 88 deletions

View file

@ -35,6 +35,7 @@ class RegistrationState:
self.original_choices = {}
self.proceed = False
self.warnings_dict = {}
self.key_choices = []
# Maps a category to the function that validates its current selection.
self._filter_map = {
@ -87,7 +88,9 @@ class RegistrationState:
"browser": (get_app_display_data, 0),
"name": (None, None)
}
for category, (loader_func, default_idx) in load_config.items():
self.key_choices.append(category)
if loader_func is None:
self._no_premade_choices(category=category, default_data=default_data)
continue
@ -277,112 +280,88 @@ class RegistrationState:
def get_final_choices(self):
return self.selections
def get_warning_skip_list(self):
"""This is the warning skip list, that affects if the user gets a visual warning."""
original_type = self.original_choices.get("type", None)
new_type = self.selections.get("type", None)
if original_type == ProfileType.SYSTEM and new_type == ProfileType.SESSION:
logger.info("It's SYSTEM to session")
return ["browser"]
else:
return []
def _get_transition_skip(self, skip_type="real"):
"""
Handles mapping of profile transitions to skip lists.
skip_type: 'real' for data changes, 'warning' for UI alerts.
"""
# Define transition rules: (original, new) -> [keys to skip]
rules = {
"warning": {
(ProfileType.SYSTEM, ProfileType.SESSION): ["browser"],
},
"real": {
# If new is SYSTEM and original is either SYSTEM or None
# We handle the 'None' case by checking the transition specifically
(ProfileType.SYSTEM, ProfileType.SYSTEM): ["browser", "resolution"],
(None, ProfileType.SYSTEM): ["browser", "resolution"],
}
}
def _get_skip_list(self):
"""This is the 'real' skip list that affects if it actually gets changed."""
new_type = self.selections.get("type", None)
original_type = self.original_choices.get("type", None)
if new_type == ProfileType.SYSTEM:
if original_type == ProfileType.SYSTEM or None:
return ["browser", "resolution"]
return None
orig = self.original_choices.get("type")
new = self.selections.get("type")
return rules.get(skip_type, {}).get((orig, new), [])
def whats_different(self):
"""Creates a dictionary of the difference between the current selections and the original choices."""
different = {}
"""Creates a dictionary of actual value differences."""
if not self.original_choices:
return self.selections
# print(f"self.selections is {self.selections}")
# print(f"self.original_choices is {self.original_choices}")
different = {}
# skip_list = self._get_transition_skip(skip_type="real")
skip_list = self._get_skip_list()
# print(f"skip_list is {skip_list}")
# Get a union of all keys to ensure we catch removals and additions
all_keys = set(self.selections.keys()) | set(self.original_choices.keys())
for category, value in self.selections.items():
if skip_list:
if category in skip_list:
print(f"skipping {category}")
continue
print(f"checking {category}")
# wasn't in the original, but it's in the new selections:
try:
if not self.original_choices[category]:
different[category] = value
continue
except KeyError:
print(f"setting category {category} as changed")
different[category] = value
for key in all_keys:
# only pay attention to the universe of keys we actually are deciding here
if key not in self.key_choices:
continue
# not in the new choices, but it is in the original:
if not self.selections[category] and self.original_choices[category]:
different[category] = None
continue
# if key in skip_list:
# continue
# actually different:
if self.original_choices[category] != self.selections[category]:
print(f"It's actually different for {category}")
different[category] = value
old_val = self.original_choices.get(key)
new_val = self.selections.get(key)
if old_val != new_val:
different[key] = new_val
return different
def is_anything_different(self) -> bool:
return bool(self.whats_different())
def before_we_proceed(self) -> PreEdit:
different_dict = self.whats_different()
# print(f"different_dict is {different_dict}")
if not different_dict:
return PreEdit(True, False, None, None)
different_keys = different_dict.keys()
warning_keys = []
# 1. Filter differences by the warning skip list
warning_skip = self._get_transition_skip(skip_type="warning")
warning_keys = [k for k in different_dict if k not in warning_skip]
# 2. Map keys to their specific warning messages
WARNING_MESSAGES = {
"location": lambda: "If you change the location, it wipes the subscription, proceed?"
if not profile_can_respawn(self.profile_id).valid
and profile_can_respawn(self.profile_id).error_type != ResultError.SUBSCRIPTION
else None,
"browser": lambda: "If you change the browser, it wipes the cookies/bookmarks, proceed?"
}
warnings_dict = {}
skip_list = self.get_warning_skip_list()
for key in warning_keys:
rule = WARNING_MESSAGES.get(key)
msg = rule() if callable(rule) else rule
if msg:
warnings_dict[key] = msg
if skip_list:
for each_key in different_keys:
if not each_key in skip_list:
warning_keys.append(each_key)
else:
warning_keys = different_keys
if "location" in warning_keys:
# Assuming profile_can_respawn is defined elsewhere
respawn_possible = profile_can_respawn(self.profile_id)
if not respawn_possible.valid and respawn_possible.error_type != ResultError.SUBSCRIPTION:
warnings_dict["location"] = "If you change the location, it wipes the subscription, proceed?"
if "browser" in warning_keys:
warnings_dict["browser"] = "If you change the browser, it wipes the cookies/bookmarks, proceed?"
has_warnings = len(warnings_dict) > 0
if not has_warnings:
return PreEdit(True, False, None, different_dict)
# Update state
has_warnings = bool(warnings_dict)
self.warnings_dict = warnings_dict
if self.proceed:
return PreEdit(True, has_warnings, warnings_dict, different_dict)
# Determine if we can proceed based on the 'proceed' state and whether warnings exist
can_proceed = self.proceed if has_warnings else True
return PreEdit(can_proceed, has_warnings, warnings_dict, different_dict)
return PreEdit(False, has_warnings, warnings_dict, different_dict)
def is_anything_different(self):
different_dict = self.whats_different()
return bool(different_dict)

View file

@ -143,6 +143,8 @@ class EditPage(Page):
def proceed_with_edit(self, different_content):
print(f"different_content is {different_content}")
edit_profile(
profile_id=self.profile_id,
potential_data=different_content,
@ -162,10 +164,27 @@ class EditPage(Page):
self.warn_or_proceed()
def reverse(self):
if self.state.is_anything_different():
print("unsubmitted changes")
# nothing changed, bounce:
if not self.state.is_anything_different():
self.actually_leave()
return
error_popup = ErrorPopup(
choice=True,
title="Unsaved changes",
message="Are you sure you want to leave with unfinished changes?",
end_app=False,
on_answer=self._after_reverse_decision,
passed_result=None,
)
error_popup.show()
def _after_reverse_decision(self, boolean_choice: bool, passed_result=None):
if boolean_choice:
self.actually_leave()
def actually_leave(self):
self.created_display = False
self.custom_window.navigator.navigate("menu")