-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
293 lines (260 loc) · 10.5 KB
/
popup.js
File metadata and controls
293 lines (260 loc) · 10.5 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
288
289
290
291
292
293
// popup.js
class TimeManagerPopup {
constructor() {
this.defaultConfig = {
// Nouveau modèle
WEEKLY_BASE_HOURS: 42,
WORKLOAD_PERCENT: 100,
DAILY_WORK_HOURS: 8.4, // gardé pour compat/content.js
WORKING_DAYS_PER_WEEK: 5,
LANGUAGE: 'fr',
ROWS_TO_CONVERT_TO_DAYS: [],
ROWS_TO_REMOVE: [],
LUNCH_BREAK: {
START_HOUR: 11,
END_HOUR: 14,
MINIMUM_DURATION_MINUTES: 30
}
};
this.rowNames = [];
this.init();
}
init() {
this.bindEvents();
this.loadConfiguration();
}
bindEvents() {
document.getElementById('saveBtn')
.addEventListener('click', () => this.saveConfiguration());
document.getElementById('resetBtn')
.addEventListener('click', () => this.resetConfiguration());
document.getElementById('refreshRows')
.addEventListener('click', () => this.refreshRowNames());
const percentNum = document.getElementById('workloadPercentNumber');
const workingDays = document.getElementById('workingDays');
if (percentNum) percentNum.addEventListener('input', () => this.updateCalculatedDailyPreview());
if (workingDays) workingDays.addEventListener('change', () => this.updateCalculatedDailyPreview());
this.setupAutoSave();
}
setupAutoSave() {
let autoSaveTimeout;
document.addEventListener('input', (e) => {
if (!e.target.matches('input, select, textarea')) return;
clearTimeout(autoSaveTimeout);
autoSaveTimeout = setTimeout(() => {
this.updateCalculatedDailyPreview();
this.saveConfiguration();
}, 1000);
});
}
async refreshRowNames() {
this.rowNames = await this.fetchRowNames();
const cfg = this.getFormData(false);
this.renderRowChecklist(cfg);
this.renderConvertChecklist(cfg);
}
fetchRowNames() {
return new Promise((resolve) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tab = tabs[0];
if (!tab) return resolve([]);
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
func: () => {
const cells = Array.from(document.querySelectorAll('tr[data-uid] td[role="gridcell"]'));
const names = cells.map(td => (td.textContent || '').trim()).filter(Boolean);
return Array.from(new Set(names));
}
},
(results) => {
if (chrome.runtime.lastError || !results || !results[0]) {
resolve([]);
} else {
resolve(results[0].result || []);
}
}
);
});
});
}
renderRowChecklist(config) {
const container = document.getElementById('rowsChecklist');
if (!container) return;
container.innerHTML = '';
const names = Array.from(new Set([...(this.rowNames || []), ...(config.ROWS_TO_REMOVE || [])]));
names.forEach(name => {
const label = document.createElement('label');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.value = name;
checkbox.checked = !config.ROWS_TO_REMOVE.includes(name);
label.appendChild(checkbox);
label.appendChild(document.createTextNode(' ' + name));
container.appendChild(label);
});
}
renderConvertChecklist(config) {
const container = document.getElementById('convertRowsChecklist');
if (!container) return;
container.innerHTML = '';
const names = Array.from(new Set([...(this.rowNames || []), ...(config.ROWS_TO_CONVERT_TO_DAYS || [])]));
names.forEach(name => {
const label = document.createElement('label');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.value = name;
checkbox.checked = config.ROWS_TO_CONVERT_TO_DAYS.includes(name);
label.appendChild(checkbox);
label.appendChild(document.createTextNode(' ' + name));
container.appendChild(label);
});
}
loadConfiguration() {
chrome.storage.sync.get(['timeManagerConfig'], async (result) => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
this.rowNames = await this.fetchRowNames();
this.populateForm(this.defaultConfig);
this.showStatus('❌ Erreur de chargement', 'error');
return;
}
const cfg = result.timeManagerConfig || { ...this.defaultConfig };
// compat clés
if (cfg.WEEKLY_BASE_HOURS == null) cfg.WEEKLY_BASE_HOURS = 42;
if (cfg.WORKLOAD_PERCENT == null) cfg.WORKLOAD_PERCENT = 100;
this.rowNames = await this.fetchRowNames();
this.populateForm(cfg);
this.showStatus('⚙️ Configuration chargée', 'info');
});
}
populateForm(config) {
const weeklyBase = document.getElementById('weeklyBaseHours');
if (weeklyBase) weeklyBase.value = config.WEEKLY_BASE_HOURS ?? 42;
const percentNum = document.getElementById('workloadPercentNumber');
if (percentNum) percentNum.value = config.WORKLOAD_PERCENT ?? 100;
document.getElementById('workingDays').value = config.WORKING_DAYS_PER_WEEK;
document.getElementById('language').value = config.LANGUAGE;
document.getElementById('lunchStart').value = config.LUNCH_BREAK.START_HOUR;
document.getElementById('lunchEnd').value = config.LUNCH_BREAK.END_HOUR;
document.getElementById('minPause').value = config.LUNCH_BREAK.MINIMUM_DURATION_MINUTES;
this.renderRowChecklist(config);
this.renderConvertChecklist(config);
this.updateCalculatedDailyPreview(config);
}
saveConfiguration() {
const config = this.getFormData();
const validation = this.validateConfiguration(config);
if (!validation.isValid) {
this.showStatus(validation.error, 'error');
return;
}
chrome.storage.sync.set({ timeManagerConfig: config }, () => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
this.showStatus('❌ Erreur de sauvegarde', 'error');
} else {
this.showStatus('✅ Configuration sauvegardée !', 'success');
this.reloadActiveTab();
}
});
}
// === Calcul heures/jour à partir de 42h @ 100% et du pourcentage ===
computeDailyFromPercent(cfg) {
const weekly = (cfg.WEEKLY_BASE_HOURS ?? 42);
const pct = Math.max(0, Math.min(100, (cfg.WORKLOAD_PERCENT ?? 100)));
const days = Math.max(1, Math.min(7, parseInt(cfg.WORKING_DAYS_PER_WEEK ?? 5)));
const daily = (weekly * (pct / 100)) / days;
return Number.isFinite(daily) ? daily : 8.4;
}
updateCalculatedDailyPreview(cfg = null) {
const data = cfg || this.getFormData(false);
const daily = this.computeDailyFromPercent({
WEEKLY_BASE_HOURS: data.WEEKLY_BASE_HOURS,
WORKLOAD_PERCENT: data.WORKLOAD_PERCENT,
WORKING_DAYS_PER_WEEK: data.WORKING_DAYS_PER_WEEK
});
const el = document.getElementById('calculatedDailyHours');
if (el) el.value = daily.toFixed(2);
}
getFormData(useValidation = true) {
const convertChecklist = document.querySelectorAll('#convertRowsChecklist input[type="checkbox"]');
const rowsToConvert = Array.from(convertChecklist)
.filter(cb => cb.checked)
.map(cb => cb.value);
const checklist = document.querySelectorAll('#rowsChecklist input[type="checkbox"]');
const rowsToRemove = Array.from(checklist)
.filter(cb => !cb.checked)
.map(cb => cb.value);
const weekly = parseFloat(document.getElementById('weeklyBaseHours')?.value) || 42;
const percent = Math.max(0, Math.min(100, parseInt(document.getElementById('workloadPercentNumber')?.value) || 100));
const workingDays = parseInt(document.getElementById('workingDays')?.value) || 5;
const computedDaily = (weekly * (percent / 100)) / workingDays;
const config = {
WEEKLY_BASE_HOURS: weekly,
WORKLOAD_PERCENT: percent,
DAILY_WORK_HOURS: computedDaily,
WORKING_DAYS_PER_WEEK: workingDays,
LANGUAGE: document.getElementById('language')?.value || this.defaultConfig.LANGUAGE,
LUNCH_BREAK: {
START_HOUR: parseInt(document.getElementById('lunchStart')?.value) || this.defaultConfig.LUNCH_BREAK.START_HOUR,
END_HOUR: parseInt(document.getElementById('lunchEnd')?.value) || this.defaultConfig.LUNCH_BREAK.END_HOUR,
MINIMUM_DURATION_MINUTES: parseInt(document.getElementById('minPause')?.value) || this.defaultConfig.LUNCH_BREAK.MINIMUM_DURATION_MINUTES
},
ROWS_TO_CONVERT_TO_DAYS: rowsToConvert,
ROWS_TO_REMOVE: rowsToRemove
};
if (!useValidation){return config} ;
return config;
}
validateConfiguration(config) {
if (config.DAILY_WORK_HOURS < 0 || config.DAILY_WORK_HOURS > 12) {
return { isValid: false, error: 'Les heures par jour doivent être entre 0 et 12' };
}
if (config.WORKING_DAYS_PER_WEEK < 1 || config.WORKING_DAYS_PER_WEEK > 7) {
return { isValid: false, error: 'Les jours par semaine doivent être entre 1 et 7' };
}
if (config.WORKLOAD_PERCENT < 0 || config.WORKLOAD_PERCENT > 100) {
return { isValid: false, error: 'Le pourcentage doit être entre 0 et 100' };
}
if (config.LUNCH_BREAK.START_HOUR >= config.LUNCH_BREAK.END_HOUR) {
return { isValid: false, error: 'L\'heure de début de pause doit être avant l\'heure de fin' };
}
if (config.LUNCH_BREAK.MINIMUM_DURATION_MINUTES < 0 || config.LUNCH_BREAK.MINIMUM_DURATION_MINUTES > 240) {
return { isValid: false, error: 'La durée minimum de pause doit être entre 0 et 240 minutes' };
}
return { isValid: true };
}
resetConfiguration() {
if (!confirm('Êtes-vous sûr de vouloir réinitialiser la configuration ?')) return;
chrome.storage.sync.remove('timeManagerConfig', () => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
this.showStatus('❌ Erreur de réinitialisation', 'error');
} else {
this.populateForm(this.defaultConfig);
this.showStatus('🔄 Configuration réinitialisée', 'info');
}
});
}
reloadActiveTab() {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tab = tabs[0];
if (tab && tab.url && tab.url.includes('launchpad.wd.pnet.ch')) {
chrome.tabs.reload(tab.id);
}
});
}
showStatus(message, type = 'info') {
const statusEl = document.getElementById('status');
statusEl.textContent = message;
statusEl.className = `status ${type} status-fade-in`;
setTimeout(() => {
statusEl.textContent = '';
statusEl.className = 'status';
}, 3000);
}
}
document.addEventListener('DOMContentLoaded', () => {
new TimeManagerPopup();
});