Skip to content

Commit 521e136

Browse files
committed
EVEN MORE RESILIENCY
1 parent bf48c40 commit 521e136

File tree

1 file changed

+53
-27
lines changed

1 file changed

+53
-27
lines changed

buttons-injection.js

Lines changed: 53 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -18,105 +18,131 @@ function doCustomModificationsExist() {
1818
}
1919

2020
/**
21-
* Inserts custom buttons, separators and settings toggles into the webpage and starts resiliency checks if enabled.
22-
* @param {boolean} enableResiliency - Flag to enable or disable resiliency checks.
23-
* @param {string} activeWebsite - The identifier of the active website.
21+
* Checks for the existence of the custom modifications and injects the custom buttons,
22+
* separators, and toggle switches into the webpage. It also starts resiliency checks
23+
* to ensure that the modifications are re‑injected if they disappear (for example, after SPA navigation).
24+
*
25+
* @param {boolean} enableResiliency - Flag indicating whether resiliency checks should be enabled.
26+
* @param {string} activeWebsite - The identifier of the active website (not used directly in this function).
2427
*/
2528
function buttonBoxCheckingAndInjection(enableResiliency = true, activeWebsite) {
2629
logConCgp('[button-injection] Checking if mods already exist...');
30+
31+
// If modifications already exist and resiliency is disabled, skip the injection.
2732
if (doCustomModificationsExist() && !enableResiliency) {
2833
logConCgp('[button-injection] Modifications already exist and resiliency is disabled. Skipping initialization.');
2934
return;
3035
}
3136

32-
// Load the saved states of toggle switches
37+
// Load the saved states of toggle switches (e.g., Auto-send, Hotkeys) from localStorage.
3338
MaxExtensionInterface.loadToggleStates();
3439
logConCgp('[button-injection] Toggle states have been loaded.');
3540

36-
// Initialize the shared flag
41+
// Flag to ensure we only process one target container (if multiple callbacks are fired).
3742
let targetFound = false;
3843

39-
// Define the selector to wait for using InjectionTargetsOnWebsite
44+
// Get the list of selectors for the containers into which the buttons should be injected.
4045
const selectors = window.InjectionTargetsOnWebsite.selectors.containers;
41-
// A unified callback function will search for div where we will insert stuff
46+
47+
/**
48+
* Unified callback function that is called when a target container is detected in the DOM.
49+
* This function injects the custom elements and starts the resiliency mechanism.
50+
*
51+
* @param {HTMLElement} targetDiv - The container element in which to inject the custom buttons.
52+
*/
4253
const handleTargetDiv = (targetDiv) => {
4354
if (!targetFound) {
44-
targetFound = true; // Set the flag to prevent other callbacks from executing
55+
targetFound = true; // Prevent further executions for this injection cycle.
4556
logConCgp('[button-injection] Target div has been found:', targetDiv);
46-
// Insert custom elements into the target container on the webpage
57+
58+
// Insert custom elements (custom send buttons and toggles) into the target container.
4759
window.MaxExtensionButtonsInit.createAndInsertCustomElements(targetDiv);
4860

49-
// Initiate resiliency checks only after the first successful modification
50-
if (!window.globalMaxExtensionConfig.firstModificationCompleted && enableResiliency) {
51-
window.globalMaxExtensionConfig.firstModificationCompleted = true;
52-
logConCgp('[button-injection] First modification complete. Starting resiliency checks.');
61+
// Always start resiliency checks when enableResiliency is true.
62+
// This change removes the one-time flag (firstModificationCompleted) dependency.
63+
if (enableResiliency) {
64+
logConCgp('[button-injection] Starting resiliency checks.');
5365
commenceEnhancedResiliencyChecks();
5466
}
5567
}
5668
};
5769

58-
// Wait for the target element to appear in the DOM and then handle it
70+
// Use a utility function to wait for the target container(s) to appear in the DOM.
5971
MaxExtensionUtils.waitForElements(selectors, handleTargetDiv);
6072
}
6173

74+
75+
76+
77+
6278
/**
6379
* The resiliency mechanism continuously monitors the DOM to verify that custom modifications remain intact.
6480
* It performs periodic checks and counts consecutive iterations where the modifications are absent.
6581
* Once a predefined threshold is reached, or after a maximum number of iterations, it triggers a reinjection of the elements.
6682
* This approach ensures the extension maintains functionality even when the webpage dynamically resets or modifies its content.
6783
*/
84+
85+
// Global variable to store the current resiliency check timer
86+
window.OneClickPropmts_currentResiliencyTimeout = null;
87+
// fucntion that uses it:
6888
function commenceEnhancedResiliencyChecks() {
89+
// Cancel any previous resiliency check
90+
if (window.OneClickPropmts_currentResiliencyTimeout) {
91+
clearTimeout(window.OneClickPropmts_currentResiliencyTimeout);
92+
window.OneClickPropmts_currentResiliencyTimeout = null;
93+
logConCgp('[button-injection] Previous resiliency check canceled due to new initialization.');
94+
}
95+
6996
let consecutiveClearCheckCount = 0;
7097
const requiredConsecutiveClearChecks = 2; // Missing for this many consecutive checks triggers reinjection
71-
const maximumTotalIterations = 160;
98+
const maximumTotalIterations = 30;
7299
let totalIterationsPerformed = 0;
73100

74101
logConCgp('[button-injection] Beginning enhanced resiliency checks with dynamic interval...');
75102
logConCgp(`[button-injection] Requires ${requiredConsecutiveClearChecks} consecutive clear checks.`);
76103

77-
// The adaptive check function uses a dynamic delay based on current state.
104+
// Adaptive check function that adjusts the delay based on the state
78105
function adaptiveCheck() {
79106
totalIterationsPerformed++;
80107
const modificationsExist = doCustomModificationsExist();
81108
let delay;
82109

83110
if (modificationsExist) {
84-
// When modifications are present, reset the missing counter.
85-
consecutiveClearCheckCount = 0;
86-
// Log only every 10 iterations to avoid excessive logs.
111+
consecutiveClearCheckCount = 0; // Reset counter if modifications are present
112+
// Log "everything is okay" only every 10 iterations to avoid log spam.
87113
if (totalIterationsPerformed % 10 === 0) {
88114
logConCgp(`[button-injection] Modifications detected. Total iterations: ${totalIterationsPerformed}/${maximumTotalIterations}.`);
89115
}
90-
// Slow down checks when everything is okay.
91-
delay = 500;
116+
// Slow down the checks when modifications are present
117+
delay = 100;
92118
} else {
93119
consecutiveClearCheckCount++;
94120
logConCgp(`[button-injection] No modifications detected. Consecutive missing: ${consecutiveClearCheckCount}/${requiredConsecutiveClearChecks}`);
95-
// Rapid checks when modifications are missing.
121+
// Use a faster check interval when modifications are missing
96122
delay = 50;
97123
}
98124

99-
// If we have reached the required consecutive clear checks, reinject.
125+
// If the required consecutive missing checks have been reached, trigger reinjection.
100126
if (consecutiveClearCheckCount >= requiredConsecutiveClearChecks) {
101127
logConCgp('[button-injection] Required consecutive clear checks achieved. Proceeding with initialization.');
102128
enforceResiliencyMeasures();
103129
return;
104130
}
105131

106-
// Safety: if maximum iterations have been reached, decide based on current state.
132+
// Safety: If maximum iterations have been reached, decide based on current state.
107133
if (totalIterationsPerformed >= maximumTotalIterations) {
108134
logConCgp('[button-injection] Maximum iterations reached.');
109135
if (!doCustomModificationsExist()) {
110136
logConCgp('[button-injection] No modifications present after maximum iterations. Proceeding cautiously.');
111137
enforceResiliencyMeasures();
112138
} else {
113-
logConCgp('[button-injection] Modifications still present after maximum iterations. Aborting initialization.');
139+
logConCgp('[button-injection] Modifications still present after maximum iterations. We had succesfully injected buttons and they stayed there. Resiliency checks will be disabled.');
114140
}
115141
return;
116142
}
117143

118-
// Schedule the next check with the dynamic delay.
119-
setTimeout(adaptiveCheck, delay);
144+
// Schedule the next check with the determined delay and store its timer.
145+
window.OneClickPropmts_currentResiliencyTimeout = setTimeout(adaptiveCheck, delay);
120146
}
121147

122148
adaptiveCheck();

0 commit comments

Comments
 (0)