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

423 lines
16 KiB
JavaScript

$(function() {
$('h4.foldable').click(function() {
$(this).toggleClass('folded').next().toggle();
});
$('h4.foldable.folded').next().hide();
$('fieldset.foldable legend').click(function() {
$(this).parent().toggleClass('folded');
});
$('option[data-goto-url]').parents('select').on('change', function() {
var jumpto_button = this.jumpto_button;
if (typeof jumpto_button == 'undefined') {
this.jumpto_button = $('<a>', {'class': 'button button--go-to-option', text: '↗'});
this.jumpto_button.hide();
this.jumpto_button.insertAfter($(this));
}
var option = $(this).find('option:selected');
var data_url = option.data('goto-url');
if (data_url) {
this.jumpto_button.attr('href', data_url);
this.jumpto_button.show();
} else {
this.jumpto_button.hide();
}
}).trigger('change');
/* focus tab with error */
$('.form-with-tabs .error').first().closest('[role=tabpanel]').each(function(idx, elem) {
const $tab_button = $('[role=tab][aria-controls="' + $(elem).attr('id') + '"]');
$(elem).closest('.pk-tabs')[0].tabs.selectTab($tab_button[0]);
});
$('.form-with-tabs [role=tabpanel]').on('gadjo:tab-selected', function() {
$(this).find('.qommon-map').trigger('qommon:invalidate');
});
/* 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.substr(0, widget_name.lastIndexOf('$')) + '$';
$(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;
});
});
$('#journal-filter #form_object').on('change', function() {
if (this.value) {
$('[data-widget-name="object_id"]').show();
} else {
$('[data-widget-name="object_id"]').hide();
}
});
/* 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 user_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, limit: 10};
},
processResults: function (data, params) {
return {results: data.data};
},
url: '/api/users/'
},
placeholder: '-',
allowClear: true,
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, select.user-selection').length) {
$('div.submit-user-selection select, select.user-selection').select2(user_select2_options);
$('div.submit-user-selection select, select.user-selection').on('select2:open', function (e) {
var available_height = $(window).height() - $(this).offset().top;
$('ul.select2-results__options').css('max-height', (available_height - 100) + 'px');
});
$('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 working_bar_height = 0;
if ($('body[data-environment-label]').length) {
working_bar_height = 20;
}
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 + working_bar_height) + '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').css('display') != 'block') {
// if current option is not visible (not a geojson source) select
// first appropriate source.
for (const option of $('select[name="data_source$type"] option')) {
if ($(option).css('display') == 'block') {
$(option).prop('selected', true).trigger('change');
break;
}
}
}
if ($('select[name="data_source$type"] option:selected').css('display') != 'block') {
// still empty, it means there are no geojson sources at all, display
// first option (which will be "None").
$('select[name="data_source$type"] option').first().show().prop('selected', true);
}
}
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');
function prepate_journal_links() {
$('#journal-page-links a').on('click', function() {
var url = $(this).attr('href');
$.ajax({url: url, dataType: 'html', success: function(html) {
var $html = $(html);
var $table = $html.find('#journal-table');
var $page_links = $html.find('#journal-page-links');
if ($table.length && $page_links.length) {
$('#journal-table').replaceWith($table);
$('#journal-page-links').replaceWith($page_links);
prepate_journal_links();
if (window.history) {
window.history.replaceState(null, null, url);
}
}
}});
return false;
});
}
prepate_journal_links();
// 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);
}
});
});