forked from thewca/worldcubeassociation.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.js
401 lines (361 loc) · 13.9 KB
/
application.js
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require bootstrap-hover-dropdown
//= require jquery.are-you-sure
//= require locationpicker.jquery
//= require selectize
//= require selectize.do_not_clear_on_blur
//= require selectize.tags_options
//= require jquery.jcrop
//= require lodash
//= require jquery.wca-autocomplete
//= require jquery.floatThead.js
//= require cocoon
//= require moment
//= require moment/cs.js
//= require moment/da.js
//= require moment/de.js
//= require moment/es.js
//= require moment/fi.js
//= require moment/fr.js
//= require moment/hr.js
//= require moment/hu.js
//= require moment/id.js
//= require moment/it.js
//= require moment/ja.js
//= require moment/ko.js
//= require moment/nl.js
//= require moment/pl.js
//= require moment/pt-br.js
//= require moment/pt.js
//= require moment/ro.js
//= require moment/ru.js
//= require moment/sk.js
//= require moment/sl.js
//= require moment/vi.js
//= require moment/zh-cn.js
//= require moment/zh-tw.js
//= require bootstrap-datetimepicker
//= require bootstrap-table
//= require bootstrap-table-locale-all
//= require extensions/bootstrap-table-mobile
//= require autosize
//= require jquery_plugins
//= require jquery.slick
//= require_self
//= require_tree .
// Global variables
var TEXT_INPUT_DEBOUNCE_MS = 250;
// Dumping ground for... stuff
window.wca = window.wca || {};
wca._pendingAjaxById = {};
wca.cancelPendingAjaxAndAjax = function(id, options) {
if(wca._pendingAjaxById[id]) {
wca._pendingAjaxById[id].abort();
}
wca._pendingAjaxById[id] = $.ajax(options).always(function() {
delete wca._pendingAjaxById[id];
});
return wca._pendingAjaxById[id];
};
wca._googleMapsLoaded = false;
wca._onGoogleMapsLoaded = function() {
wca._googleMapsLoaded = true;
wca._googleMapsLoadedListeners.forEach(function(listener) {
listener();
});
wca._googleMapsLoadedListeners = null;
};
wca._googleMapsLoadedListeners = [];
wca.addGoogleMapsLoadedListener = function(listener) {
if(wca._googleMapsLoaded) {
listener();
} else {
wca._googleMapsLoadedListeners.push(listener);
}
};
wca.addCompetitionsToMap = function(map, competitions) {
competitions.forEach(function(c) {
if (c.is_probably_over) {
iconImage = 'https://maps.google.com/mapfiles/ms/icons/blue.png';
} else {
iconImage = 'https://maps.google.com/mapfiles/ms/icons/red.png';
}
c.marker = new google.maps.Marker({
map: map,
position: {
lat: c.latitude_degrees,
lng: c.longitude_degrees,
},
title: c.name,
icon: iconImage
});
c.marker.desc = "<a href=" + c.url + ">" + c.name + "</a><br />" + c.marker_date + " - " + c.cityName;
map.overlappingMarkerSpiderfier.addMarker(c.marker);
});
};
wca.createCompetitionsMap = function(element) {
var map = new google.maps.Map(element, {
zoom: 2,
center: { lat: 0, lng: 0 },
});
map.overlappingMarkerSpiderfier = new OverlappingMarkerSpiderfier(map);
var infowindow = new google.maps.InfoWindow();
map.overlappingMarkerSpiderfier.addListener('click', function(marker) {
infowindow.setContent(marker.desc);
infowindow.open(map, marker);
});
return map;
};
wca.removeMarkers = function(map) {
map.overlappingMarkerSpiderfier.getMarkers().forEach(function(marker) {
marker.setMap(null);
});
map.overlappingMarkerSpiderfier.clearMarkers();
};
wca.renderMarkdownRequest = function(markdownContent) {
return wca.cancelPendingAjaxAndAjax('render_markdown', {
url: '/render_markdown',
method: 'POST',
data: {
'markdown_content': markdownContent,
},
});
};
wca.stripHtmlTags = function(text) {
return $("<div/>").html(text).text();
};
wca.datetimepicker = function(){
// Copied (and modified by jfly) from
// https://github.com/zpaulovics/datetimepicker-rails
// We're using keepOpen: true here to allow the user to
// "change his mind" and select a different date without
// having to click outside and clicking on the input again.
$datetimepicker = $('.date_picker.form-control, .datetime_picker.form-control');
$datetimepicker.each(function() {
var $this = $(this);
var datetimepickerOptions = {
useStrict: true,
keepInvalid: true,
useCurrent: false,
keepOpen: true,
sideBySide: true,
};
if($this.attr("name") === "user[dob]") {
// Don't allow people to choose a birthdate in the future.
datetimepickerOptions.maxDate = new Date();
} else {
// Only show the today button if we're not using dealing with a birthdate,
// where the today button can't possibly work because today is after the maxDate
// for the datetimepicker.
datetimepickerOptions.showTodayButton = true;
}
$this.datetimepicker(datetimepickerOptions);
});
// Using 'blur' here, because 'change' or 'dp.change' is not fired every time
// (see https://github.com/thewca/worldcubeassociation.org/issues/376#issuecomment-180547289).
// Also, 'input' gets too annoying, because it flashes at every stroke until you have
// a valid date typed.
$datetimepicker.off('blur.wcaDateValidation').on('blur.wcaDateValidation', function() {
var $this = $(this);
var datetimepicker = $this.data("DateTimePicker");
var val = $this.val();
var valid = val === "" || moment(val, datetimepicker.format(), true).isValid();
if(valid) {
$this.parent().siblings('p').removeClass('alert alert-danger');
$this.removeClass('alert-danger');
} else {
$this.parent().siblings('p').addClass('alert alert-danger');
$this.parent().siblings('p').fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200);
$this.addClass('alert-danger');
}
});
};
$(function() {
$('.dropdown-toggle').dropdownHover();
$('form.are-you-sure').areYouSure();
wca.datetimepicker();
$('.datetimerange').each(function() {
var $inputGroups = $(this).find('.date_picker.form-control');
var $range1 = $inputGroups.eq(0);
var $range2 = $inputGroups.eq(1);
$range1.on("dp.change", function(e) {
var startDate = $range1.data("DateTimePicker").date() || false;
var endDate = $range2.data("DateTimePicker").date();
$range2.data("DateTimePicker").minDate(startDate);
if (startDate && (!endDate || endDate < startDate)) {
$range2.data("DateTimePicker").date(startDate);
}
}).trigger("dp.change");
});
$('[data-toggle="tooltip"]').tooltip();
$('[data-toggle="popover"]').popover();
$('input.wca-autocomplete').wcaAutocomplete();
var $tablesToFloatHeaders = $('table.floatThead');
$tablesToFloatHeaders.floatThead({
zIndex: 999, // Allow bootstrap popups (z-index 1000) to show up on top.
responsiveContainer: function($table) {
return $table.closest(".table-responsive");
},
});
// After a popup actually occurs, there may be some images that need to load.
// Here we add load listeners for those images and resize the popup once they
// have loaded. We have to be careful not to end up in an infinite loop
// (hence the ignoreInsert variable).
var ignoreInsert = false;
$('[data-toggle="popover"]').on('inserted.bs.popover', function(e) {
var $popoverTrigger = $(e.currentTarget);
if($popoverTrigger.data('ignoreInsert')) {
$popoverTrigger.data('ignoreInsert', false);
return;
}
$('.popover img').on('load.resizePopover', function() {
// While waiting for the image inside the popover to load,
// the popover may have been hidden. Only show (resize) it if
// it's currently visible.
// Trick to detect if popover is currently visible from:
// http://stackoverflow.com/a/29923760
var popoverVisible = !!$popoverTrigger.attr('aria-describedby');
if(!popoverVisible) {
return;
}
$popoverTrigger.data('ignoreInsert', true);
$popoverTrigger.popover('show');
});
});
$("form").bind("keypress", function(e) {
// ctrl+enter should always submit a form.
if((e.which === 13 || e.which === 10) && e.ctrlKey) {
// Find the submit button for this form and click it.
// Note that we don't submit the form because that would bypass
// any click listeners on the submit button.
$(this).find('[type=submit]')[0].click();
}
});
$("form.no-submit-on-enter").bind("keypress", function(e) {
// We allow pressing enter inside textareas, because that only inserts
// a newline, it doesn't submit the form.
// Note that we let the keypress occur if ctrl is being held down, as
// we still want ctrl+enter to submit the form.
if(e.which === 13 && !e.ctrlKey && e.target.tagName !== "TEXTAREA") {
e.preventDefault();
}
});
});
// Polyfill for Math.trunc from
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
Math.trunc = Math.trunc || function(x) {
return x < 0 ? Math.ceil(x) : Math.floor(x);
};
// Bootstrap-table default options
$.extend($.fn.bootstrapTable.defaults, {
searchTimeOut: TEXT_INPUT_DEBOUNCE_MS,
trimOnSearch: false
});
// Setting up bootstrap-table
$(function() {
$('table[data-toggle="table"]').addClass('bs-table');
// Hide loading box
$('.bs-table').bootstrapTable('hideLoading');
// It's not necessary when bootstrap-table will be distributed with this merged:
// https://github.com/wenzhixin/bootstrap-table/pull/2145
// (and the appropriate gem will be updated)
// -------------------------------------------------------------------
// Triggered when a sort arrow is clicked but before a table is sorted
$('table').on('sort.bs.table', function(e, name, order) {
// The table column that we are sorting by
var field = $(this).floatThead('getRowGroups').eq(0).find('th[data-field="' + name + '"] .sortable');
// If it's not the field we are currently sorting by
if(!field.is('.asc, .desc')) {
// Change the sort order that's set in data-order ('asc' by default)
var options = $(this).bootstrapTable('getOptions');
options.sortOrder = options.columns[0].find(function(option) { return option.field == name; }).order;
// Now the table will be sorted using the order that we set
}
});
// -------------------------------------------------------------------
// It's not necessary when bootstrap-table will be distributed with this issue solved:
// https://github.com/wenzhixin/bootstrap-table/issues/2154
// (and the appropriate gem will be updated)
// -------------------------------------------------------------------
// Prevent bootstrap-table from selecting a row when a link is clicked
$('.bs-table td a').on('click', function(e) {
e.stopPropagation();
});
// -------------------------------------------------------------------
// Set values of checkboxes in a table to corresponding rows ids
var initCheckboxesValues = function($table) {
$table.find('tr td input[type="checkbox"]').each(function(index) {
$(this).val($(this).parents('tr').attr('id'));
});
};
initCheckboxesValues($('.bs-table'));
$('table').on('post-body.bs.table', function() {
initCheckboxesValues($(this));
// Re-apply tooltip on each table body change
$('[data-toggle="tooltip"]').tooltip();
});
});
// Setting up autosize
$(function() {
autosize($('textarea:not(.no-autosize)'));
});
// Helpers
// Executes the given function on the specified page/pages.
// The given string should have a format: '<controller>#<action>'.
// The action name preceded by '#' is optional.
// Could be followed by comma and another pair.
// Example: 'users#show, users#edit, users#update, competitions'.
function onPage(controllersWithActions, fun) {
controllersWithActions = controllersWithActions.replace(/\s/g, '');
controllersWithActions = controllersWithActions.split(',');
controllersWithActions = controllersWithActions.map(function(controllerWithAction) { return controllerWithAction.split('#'); });
$(function() {
if (controllersWithActions.some(function(controllerWithAction) {
return controllerWithAction[0] === document.body.dataset.railsControllerName &&
(controllerWithAction[1] ? document.body.dataset.railsControllerActionName === controllerWithAction[1] : true);
})) {
fun();
}
});
}
$(function() {
$('.wca-local-time').each(function() {
var data = $(this).data();
var date = new Date(data.utcTime);
var formatted = new Intl.DateTimeFormat(data.locale, {
weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: 'numeric', minute: 'numeric', timeZoneName: 'short'
}).format(date);
$(this).text(formatted);
});
});
// Handler for locale changes.
$(function() {
$('#locale-selector').on('click', 'a', function(e) {
e.preventDefault();
e.stopPropagation();
// More or less copied from
// https://github.com/rails/jquery-ujs/blob/9e805c90c8cfc57b39967052e1e9013ccb318cf8/src/rails.js#L215.
var csrfToken = $('meta[name=csrf-token]').attr('content');
var csrfParam = $('meta[name=csrf-param]').attr('content');
var form = $('<form method="post" action="' + this.href + '"></form>');
var metadataInput = '<input name="_method" value="patch" type="hidden" />';
metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />';
metadataInput += '<input name="current_url" value="' + window.location.toString() + '" type="hidden" />';
form.hide().append(metadataInput).appendTo('body');
form.submit();
});
});