wcs/wcs/qommon/static/js/qommon.admin.js

346 lines
12 KiB
JavaScript

$(function() {
$('.section.foldable > h2').click(function() {
$(this).parent().find('.qommon-map').trigger('qommon:invalidate');
});
$('h4.foldable').click(function() {
$(this).toggleClass('folded').next().toggle();
});
$('h4.foldable.folded').next().hide();
/* insert variable code in textarea when clicking on them */
var latest_textarea = null;
if ($('textarea').length == 1) {
latest_textarea = $('textarea');
}
$('textarea').on('focus', function() { latest_textarea = this; });
$('#substvars td:nth-child(2)').css('cursor', 'pointer').click(function() {
if (latest_textarea === null) return true;
var current_val = $(latest_textarea).val();
position = $(latest_textarea).get(0).selectionStart;
if (position >= 0) {
var code = $(this).text();
var new_val = current_val.substr(0, position) + code + current_val.substr(position);
$(latest_textarea).val(new_val);
}
return true;
});
/* open theme preview in a iframe */
$('a.theme-preview').click(function() {
var html = '<div id="theme-preview"><iframe src="' + $(this).attr('href') + '"></iframe></div>';
var title = $(this).parent().parent().find('label').text()
var dialog = $(html).dialog({
closeText: WCS_I18N.close,
modal: true,
title: title,
width: $(window).width() - 180,
height: $(window).height() - 80
});
return false;
});
/* highlight info text on hover */
$('.action-info-text[data-button-name]').each(function(idx, elem) {
$('[name=' + $(elem).data('button-name') + ']').on('mouseenter', function() {
$(elem).addClass('highlight');
}).on('mouseleave', function() {
$(elem).removeClass('highlight');
});
});
/* close advanced section */
$('fieldset.form-plus').addClass('closed');
/* handle toggling advanced section */
$('fieldset.form-plus legend').on('click', function() {
$(this).parent().toggleClass('closed');
});
/* open advanced section if there's a field with errors */
$('fieldset.form-plus').each(function(idx, elem) {
if ($(elem).find('div.error').length) {
$(elem).removeClass('closed');
}
});
/* hints on the computed expression widget */
var validation_timeout_id = 0;
$('input[data-validation-url]').on('change focus input', function() {
var val = $(this).val();
var $widget = $(this).parents('.ComputedExpressionWidget');
var validation_url = $(this).data('validation-url');
clearTimeout(validation_timeout_id);
validation_timeout_id = setTimeout(function() {
$.ajax({
url: validation_url,
data: {expression: val},
dataType: 'json',
success: function(data) {
$widget.removeClass('hint-warning');
$widget.removeClass('hint-error');
if (data.klass) {
$widget.addClass('hint-' + data.klass);
}
$widget.prop('title', data.msg);
}
})}, 250);
return false;
});
$('div[data-validation-url]').each(function(idx, elem) {
var $widget = $(this);
var widget_name = $widget.find('select').attr('name');
var prefix = widget_name.replace(/\$[a-z]*/, '') + '$';
$(this).find('input, select').on('change focus input', function() {
clearTimeout($widget.validation_timeout_id);
$widget.validation_timeout_id = setTimeout(function() {
var data = Object();
$widget.find('select, input').each(function(idx, elem) {
data[$(elem).attr('name').replace(prefix, '')] = $(elem).val();
});
$.ajax({
url: $widget.data('validation-url'),
data: data,
dataType: 'json',
success: function(data) {
$widget.removeClass('hint-warning');
$widget.removeClass('hint-error');
if (data.klass) {
$widget.addClass('hint-' + data.klass);
}
$widget.prop('title', data.msg);
}
})}, 250);
return false;
});
});
/* keep title/slug in sync */
$('body').delegate('input[data-slug-sync]', 'input change paste',
function() {
var $slug_field = $(this).parents('form').find('[name=' + $(this).data('slug-sync') + ']');
if ($slug_field.prop('readonly')) return;
$slug_field.val($.slugify($(this).val()));
});
/* remove readonly attribute from fields */
$('body').delegate('a.change-nevertheless', 'click', function(e) {
var readonly_fields = $(this).parents('form').find('input[readonly]');
if (readonly_fields.length) {
readonly_fields.prop('readonly', false);
readonly_fields[0].focus();
}
$(this).parent().hide();
return false;
});
/* submission channel */
$('div.submit-channel-selection').show().find('select').on('change', function() {
$('input[type=hidden][name=submission_channel]').val($(this).val());
});
/* user id */
var select2_options = {
language: {
errorLoading: function() { return WCS_I18N.s2_errorloading; },
noResults: function () { return WCS_I18N.s2_nomatches; },
inputTooShort: function (input, min) { return WCS_I18N.s2_tooshort; },
loadingMore: function () { return WCS_I18N.s2_loadmore; },
searching: function () { return WCS_I18N.s2_searching; }
},
ajax: {
delay: 250,
dataType: 'json',
data: function(params) {
return {q: params.term, page_limit: 10};
},
processResults: function (data, params) {
return {results: data.data};
},
url: '/api/users/'
},
placeholder: '-',
templateResult: function (state) {
if (!state.description) {
return state.text;
}
var $template_string = $('<span>');
$template_string.append(
$('<span>', {text: state.text})).append(
$('<br>')).append(
$('<span>' + state.description + '</span>'));
return $template_string;
}
}
if ($('div.submit-user-selection').length) {
$('div.submit-user-selection select').select2(select2_options);
$('div.submit-user-selection').show().find('select').on('change', function() {
$('input[type=hidden][name=user_id]').val($(this).val());
$('form[data-live-url]').trigger(
'wcs:change',
{modified_field: 'user', selected_user_id: $(this).val()}
);
});
}
/* new action form */
$('#new-action-form select').on('change', function() {
if ($(this).val() == '') {
$('#new-action-form select').prop('disabled', null)
} else {
$('#new-action-form select').prop('disabled', 'disabled')
$(this).prop('disabled', null)
}
return false;
});
/* possibility to toggle the sidebar */
if ($('#sidebar').length) {
$('#sidebar-toggle').click(function() {
if ($('#sticky-sidebar').css('display') === 'none') {
$('#sidebar').animate(
{'max-width': '23rem'},
400,
function() {
$('#sticky-sidebar').show()
$(window).trigger('wcs:sidebar-toggled');
}
);
} else {
$('#sticky-sidebar').hide();
$('#sidebar').animate(
{'max-width': '0rem'},
400,
function() {
$(window).trigger('wcs:sidebar-toggled');
}
);
}
});
}
/* load html parts asynchronously */
$('[data-async-url]').each(function(idx, elem) {
$(elem).load($(elem).data('async-url'));
});
/* keep sidebar sticky */
if ($('#sticky-sidebar').length) {
var $window = $(window);
var sidebar_fixed_from = $('#sticky-sidebar').offset().top;
var sidebar_top = $('#sticky-sidebar').position().top;
$window.bind('scroll', function() {
var pos = $window.scrollTop();
var minus = 0;
if (pos >= sidebar_fixed_from) {
$('#sticky-sidebar').css('top', pos - (sidebar_fixed_from - sidebar_top));
} else {
$('#sticky-sidebar').css('top', 'auto');
minus = sidebar_fixed_from - pos;
}
$('#sticky-sidebar').css('height', 'calc(100vh - 5px - ' + minus + 'px)');
});
$window.trigger('scroll');
}
$('#inspect-test-tools form').on('submit', function() {
var data = $(this).serialize();
$.ajax({url: 'inspect-tool',
xhrFields: { withCredentials: true },
data: $(this).serialize(),
method: 'POST',
async: true,
dataType: 'html',
success: function(data) {
$('#test-tool-result').empty().append($(data));
}
});
return false;
});
$('#inspect-test-tools textarea').on('keydown', function(e) {
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
$(this).parents('form').trigger('submit');
return false;
}
return true;
});
if ($('svg').length && typeof(svgPanZoom) === 'function') {
var panned_svg = svgPanZoom('svg', {controlIconsEnabled: true});
$(window).on('resize wcs:sidebar-toggled gadjo:sidepage-toggled', function() {
panned_svg.resize();
});
}
$('[type=radio][name=display_mode]').on('change', function() {
// show everything
$('select[name="data_source$type"] option').show();
$('input[name="data_mode"][value="simple-list"]').prop('disabled', false);
// then restrict
if ($(this).val() == 'map') {
$('input[name="data_mode"][value="simple-list"]').prop('disabled', true);
$('input[name="data_mode"][value="data-source"]').click()
$('select[name="data_source$type"] option:not([data-type="geojson"])').hide();
if ($('select[name="data_source$type"] option:selected:visible').length == 0) {
$('select[name="data_source$type"] option:visible').first().prop('selected', true).trigger('change');
}
}
if ($(this).val() == 'timetable') {
$('input[name="data_mode"][value="simple-list"]').prop('disabled', true);
$('input[name="data_mode"][value="data-source"]').click()
$('select[name="data_source$type"] option:not([data-maybe-datetimes="true"])').hide();
if ($('select[name="data_source$type"] option:selected:visible').length == 0) {
$('select[name="data_source$type"] option:visible').first().prop('selected', true).trigger('change');
}
}
});
$('[type=radio][name=display_mode]:checked').trigger('change');
// IE doesn't accept periods or dashes in the window name, but the element IDs
// we use to generate popup window names may contain them, therefore we map them
// to allowed characters in a reversible way so that we can locate the correct
// element when the popup window is dismissed.
function id_to_windowname(text) {
text = text.replace(/\./g, '__dot__');
text = text.replace(/\-/g, '__dash__');
return text;
}
function windowname_to_id(text) {
text = text.replace(/__dot__/g, '.');
text = text.replace(/__dash__/g, '-');
return text;
}
function showAddRelatedObjectPopup(triggeringLink) {
var name = triggeringLink.id.replace(/^add_/, '');
name = id_to_windowname(name);
console.log(name)
var href = triggeringLink.href;
console.log(href)
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
function dismissAddRelatedObjectPopup(win, newId, newRepr) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
var elemName = elem.nodeName.toUpperCase();
if (elemName === 'SELECT') {
elem.options[elem.options.length] = new Option(newRepr, newId, true, true);
}
// Trigger a change event to update related links if required.
$(elem).trigger('change');
}
win.close();
}
window.dismissAddRelatedObjectPopup = dismissAddRelatedObjectPopup;
$('body').on('click', '.add-related', function(e) {
e.preventDefault();
if (this.href) {
showAddRelatedObjectPopup(this);
}
});
});