Normalise indentation in GridField.js

This commit is contained in:
Damian Mooyman 2017-01-11 11:38:19 +13:00
parent 4ea614f04c
commit dcee7c99d3
No known key found for this signature in database
GPG Key ID: 78B823A10DE27D1A

View File

@ -8,131 +8,131 @@ require('../../../thirdparty/jquery-entwine/dist/jquery.entwine-dist.js');
// require('../styles/legacy/GridField.scss'); // require('../styles/legacy/GridField.scss');
$.entwine('ss', function($) { $.entwine('ss', function($) {
$('.grid-field').entwine({ $('.grid-field').entwine({
/** /**
* @param {Object} Additional options for jQuery.ajax() call * @param {Object} Additional options for jQuery.ajax() call
* @param {successCallback} callback to call after reloading succeeded. * @param {successCallback} callback to call after reloading succeeded.
*/ */
reload: function(ajaxOpts, successCallback) { reload: function(ajaxOpts, successCallback) {
var self = this, form = this.closest('form'), var self = this, form = this.closest('form'),
focusedElName = this.find(':input:focus').attr('name'), // Save focused element for restoring after refresh focusedElName = this.find(':input:focus').attr('name'), // Save focused element for restoring after refresh
data = form.find(':input').serializeArray(); data = form.find(':input').serializeArray();
if(!ajaxOpts) ajaxOpts = {}; if(!ajaxOpts) ajaxOpts = {};
if(!ajaxOpts.data) ajaxOpts.data = []; if(!ajaxOpts.data) ajaxOpts.data = [];
ajaxOpts.data = ajaxOpts.data.concat(data); ajaxOpts.data = ajaxOpts.data.concat(data);
// Include any GET parameters from the current URL, as the view state might depend on it. // Include any GET parameters from the current URL, as the view state might depend on it.
// For example, a list prefiltered through external search criteria might be passed to GridField. // For example, a list prefiltered through external search criteria might be passed to GridField.
if(window.location.search) { if(window.location.search) {
ajaxOpts.data = window.location.search.replace(/^\?/, '') + '&' + $.param(ajaxOpts.data); ajaxOpts.data = window.location.search.replace(/^\?/, '') + '&' + $.param(ajaxOpts.data);
} }
form.addClass('loading'); form.addClass('loading');
$.ajax($.extend({}, { $.ajax($.extend({}, {
headers: {"X-Pjax" : 'CurrentField'}, headers: {"X-Pjax" : 'CurrentField'},
type: "POST", type: "POST",
url: this.data('url'), url: this.data('url'),
dataType: 'html', dataType: 'html',
success: function(data) { success: function(data) {
// Replace the grid field with response, not the form. // Replace the grid field with response, not the form.
// TODO Only replaces all its children, to avoid replacing the current scope // TODO Only replaces all its children, to avoid replacing the current scope
// of the executing method. Means that it doesn't retrigger the onmatch() on the main container. // of the executing method. Means that it doesn't retrigger the onmatch() on the main container.
self.empty().append($(data).children()); self.empty().append($(data).children());
// Refocus previously focused element. Useful e.g. for finding+adding // Refocus previously focused element. Useful e.g. for finding+adding
// multiple relationships via keyboard. // multiple relationships via keyboard.
if(focusedElName) self.find(':input[name="' + focusedElName + '"]').focus(); if(focusedElName) self.find(':input[name="' + focusedElName + '"]').focus();
// Update filter // Update filter
if(self.find('.filter-header').length) { if(self.find('.filter-header').length) {
var content; var content;
if(ajaxOpts.data[0].filter=="show") { if(ajaxOpts.data[0].filter=="show") {
content = '<span class="non-sortable"></span>'; content = '<span class="non-sortable"></span>';
self.addClass('show-filter').find('.filter-header').show(); self.addClass('show-filter').find('.filter-header').show();
} else { } else {
content = '<button type="button" title="Open search and filter" name="showFilter" class="btn btn-secondary font-icon-search btn--no-text btn--icon-large grid-field__filter-open"></button>'; content = '<button type="button" title="Open search and filter" name="showFilter" class="btn btn-secondary font-icon-search btn--no-text btn--icon-large grid-field__filter-open"></button>';
self.removeClass('show-filter').find('.filter-header').hide(); self.removeClass('show-filter').find('.filter-header').hide();
} }
self.find('.sortable-header th:last').html(content); self.find('.sortable-header th:last').html(content);
} }
form.removeClass('loading'); form.removeClass('loading');
if(successCallback) successCallback.apply(this, arguments); if(successCallback) successCallback.apply(this, arguments);
self.trigger('reload', self); self.trigger('reload', self);
}, },
error: function(e) { error: function(e) {
alert(i18n._t('GRIDFIELD.ERRORINTRANSACTION')); alert(i18n._t('GRIDFIELD.ERRORINTRANSACTION'));
form.removeClass('loading'); form.removeClass('loading');
} }
}, ajaxOpts)); }, ajaxOpts));
}, },
showDetailView: function(url) { showDetailView: function(url) {
window.location.href = url; window.location.href = url;
}, },
getItems: function() { getItems: function() {
return this.find('.ss-gridfield-item'); return this.find('.ss-gridfield-item');
}, },
/** /**
* @param {String} * @param {String}
* @param {Mixed} * @param {Mixed}
*/ */
setState: function(k, v) { setState: function(k, v) {
var state = this.getState(); var state = this.getState();
state[k] = v; state[k] = v;
this.find(':input[name="' + this.data('name') + '[GridState]"]').val(JSON.stringify(state)); this.find(':input[name="' + this.data('name') + '[GridState]"]').val(JSON.stringify(state));
}, },
/** /**
* @return {Object} * @return {Object}
*/ */
getState: function() { getState: function() {
return JSON.parse(this.find(':input[name="' + this.data('name') + '[GridState]"]').val()); return JSON.parse(this.find(':input[name="' + this.data('name') + '[GridState]"]').val());
} }
}); });
$('.grid-field *').entwine({ $('.grid-field *').entwine({
getGridField: function() { getGridField: function() {
return this.closest('.grid-field'); return this.closest('.grid-field');
} }
}); });
$('.grid-field :button[name=showFilter]').entwine({ $('.grid-field :button[name=showFilter]').entwine({
onclick: function(e) { onclick: function(e) {
this.closest('.grid-field__table') this.closest('.grid-field__table')
.find('.filter-header') .find('.filter-header')
.show() .show()
.find(':input:first').focus(); // focus first search field .find(':input:first').focus(); // focus first search field
this.closest('.grid-field').addClass('show-filter'); this.closest('.grid-field').addClass('show-filter');
this.parent().html('<span class="non-sortable"></span>'); this.parent().html('<span class="non-sortable"></span>');
e.preventDefault(); e.preventDefault();
} }
}); });
$('.grid-field .ss-gridfield-item').entwine({ $('.grid-field .ss-gridfield-item').entwine({
onclick: function(e) { onclick: function(e) {
if($(e.target).closest('.action').length) { if($(e.target).closest('.action').length) {
this._super(e); this._super(e);
return false; return false;
} }
var editLink = this.find('.edit-link'); var editLink = this.find('.edit-link');
if(editLink.length) this.getGridField().showDetailView(editLink.prop('href')); if(editLink.length) this.getGridField().showDetailView(editLink.prop('href'));
}, },
onmouseover: function() { onmouseover: function() {
if(this.find('.edit-link').length) this.css('cursor', 'pointer'); if(this.find('.edit-link').length) this.css('cursor', 'pointer');
}, },
onmouseout: function() { onmouseout: function() {
this.css('cursor', 'default'); this.css('cursor', 'default');
} }
}); });
$('.grid-field .action.action_import:button').entwine({ $('.grid-field .action.action_import:button').entwine({
onclick: function(e) { onclick: function(e) {
@ -140,15 +140,15 @@ $.entwine('ss', function($) {
this.openmodal(); this.openmodal();
}, },
onmatch: function() { onmatch: function() {
this._super(); this._super();
// Trigger auto-open // Trigger auto-open
if (this.data('state') === 'open') { if (this.data('state') === 'open') {
this.openmodal(); this.openmodal();
} }
}, },
onunmatch: function() { onunmatch: function() {
this._super(); this._super();
}, },
openmodal: function() { openmodal: function() {
// Remove existing modal // Remove existing modal
@ -188,271 +188,271 @@ $.entwine('ss', function($) {
} }
}); });
$('.grid-field .action:button').entwine({ $('.grid-field .action:button').entwine({
onclick: function(e){ onclick: function(e){
var filterState='show'; //filterstate should equal current state. var filterState='show'; //filterstate should equal current state.
// If the button is disabled, do nothing. // If the button is disabled, do nothing.
if (this.is(':disabled')) { if (this.is(':disabled')) {
e.preventDefault(); e.preventDefault();
return; return;
} }
if(this.hasClass('ss-gridfield-button-close') || !(this.closest('.grid-field').hasClass('show-filter'))) { if(this.hasClass('ss-gridfield-button-close') || !(this.closest('.grid-field').hasClass('show-filter'))) {
filterState='hidden'; filterState='hidden';
} }
this.getGridField().reload({ this.getGridField().reload({
data: [{name: this.attr('name'), value: this.val(), filter: filterState}] data: [{name: this.attr('name'), value: this.val(), filter: filterState}]
}); });
e.preventDefault(); e.preventDefault();
}, },
/** /**
* Get the url this action should submit to * Get the url this action should submit to
*/ */
actionurl: function() { actionurl: function() {
var btn = this.closest(':button'), grid = this.getGridField(), var btn = this.closest(':button'), grid = this.getGridField(),
form = this.closest('form'), data = form.find(':input.gridstate').serialize(), form = this.closest('form'), data = form.find(':input.gridstate').serialize(),
csrf = form.find('input[name="SecurityID"]').val(); csrf = form.find('input[name="SecurityID"]').val();
// Add current button // Add current button
data += "&" + encodeURIComponent(btn.attr('name')) + '=' + encodeURIComponent(btn.val()); data += "&" + encodeURIComponent(btn.attr('name')) + '=' + encodeURIComponent(btn.val());
// Add csrf // Add csrf
if(csrf) { if(csrf) {
data += "&SecurityID=" + encodeURIComponent(csrf); data += "&SecurityID=" + encodeURIComponent(csrf);
} }
// Include any GET parameters from the current URL, as the view // Include any GET parameters from the current URL, as the view
// state might depend on it. For example, a list pre-filtered // state might depend on it. For example, a list pre-filtered
// through external search criteria might be passed to GridField. // through external search criteria might be passed to GridField.
if(window.location.search) { if(window.location.search) {
data = window.location.search.replace(/^\?/, '') + '&' + data; data = window.location.search.replace(/^\?/, '') + '&' + data;
} }
// decide whether we should use ? or & to connect the URL // decide whether we should use ? or & to connect the URL
var connector = grid.data('url').indexOf('?') == -1 ? '?' : '&'; var connector = grid.data('url').indexOf('?') == -1 ? '?' : '&';
return $.path.makeUrlAbsolute( return $.path.makeUrlAbsolute(
grid.data('url') + connector + data, grid.data('url') + connector + data,
$('base').attr('href') $('base').attr('href')
); );
} }
}); });
/** /**
* Don't allow users to submit empty values in grid field auto complete inputs. * Don't allow users to submit empty values in grid field auto complete inputs.
*/ */
$('.grid-field .add-existing-autocompleter').entwine({ $('.grid-field .add-existing-autocompleter').entwine({
onbuttoncreate: function () { onbuttoncreate: function () {
var self = this; var self = this;
this.toggleDisabled(); this.toggleDisabled();
this.find('input[type="text"]').on('keyup', function () { this.find('input[type="text"]').on('keyup', function () {
self.toggleDisabled(); self.toggleDisabled();
}); });
}, },
onunmatch: function () { onunmatch: function () {
this.find('input[type="text"]').off('keyup'); this.find('input[type="text"]').off('keyup');
}, },
toggleDisabled: function () { toggleDisabled: function () {
var $button = this.find('.ss-ui-button'), var $button = this.find('.ss-ui-button'),
$input = this.find('input[type="text"]'), $input = this.find('input[type="text"]'),
inputHasValue = $input.val() !== '', inputHasValue = $input.val() !== '',
buttonDisabled = $button.is(':disabled'); buttonDisabled = $button.is(':disabled');
if ((inputHasValue && buttonDisabled) || (!inputHasValue && !buttonDisabled)) { if ((inputHasValue && buttonDisabled) || (!inputHasValue && !buttonDisabled)) {
$button.attr("disabled", !buttonDisabled); $button.attr("disabled", !buttonDisabled);
} }
} }
}); });
// Covers both tabular delete button, and the button on the detail form // Covers both tabular delete button, and the button on the detail form
$('.grid-field .grid-field__col-compact .action.gridfield-button-delete, .cms-edit-form .btn-toolbar button.action.action-delete').entwine({ $('.grid-field .grid-field__col-compact .action.gridfield-button-delete, .cms-edit-form .btn-toolbar button.action.action-delete').entwine({
onclick: function(e){ onclick: function(e){
if(!confirm(i18n._t('TABLEFIELD.DELETECONFIRMMESSAGE'))) { if(!confirm(i18n._t('TABLEFIELD.DELETECONFIRMMESSAGE'))) {
e.preventDefault(); e.preventDefault();
return false; return false;
} else { } else {
this._super(e); this._super(e);
} }
} }
}); });
$('.grid-field .action.gridfield-button-print').entwine({ $('.grid-field .action.gridfield-button-print').entwine({
UUID: null, UUID: null,
onmatch: function() { onmatch: function() {
this._super(); this._super();
this.setUUID(new Date().getTime()); this.setUUID(new Date().getTime());
}, },
onunmatch: function() { onunmatch: function() {
this._super(); this._super();
}, },
onclick: function(e){ onclick: function(e){
var url = this.actionurl(); var url = this.actionurl();
window.open(url); window.open(url);
e.preventDefault(); e.preventDefault();
return false; return false;
} }
}); });
$('.ss-gridfield-print-iframe').entwine({ $('.ss-gridfield-print-iframe').entwine({
onmatch: function(){ onmatch: function(){
this._super(); this._super();
this.hide().bind('load', function() { this.hide().bind('load', function() {
this.focus(); this.focus();
var ifWin = this.contentWindow || this; var ifWin = this.contentWindow || this;
ifWin.print(); ifWin.print();
}); });
}, },
onunmatch: function() { onunmatch: function() {
this._super(); this._super();
} }
}); });
/** /**
* Prevents actions from causing an ajax reload of the field. * Prevents actions from causing an ajax reload of the field.
* *
* Useful e.g. for actions which rely on HTTP response headers being * Useful e.g. for actions which rely on HTTP response headers being
* interpreted natively by the browser, like file download triggers. * interpreted natively by the browser, like file download triggers.
*/ */
$('.grid-field .action.no-ajax').entwine({ $('.grid-field .action.no-ajax').entwine({
onclick: function(e){ onclick: function(e){
window.location.href = this.actionurl(); window.location.href = this.actionurl();
e.preventDefault(); e.preventDefault();
return false; return false;
} }
}); });
$('.grid-field .action-detail').entwine({ $('.grid-field .action-detail').entwine({
onclick: function() { onclick: function() {
this.getGridField().showDetailView($(this).prop('href')); this.getGridField().showDetailView($(this).prop('href'));
return false; return false;
} }
}); });
/** /**
* Allows selection of one or more rows in the grid field. * Allows selection of one or more rows in the grid field.
* Purely clientside at the moment. * Purely clientside at the moment.
*/ */
$('.grid-field[data-selectable]').entwine({ $('.grid-field[data-selectable]').entwine({
/** /**
* @return {jQuery} Collection * @return {jQuery} Collection
*/ */
getSelectedItems: function() { getSelectedItems: function() {
return this.find('.ss-gridfield-item.ui-selected'); return this.find('.ss-gridfield-item.ui-selected');
}, },
/** /**
* @return {Array} Of record IDs * @return {Array} Of record IDs
*/ */
getSelectedIDs: function() { getSelectedIDs: function() {
return $.map(this.getSelectedItems(), function(el) {return $(el).data('id');}); return $.map(this.getSelectedItems(), function(el) {return $(el).data('id');});
} }
}); });
$('.grid-field[data-selectable] .ss-gridfield-items').entwine({ $('.grid-field[data-selectable] .ss-gridfield-items').entwine({
onadd: function() { onadd: function() {
this._super(); this._super();
// TODO Limit to single selection // TODO Limit to single selection
this.selectable(); this.selectable();
}, },
onremove: function() { onremove: function() {
this._super(); this._super();
if (this.data('selectable')) this.selectable('destroy'); if (this.data('selectable')) this.selectable('destroy');
} }
}); });
/** /**
* Catch submission event in filter input fields, and submit the correct button * Catch submission event in filter input fields, and submit the correct button
* rather than the whole form. * rather than the whole form.
*/ */
$('.grid-field .filter-header :input').entwine({ $('.grid-field .filter-header :input').entwine({
onmatch: function() { onmatch: function() {
var filterbtn = this.closest('.extra').find('.ss-gridfield-button-filter'), var filterbtn = this.closest('.extra').find('.ss-gridfield-button-filter'),
resetbtn = this.closest('.extra').find('.ss-gridfield-button-reset'); resetbtn = this.closest('.extra').find('.ss-gridfield-button-reset');
if(this.val()) { if(this.val()) {
filterbtn.addClass('filtered'); filterbtn.addClass('filtered');
resetbtn.addClass('filtered'); resetbtn.addClass('filtered');
} }
this._super(); this._super();
}, },
onunmatch: function() { onunmatch: function() {
this._super(); this._super();
}, },
onkeydown: function(e) { onkeydown: function(e) {
// Skip reset button events, they should trigger default submission // Skip reset button events, they should trigger default submission
if(this.closest('.ss-gridfield-button-reset').length) return; if(this.closest('.ss-gridfield-button-reset').length) return;
var filterbtn = this.closest('.extra').find('.ss-gridfield-button-filter'), var filterbtn = this.closest('.extra').find('.ss-gridfield-button-filter'),
resetbtn = this.closest('.extra').find('.ss-gridfield-button-reset'); resetbtn = this.closest('.extra').find('.ss-gridfield-button-reset');
if(e.keyCode == '13') { if(e.keyCode == '13') {
var btns = this.closest('.filter-header').find('.ss-gridfield-button-filter'); var btns = this.closest('.filter-header').find('.ss-gridfield-button-filter');
var filterState='show'; //filterstate should equal current state. var filterState='show'; //filterstate should equal current state.
if(this.hasClass('ss-gridfield-button-close')||!(this.closest('.grid-field').hasClass('show-filter'))){ if(this.hasClass('ss-gridfield-button-close')||!(this.closest('.grid-field').hasClass('show-filter'))){
filterState='hidden'; filterState='hidden';
} }
this.getGridField().reload({data: [{name: btns.attr('name'), value: btns.val(), filter: filterState}]}); this.getGridField().reload({data: [{name: btns.attr('name'), value: btns.val(), filter: filterState}]});
return false; return false;
}else{ }else{
filterbtn.addClass('hover-alike'); filterbtn.addClass('hover-alike');
resetbtn.addClass('hover-alike'); resetbtn.addClass('hover-alike');
} }
} }
}); });
$(".grid-field .relation-search").entwine({ $(".grid-field .relation-search").entwine({
onfocusin: function (event) { onfocusin: function (event) {
this.autocomplete({ this.autocomplete({
source: function(request, response){ source: function(request, response){
var searchField = $(this.element); var searchField = $(this.element);
var form = $(this.element).closest("form"); var form = $(this.element).closest("form");
$.ajax({ $.ajax({
headers: { headers: {
"X-Pjax" : 'Partial' "X-Pjax" : 'Partial'
}, },
dataType: 'json', dataType: 'json',
type: "GET", type: "GET",
url: $(searchField).data('searchUrl'), url: $(searchField).data('searchUrl'),
data: encodeURIComponent(searchField.attr('name'))+'='+encodeURIComponent(searchField.val()), data: encodeURIComponent(searchField.attr('name'))+'='+encodeURIComponent(searchField.val()),
success: response, success: response,
error: function(e) { error: function(e) {
alert(i18n._t('GRIDFIELD.ERRORINTRANSACTION', 'An error occured while fetching data from the server\n Please try again later.')); alert(i18n._t('GRIDFIELD.ERRORINTRANSACTION', 'An error occured while fetching data from the server\n Please try again later.'));
} }
}); });
}, },
select: function(event, ui) { select: function(event, ui) {
var hiddenField = $('<input type="hidden" name="relationID" class="action_gridfield_relationfind" />'); var hiddenField = $('<input type="hidden" name="relationID" class="action_gridfield_relationfind" />');
hiddenField.val(ui.item.id); hiddenField.val(ui.item.id);
$(this) $(this)
.closest(".grid-field") .closest(".grid-field")
.find(".action_gridfield_relationfind") .find(".action_gridfield_relationfind")
.replaceWith(hiddenField); .replaceWith(hiddenField);
var addbutton = $(this).closest(".grid-field").find(".action_gridfield_relationadd"); var addbutton = $(this).closest(".grid-field").find(".action_gridfield_relationadd");
addbutton.removeAttr('disabled'); addbutton.removeAttr('disabled');
} }
}); });
} }
}); });
$(".grid-field .pagination-page-number input").entwine({ $(".grid-field .pagination-page-number input").entwine({
onkeydown: function(event) { onkeydown: function(event) {
if(event.keyCode == 13) { if(event.keyCode == 13) {
var newpage = parseInt($(this).val(), 10); var newpage = parseInt($(this).val(), 10);
var gridfield = $(this).getGridField(); var gridfield = $(this).getGridField();
gridfield.setState('GridFieldPaginator', {currentPage: newpage}); gridfield.setState('GridFieldPaginator', {currentPage: newpage});
gridfield.reload(); gridfield.reload();
return false; return false;
} }
} }
}); });
}); });