-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfloating-panel-settings.js
More file actions
287 lines (267 loc) · 12.1 KB
/
floating-panel-settings.js
File metadata and controls
287 lines (267 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Version: 1.1
//
// Documentation:
// This file handles settings persistence and profile management for the floating panel.
// It includes methods for loading/saving panel settings, debouncing saves, and profile switching.
// These functions extend the window.MaxExtensionFloatingPanel namespace.
//
// Key Components:
// 1. Settings Management - Loading and saving panel configuration per website
// 2. Storage Integration - Communication with the config.js service worker
// 3. Profile Management - Loading available profiles and handling profile switching
// 4. Initialization - Setup of the floating panel system
//
// Key Methods:
// - loadPanelSettings(): Fetches settings from service worker for current hostname
// - savePanelSettings(): Stores current panel settings via service worker
// - debouncedSavePanelSettings(): Throttles saves to improve performance
// - loadAvailableProfiles(): Gets profile list from service worker
// - getCurrentProfile(): Fetches and sets current active profile
// - switchToProfile(): Changes active profile and updates panel content
// - initialize(): Sets up the floating panel by creating UI and loading settings
//
// Implementation Details:
// - All settings are stored with the prefix 'floating_panel_' followed by hostname
// - Settings are loaded asynchronously via chrome.runtime.sendMessage
// - The panel uses a debounce mechanism (150ms) to avoid excessive storage writes
// - Each website has its own panel settings (position, size, visibility)
// - Profile switching refreshes the buttons shown in the panel
//
// Dependencies:
// - floating-panel.js: Provides the namespace and shared properties
// - floating-panel-ui-creation.js: Provides UI creation methods
// - floating-panel-ui-interaction.js: Provides UI interaction methods
// - config.js (Service Worker): Handles persistent storage operations
'use strict';
/**
* Debounced version of savePanelSettings.
* Waits 150ms after the last call before actually saving.
*/
window.MaxExtensionFloatingPanel.debouncedSavePanelSettings = function () {
if (this.savePositionTimer) {
clearTimeout(this.savePositionTimer);
}
this.savePositionTimer = setTimeout(() => {
this.savePanelSettings();
this.savePositionTimer = null;
}, 150);
};
/**
* Loads panel settings from Chrome's storage via the config service worker.
* If no settings are found, default settings are used.
*/
window.MaxExtensionFloatingPanel.loadPanelSettings = function () {
try {
// Initialize with default settings immediately to avoid null references.
this.currentPanelSettings = { ...this.defaultPanelSettings };
const hostname = window.location.hostname;
// Request settings from the service worker.
chrome.runtime.sendMessage({
type: 'getFloatingPanelSettings',
hostname: hostname
}, (response) => {
if (chrome.runtime.lastError) {
logConCgp('[floating-panel] Error loading panel settings:', chrome.runtime.lastError.message);
this.currentPanelSettings = { ...this.defaultPanelSettings };
return;
}
if (response && response.settings) {
this.currentPanelSettings = response.settings;
logConCgp('[floating-panel] Loaded panel settings for ' + hostname);
} else {
logConCgp('[floating-panel] Using default panel settings for ' + hostname);
}
// Apply settings to panel if it exists.
if (this.panelElement) {
this.updatePanelFromSettings();
// After applying saved position, clamp within the current viewport once
if (typeof this.ensurePanelWithinViewport === 'function') {
try { requestAnimationFrame(() => this.ensurePanelWithinViewport()); } catch (_) { this.ensurePanelWithinViewport(); }
}
}
// Mark settings as loaded so toggling logic can respect saved position
this.panelSettingsLoaded = true;
// Initial panel state restoration is now handled by init.js (the Director).
});
} catch (error) {
logConCgp('[floating-panel] Error loading panel settings: ' + error.message);
this.currentPanelSettings = { ...this.defaultPanelSettings };
// Even on error, mark as loaded to avoid overwriting user position on toggle
this.panelSettingsLoaded = true;
}
};
/**
* Saves panel settings to Chrome's storage via the config service worker.
* Returns a Promise that resolves on success and rejects on failure.
*/
window.MaxExtensionFloatingPanel.savePanelSettings = function () {
return new Promise((resolve, reject) => {
try {
const hostname = window.location.hostname;
chrome.runtime.sendMessage({
type: 'saveFloatingPanelSettings',
hostname: hostname,
settings: this.currentPanelSettings
}, (response) => {
if (chrome.runtime.lastError) {
const errorMsg = `Failed to save panel settings: ${chrome.runtime.lastError.message}`;
logConCgp(`[floating-panel] ${errorMsg}`);
reject(new Error(errorMsg));
} else if (response && response.success) {
logConCgp('[floating-panel] Saved panel settings for ' + hostname);
resolve();
} else {
const errorMsg = `Save failed with response: ${JSON.stringify(response)}`;
logConCgp(`[floating-panel] ${errorMsg}`);
reject(new Error(errorMsg));
}
});
} catch (error) {
const errorMsg = `Error saving panel settings: ${error.message}`;
logConCgp(`[floating-panel] ${errorMsg}`);
reject(error);
}
});
};
/**
* Loads global (non-profile) settings from the service worker.
*/
window.MaxExtensionFloatingPanel.loadGlobalSettings = function () {
chrome.runtime.sendMessage({ type: 'getGlobalSettings' }, (response) => {
if (chrome.runtime.lastError) {
logConCgp('[floating-panel] Error loading global settings:', chrome.runtime.lastError.message);
return;
}
if (response && response.settings) {
window.MaxExtensionGlobalSettings = response.settings;
logConCgp('[floating-panel] Loaded global settings:', response.settings);
}
});
};
/**
* Saves global (non-profile) settings via the service worker.
*/
window.MaxExtensionFloatingPanel.saveGlobalSettings = function () {
chrome.runtime.sendMessage({
type: 'saveGlobalSettings',
settings: window.MaxExtensionGlobalSettings
}, (response) => {
if (chrome.runtime.lastError) {
logConCgp('[floating-panel] Failed to save global settings:', chrome.runtime.lastError.message);
} else if (response && response.success) {
logConCgp('[floating-panel] Global settings saved successfully.');
}
});
};
/**
* Saves the current global config to storage for the active profile.
*/
window.MaxExtensionFloatingPanel.saveCurrentProfileConfig = function () {
if (!this.currentProfileName || !window.globalMaxExtensionConfig) {
logConCgp('[floating-panel] Cannot save profile: profile name or config not available.');
return;
}
chrome.runtime.sendMessage({
type: 'saveConfig',
profileName: this.currentProfileName,
config: window.globalMaxExtensionConfig
}, (response) => {
if (chrome.runtime.lastError) {
logConCgp('[floating-panel] Failed to save current profile config:', chrome.runtime.lastError.message);
} else if (response && response.success) {
logConCgp('[floating-panel] Current profile config saved successfully.');
} else {
logConCgp('[floating-panel] Failed to save current profile config. Response:', response);
}
});
};
/**
* Loads available profiles from the service worker.
*/
window.MaxExtensionFloatingPanel.loadAvailableProfiles = function () {
chrome.runtime.sendMessage(
{ type: 'listProfiles' },
(response) => {
if (response && response.profiles && Array.isArray(response.profiles)) {
this.availableProfiles = response.profiles;
logConCgp('[floating-panel] Available profiles loaded:', this.availableProfiles);
// After loading profiles, get the current profile.
this.getCurrentProfile();
}
}
);
};
/**
* Gets the current active profile from the service worker.
*/
window.MaxExtensionFloatingPanel.getCurrentProfile = function () {
chrome.runtime.sendMessage(
{ type: 'getConfig' },
(response) => {
if (response && response.config) {
// Retrieve current profile name from storage.
chrome.storage.local.get(['currentProfile'], (result) => {
if (result.currentProfile) {
this.currentProfileName = result.currentProfile;
logConCgp('[floating-panel] Current profile:', this.currentProfileName);
// Update the profile switcher UI.
this.createProfileSwitcher();
}
});
}
}
);
};
/**
* Handles switching to a different profile. Unlike standard buttons, Panel is capable of immediately changing buttons on profile change.
*/
window.MaxExtensionFloatingPanel.switchToProfile = function (profileName) {
// Prevent switching to the same profile.
if (profileName === this.currentProfileName) return;
chrome.runtime.sendMessage(
// Pass origin so receivers (including our own content script)
// can limit refresh scope to the floating panel only.
{ type: 'switchProfile', profileName: profileName, origin: 'panel' },
(response) => {
if (response.error) {
logConCgp(`[floating-panel] Error switching to profile ${profileName}: ${response.error}`);
return;
}
if (response.config) {
// The service worker broadcasts the change to other tabs. For this tab,
// we update the UI directly for immediate and reliable feedback.
this.currentProfileName = profileName; // Update internal state
window.globalMaxExtensionConfig = response.config; // Update global config
// Prefer partial refresh to preserve panel state
if (typeof window.__OCP_partialRefreshUI === 'function') {
window.__OCP_partialRefreshUI(response.config);
} else if (typeof window.__OCP_nukeAndRefresh === 'function') {
window.__OCP_nukeAndRefresh(response.config);
} else {
// Fallback: update only the floating panel, never inline buttons
window.MaxExtensionButtonsInit.updateButtonsForProfileChange('panel');
}
logConCgp(`[floating-panel] Successfully switched to profile: ${profileName}`);
}
}
);
};
/**
* Initializes the floating panel functionality.
* It now uses .then() to handle the asynchronous creation of the panel from the HTML template.
*/
window.MaxExtensionFloatingPanel.initialize = function () {
this.currentPanelSettings = { ...this.defaultPanelSettings };
this.loadGlobalSettings(); // Load global settings like TOS acceptance
// If panel was already created by the director (init.js), this will do nothing.
// Otherwise, this will create the panel if the user toggles it on later.
this.createFloatingPanel().then(() => {
if (this.panelElement) {
// Load saved settings (which will apply them).
this.loadPanelSettings();
// Load available profiles (which will populate the switcher).
this.loadAvailableProfiles();
}
});
logConCgp('[floating-panel] Floating panel initialization process started.');
};