-
-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathproblemsetlist.js
More file actions
349 lines (325 loc) · 12.8 KB
/
problemsetlist.js
File metadata and controls
349 lines (325 loc) · 12.8 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
(() => {
// Action form validation.
// Store event listeners so they can be removed.
const event_listeners = {};
const show_errors = (ids, elements) => {
for (const id of ids) elements.push(document.getElementById(id));
for (const element of elements) {
if (element?.id.endsWith('_err_msg')) {
element.classList.remove('d-none');
} else if (element) {
element.classList.add('is-invalid');
if (!(element.id in event_listeners)) {
event_listeners[element.id] = hide_errors([], elements);
element.addEventListener('change', event_listeners[element.id]);
}
}
}
};
const hide_errors = (ids, elements) => {
return () => {
for (const id of ids) elements.push(document.getElementById(id));
for (const element of elements) {
if (element?.id.endsWith('_err_msg')) {
element.classList.add('d-none');
if (element.id === 'select_set_err_msg' && 'set_table_id' in event_listeners) {
document
.getElementById('set_table_id')
?.removeEventListener('change', event_listeners.set_table_id);
delete event_listeners.set_table_id;
}
} else if (element) {
element.classList.remove('is-invalid');
if (element.id in event_listeners) {
element.removeEventListener('change', event_listeners[element.id]);
delete event_listeners[element.id];
}
}
}
};
};
const is_set_selected = () => {
for (const set of document.getElementsByName('selected_sets')) {
if (set.checked) return true;
}
const err_msg = document.getElementById('select_set_err_msg');
err_msg?.classList.remove('d-none');
if (!('set_table_id' in event_listeners)) {
event_listeners.set_table_id = hide_errors(
['filter_select', 'edit_select', 'publish_filter_select', 'export_select', 'score_select'],
[err_msg]
);
document.getElementById('set_table_id')?.addEventListener('change', event_listeners.set_table_id);
}
return false;
};
document.getElementById('problemsetlist')?.addEventListener('submit', (e) => {
const action = document.getElementById('current_action')?.value || '';
if (action === 'filter') {
const filter_select = document.getElementById('filter_select');
const filter = filter_select?.value || '';
const filter_text = document.getElementById('filter_text');
if (filter === 'selected' && !is_set_selected()) {
e.preventDefault();
e.stopPropagation();
show_errors(['select_set_err_msg'], [filter_select]);
} else if (filter === 'match_ids' && filter_text.value === '') {
e.preventDefault();
e.stopPropagation();
show_errors(['filter_err_msg'], [filter_select, filter_text]);
}
} else if (['edit', 'publish', 'export', 'score'].includes(action)) {
const action_select = document.getElementById(`${action}_select`);
if (action_select.value === 'selected' && !is_set_selected()) {
e.preventDefault();
e.stopPropagation();
show_errors(['select_set_err_msg'], [action_select]);
}
} else if (action === 'save_export') {
if (!is_set_selected()) {
e.preventDefault();
e.stopPropagation();
}
} else if (action === 'import') {
const import_select = document.getElementById('import_source_select');
if (!import_select.value.endsWith('.def')) {
e.preventDefault();
e.stopPropagation();
show_errors(['import_file_err_msg'], [import_select]);
}
} else if (action === 'create') {
const create_text = document.getElementById('create_text');
const create_select = document.getElementById('create_select');
if (create_text.value === '') {
e.preventDefault();
e.stopPropagation();
show_errors(['create_file_err_msg'], [create_text]);
} else if (create_select?.value == 'copy' && !is_set_selected()) {
e.preventDefault();
e.stopPropagation();
show_errors(['select_set_err_msg'], [create_select]);
}
} else if (action === 'delete') {
const delete_confirm = document.getElementById('delete_select');
if (!is_set_selected()) {
e.preventDefault();
e.stopPropagation();
} else if (delete_confirm.value != 'yes') {
e.preventDefault();
e.stopPropagation();
show_errors(['delete_confirm_err_msg'], [delete_confirm]);
}
}
});
// Remove all error messages when changing tabs.
for (const tab of document.querySelectorAll('a[data-bs-toggle="tab"]')) {
tab.addEventListener('shown.bs.tab', () => {
if (Object.keys(event_listeners) != 0)
hide_errors(
[],
document.getElementById('problemsetlist')?.querySelectorAll('div[id$=_err_msg], .is-invalid')
)();
});
}
// Toggle the display of the filter elements as the filter select changes.
const filter_select = document.getElementById('filter_select');
const filter_elements = document.getElementById('filter_elements');
const filterElementToggle = () => {
if (filter_select?.value == 'match_ids') filter_elements.style.display = 'flex';
else filter_elements.style.display = 'none';
};
if (filter_select) filterElementToggle();
filter_select?.addEventListener('change', filterElementToggle);
// This will make the popup menu alternate between a single selection and a multiple selection menu.
const numSelect = document.problemsetlist['action.import.number'];
if (numSelect) {
numSelect.addEventListener('change', () => {
const number = parseInt(numSelect.options[numSelect.selectedIndex]?.value ?? '1');
const importSourceSelect = document.problemsetlist['action.import.source'];
if (importSourceSelect) {
importSourceSelect.size = number;
if (number === 1) {
if (!importSourceSelect.value) importSourceSelect.options[0].selected = true;
importSourceSelect.options[0].textContent =
importSourceSelect.dataset.selectSingleText ?? 'Select filename below';
importSourceSelect.multiple = false;
} else {
importSourceSelect.options[0].textContent =
importSourceSelect.dataset.selectMultipleText ?? 'Select filename below';
importSourceSelect.multiple = true;
importSourceSelect.options[0].selected = false;
}
}
const importNameInput = document.problemsetlist['action.import.name'];
if (importNameInput) {
importNameInput.value =
number > 1 ? (importNameInput.dataset.multipleFilesText ?? '(taken from filenames)') : '';
importNameInput.readOnly = number > 1 ? true : false;
importNameInput.disabled = number > 1 ? true : false;
}
});
}
// Date/time formats for the languages supported by webwork.
// Note that these formats are chosen to match the perl DateTime::Locale formats.
// Make sure that anytime a new language is added, its format is added here.
const datetimeFormats = {
en: 'L/d/yy, h:mm a',
'en-US': 'L/d/yy, h:mm a',
'en-GB': 'dd/LL/yyyy, HH:mm',
'cs-CZ': 'dd.LL.yy H:mm',
de: 'dd.LL.yy, HH:mm',
el: 'd/L/yy, h:mm a',
es: 'd/L/yy, H:mm',
'fr-CA': "yyyy-LL-dd HH 'h' mm",
fr: 'dd/LL/yyyy HH:mm',
'he-IL': 'd.L.yyyy, H:mm',
hu: 'yyyy. LL. dd. H:mm',
ko: 'yy. L. d. a h:mm',
'ru-RU': 'dd.LL.yyyy, HH:mm',
tr: 'd.LL.yyyy HH:mm',
'zh-CN': 'yyyy/L/d ah:mm',
'zh-HK': 'yyyy/L/d ah:mm'
};
// Initialize the date/time picker for the import form and common date editor.
const dateInputs = [];
const importDateShift = document.getElementById('import_date_shift');
if (importDateShift) dateInputs.push(importDateShift);
const commonDateInput = document.getElementById('common-date');
if (commonDateInput) dateInputs.push(commonDateInput);
for (const dateInput of dateInputs) {
luxon.Settings.defaultLocale = dateInput.dataset.locale ?? 'en';
// Compute the time difference between a time in the browser timezone and the same time in the course timezone.
// flatpickr gives the time in the browser's timezone, and this is used to adjust to the course timezone.
// Note that the input time is in seconds and output times is in milliseconds.
const timezoneAdjustment = (time) => {
const dateTime = new Date(0);
dateTime.setUTCSeconds(time);
return (
new Date(dateTime.toLocaleString('en-US')).getTime() -
new Date(
dateTime.toLocaleString('en-US', {
timeZone: dateInput.dataset.timezone ?? 'America/New_York'
})
).getTime()
);
};
let fallbackDate = dateInput.value
? new Date(parseInt(dateInput.value) * 1000 - timezoneAdjustment(parseInt(dateInput.value)))
: new Date();
const fp = flatpickr(dateInput.parentNode, {
allowInput: true,
enableTime: true,
minuteIncrement: 1,
altInput: true,
dateFormat: 'U',
altFormat: datetimeFormats[luxon.Settings.defaultLocale],
ariaDateFormat: datetimeFormats[luxon.Settings.defaultLocale],
defaultHour: 0,
locale:
luxon.Settings.defaultLocale.substring(0, 2) === 'el'
? 'gr'
: luxon.Settings.defaultLocale.substring(0, 2),
clickOpens: false,
disableMobile: true,
wrap: true,
plugins: [
new confirmDatePlugin({ confirmText: dateInput.dataset.doneText, showAlways: true }),
new ShortcutButtonsPlugin({
button: [
{
label: dateInput.dataset.todayText ?? 'Today',
attributes: { class: 'btn btn-sm btn-secondary ms-auto me-1 mb-1' }
},
{
label: dateInput.dataset.nowText ?? 'Now',
attributes: { class: 'btn btn-sm btn-secondary mx-auto mb-1' }
}
],
onClick: (index, fp) => {
if (index === 0) {
// The initial date represents 12:00 am on the current date.
const today = new Date(new Date().toDateString());
if (fp.selectedDates[0]) {
today.setHours(fp.selectedDates[0].getHours());
today.setMinutes(fp.selectedDates[0].getMinutes());
today.setSeconds(fp.selectedDates[0].getSeconds());
}
fp.setDate(today, true);
} else if (index === 1) {
fp.setDate(new Date());
}
}
})
],
onReady() {
// Flatpickr hides the original input and adds the alternate input after it. That messes up the
// bootstrap input group styling. So move the now hidden original input after the created alternate
// input to fix that.
this.altInput.after(this.input);
// Make the alternate input left-to-right even for right-to-left languages.
this.altInput.dir = 'ltr';
// Move the id of the now hidden input onto the added input so the labels still work.
this.altInput.id = this.input.id;
this.input.removeAttribute('id');
},
parseDate(datestr, format) {
// Deal with the case of a unix timestamp. The timezone needs to be adjusted back as this is for
// the unix timestamp stored in the hidden input whose value will be sent to the server.
if (format === 'U') return new Date(parseInt(datestr) * 1000 - timezoneAdjustment(parseInt(datestr)));
// Next attempt to parse the datestr with the current format. This should not be adjusted. It is
// for display only.
const date = luxon.DateTime.fromFormat(datestr.replaceAll(/\u202F/g, ' ').trim(), format);
if (date.isValid) fallbackDate = date.toJSDate();
// Finally, fall back to the previous value in the original input if that failed. This is the case
// that the user typed a time that isn't in the valid format. So fallback to the last valid time
// that was displayed. This also should not be adjusted.
return fallbackDate;
},
formatDate(date, format) {
// In this case the date provided is in the browser's time zone. So it needs to be adjusted to the
// timezone of the course.
if (format === 'U') return (date.getTime() + timezoneAdjustment(date.getTime() / 1000)) / 1000;
return luxon.DateTime.fromMillis(date.getTime()).toFormat(
datetimeFormats[luxon.Settings.defaultLocale]
);
}
});
dateInput.nextElementSibling.addEventListener('keydown', (e) => {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
fp.open();
}
});
}
if (commonDateInput) {
document.getElementById('apply-common-date')?.addEventListener('click', () => {
const dateTypeInput = document.getElementById('set-date-choice');
if (!dateTypeInput?.value) {
show_errors(['choose_date_type_err_msg'], [dateTypeInput]);
return;
}
if (!commonDateInput.value) {
show_errors(
['choose_common_date_err_msg'],
[commonDateInput.parentNode?._flatpickr?.input, commonDateInput.parentNode?._flatpickr?.altInput]
);
return;
}
const selectedSets = Array.from(document.getElementsByName('apply_date_sets')).filter((c) => c.checked);
if (!selectedSets.length) {
show_errors(['select_set_err_msg'], []);
event_listeners.set_table_id = hide_errors(
['set_table_id'],
[document.getElementById('select_set_err_msg')]
);
document.getElementById('set_table_id')?.addEventListener('change', event_listeners.set_table_id);
}
for (const set of selectedSets) {
const inputPicker = document.getElementsByName(`set.${set.value}.${dateTypeInput.value}`)[0]?.parentNode
?._flatpickr;
inputPicker?.setDate(commonDateInput.value, true);
inputPicker?.close(); // The picker isn't actually open, but this triggers the onClose handler.
}
});
}
})();