Commit 058f3387 authored by lauriii's avatar lauriii

Issue #2981652 by ApacheEx, corbacho, drpal, dawehner, xjm, alexpott, lauriii:...

Issue #2981652 by ApacheEx, corbacho, drpal, dawehner, xjm, alexpott, lauriii: Format core JavaScript using recently add Prettier

(cherry picked from commit e742590e)
parent e3458a70
......@@ -10,7 +10,6 @@
"prefer-destructuring": "off",
"react/no-this-in-sfc": "off",
"react/destructuring-assignment": "off",
"import/named": "off",
"prettier/prettier": "off"
"import/named": "off"
}
}
modules/locale/tests/locale_test.es6.js
......@@ -3,7 +3,7 @@
* Attaches behaviors for Drupal's active link marking.
*/
(function (Drupal, drupalSettings) {
(function(Drupal, drupalSettings) {
/**
* Append is-active class.
*
......@@ -23,8 +23,12 @@
// Start by finding all potentially active links.
const path = drupalSettings.path;
const queryString = JSON.stringify(path.currentQuery);
const querySelector = path.currentQuery ? `[data-drupal-link-query='${queryString}']` : ':not([data-drupal-link-query])';
const originalSelectors = [`[data-drupal-link-system-path="${path.currentPath}"]`];
const querySelector = path.currentQuery
? `[data-drupal-link-query='${queryString}']`
: ':not([data-drupal-link-query])';
const originalSelectors = [
`[data-drupal-link-system-path="${path.currentPath}"]`,
];
let selectors;
// If this is the front page, we have to check for the <front> path as
......@@ -38,7 +42,9 @@
// Links without any hreflang attributes (most of them).
originalSelectors.map(selector => `${selector}:not([hreflang])`),
// Links with hreflang equals to the current language.
originalSelectors.map(selector => `${selector}[hreflang="${path.currentLanguage}"]`),
originalSelectors.map(
selector => `${selector}[hreflang="${path.currentLanguage}"]`,
),
);
// Add query string selector for pagers, exposed filters.
......@@ -53,7 +59,9 @@
},
detach(context, settings, trigger) {
if (trigger === 'unload') {
const activeLinks = context.querySelectorAll('[data-drupal-link-system-path].is-active');
const activeLinks = context.querySelectorAll(
'[data-drupal-link-system-path].is-active',
);
const il = activeLinks.length;
for (let i = 0; i < il; i++) {
activeLinks[i].classList.remove('is-active');
......@@ -61,4 +69,4 @@
}
},
};
}(Drupal, drupalSettings));
})(Drupal, drupalSettings);
This diff is collapsed.
......@@ -66,21 +66,29 @@ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr
statusText = '';
try {
statusText = '\n' + Drupal.t('StatusText: !statusText', { '!statusText': $.trim(xmlhttp.statusText) });
statusText = '\n' + Drupal.t('StatusText: !statusText', {
'!statusText': $.trim(xmlhttp.statusText)
});
} catch (e) {}
responseText = '';
try {
responseText = '\n' + Drupal.t('ResponseText: !responseText', { '!responseText': $.trim(xmlhttp.responseText) });
responseText = '\n' + Drupal.t('ResponseText: !responseText', {
'!responseText': $.trim(xmlhttp.responseText)
});
} catch (e) {}
responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '');
responseText = responseText.replace(/[\n]+\s+/g, '\n');
var readyStateText = xmlhttp.status === 0 ? '\n' + Drupal.t('ReadyState: !readyState', { '!readyState': xmlhttp.readyState }) : '';
var readyStateText = xmlhttp.status === 0 ? '\n' + Drupal.t('ReadyState: !readyState', {
'!readyState': xmlhttp.readyState
}) : '';
customMessage = customMessage ? '\n' + Drupal.t('CustomMessage: !customMessage', { '!customMessage': customMessage }) : '';
customMessage = customMessage ? '\n' + Drupal.t('CustomMessage: !customMessage', {
'!customMessage': customMessage
}) : '';
this.message = statusCode + pathText + statusText + customMessage + responseText + readyStateText;
......@@ -254,7 +262,9 @@ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr
$(ajax.element).on(elementSettings.event, function (event) {
if (!drupalSettings.ajaxTrustedUrl[ajax.url] && !Drupal.url.isLocal(ajax.url)) {
throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', { '!url': ajax.url }));
throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', {
'!url': ajax.url
}));
}
return ajax.eventResponse(this, event);
});
......@@ -610,7 +620,7 @@ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr
$('head').prepend(response.data);
var match = void 0;
var importMatch = /^@import url\("(.*)"\);$/igm;
var importMatch = /^@import url\("(.*)"\);$/gim;
if (document.styleSheets[0].addImport && importMatch.test(response.data)) {
importMatch.lastIndex = 0;
do {
......
......@@ -18,7 +18,7 @@
* });
*/
(function (Drupal, debounce) {
(function(Drupal, debounce) {
let liveElement;
const announcements = [];
......@@ -102,7 +102,7 @@
*
* @see http://www.w3.org/WAI/PF/aria-practices/#liveprops
*/
Drupal.announce = function (text, priority) {
Drupal.announce = function(text, priority) {
// Save the text and priority into a closure variable. Multiple simultaneous
// announcements will be concatenated and read in sequence.
announcements.push({
......@@ -112,6 +112,6 @@
// Immediately invoke the function that debounce returns. 200 ms is right at
// the cusp where humans notice a pause, so we will wait
// at most this much time before the set of queued announcements is read.
return (debounce(announce, 200)());
return debounce(announce, 200)();
};
}(Drupal, Drupal.debounce));
})(Drupal, Drupal.debounce);
......@@ -3,7 +3,7 @@
* Autocomplete based on jQuery UI.
*/
(function ($, Drupal) {
(function($, Drupal) {
let autocomplete;
/**
......@@ -30,12 +30,10 @@
if (character === '"') {
current += character;
quote = !quote;
}
else if (character === ',' && !quote) {
} else if (character === ',' && !quote) {
result.push(current.trim());
current = '';
}
else {
} else {
current += character;
}
}
......@@ -81,7 +79,10 @@
const term = autocomplete.extractLastTerm(event.target.value);
// Abort search if the first character is in firstCharacterBlacklist.
if (term.length > 0 && options.firstCharacterBlacklist.indexOf(term[0]) !== -1) {
if (
term.length > 0 &&
options.firstCharacterBlacklist.indexOf(term[0]) !== -1
) {
return false;
}
// Only search when the term is at least the minimum length.
......@@ -141,9 +142,11 @@
// Check if the term is already cached.
if (autocomplete.cache[elementId].hasOwnProperty(term)) {
showSuggestions(autocomplete.cache[elementId][term]);
}
else {
const options = $.extend({ success: sourceCallbackHandler, data: { q: term } }, autocomplete.ajax);
} else {
const options = $.extend(
{ success: sourceCallbackHandler, data: { q: term } },
autocomplete.ajax,
);
$.ajax(this.element.attr('data-autocomplete-path'), options);
}
}
......@@ -211,18 +214,22 @@
Drupal.behaviors.autocomplete = {
attach(context) {
// Act on textfields with the "form-autocomplete" class.
const $autocomplete = $(context).find('input.form-autocomplete').once('autocomplete');
const $autocomplete = $(context)
.find('input.form-autocomplete')
.once('autocomplete');
if ($autocomplete.length) {
// Allow options to be overriden per instance.
const blacklist = $autocomplete.attr('data-autocomplete-first-character-blacklist');
const blacklist = $autocomplete.attr(
'data-autocomplete-first-character-blacklist',
);
$.extend(autocomplete.options, {
firstCharacterBlacklist: (blacklist) || '',
firstCharacterBlacklist: blacklist || '',
});
// Use jQuery UI Autocomplete on the textfield.
$autocomplete.autocomplete(autocomplete.options)
.each(function () {
$(this).data('ui-autocomplete')._renderItem = autocomplete.options.renderItem;
});
$autocomplete.autocomplete(autocomplete.options).each(function() {
$(this).data('ui-autocomplete')._renderItem =
autocomplete.options.renderItem;
});
// Use CompositionEvent to handle IME inputs. It requests remote server on "compositionend" event only.
$autocomplete.on('compositionstart.autocomplete', () => {
......@@ -235,7 +242,8 @@
},
detach(context, settings, trigger) {
if (trigger === 'unload') {
$(context).find('input.form-autocomplete')
$(context)
.find('input.form-autocomplete')
.removeOnce('autocomplete')
.autocomplete('destroy');
}
......@@ -277,4 +285,4 @@
};
Drupal.autocomplete = autocomplete;
}(jQuery, Drupal));
})(jQuery, Drupal);
......@@ -3,7 +3,7 @@
* Drupal's batch API.
*/
(function ($, Drupal) {
(function($, Drupal) {
/**
* Attaches the batch behavior to progress bars.
*
......@@ -29,7 +29,12 @@
}
if ($progress.length) {
progressBar = new Drupal.ProgressBar('updateprogress', updateCallback, 'POST', errorCallback);
progressBar = new Drupal.ProgressBar(
'updateprogress',
updateCallback,
'POST',
errorCallback,
);
progressBar.setProgress(-1, batch.initMessage);
progressBar.startMonitoring(`${batch.uri}&op=do`, 10);
// Remove HTML from no-js progress bar.
......@@ -39,4 +44,4 @@
}
},
};
}(jQuery, Drupal));
})(jQuery, Drupal);
......@@ -3,7 +3,7 @@
* Polyfill for HTML5 details elements.
*/
(function ($, Modernizr, Drupal) {
(function($, Modernizr, Drupal) {
/**
* The collapsible details object represents a single details element.
*
......@@ -17,7 +17,10 @@
this.$node.data('details', this);
// Expand details if there are errors inside, or if it contains an
// element that is targeted by the URI fragment identifier.
const anchor = window.location.hash && window.location.hash !== '#' ? `, ${window.location.hash}` : '';
const anchor =
window.location.hash && window.location.hash !== '#'
? `, ${window.location.hash}`
: '';
if (this.$node.find(`.error${anchor}`).length) {
this.$node.attr('open', true);
}
......@@ -27,93 +30,98 @@
this.setupLegend();
}
$.extend(CollapsibleDetails, /** @lends Drupal.CollapsibleDetails */{
/**
* Holds references to instantiated CollapsibleDetails objects.
*
* @type {Array.<Drupal.CollapsibleDetails>}
*/
instances: [],
});
$.extend(CollapsibleDetails.prototype, /** @lends Drupal.CollapsibleDetails# */{
/**
* Initialize and setup summary events and markup.
*
* @fires event:summaryUpdated
*
* @listens event:summaryUpdated
*/
setupSummary() {
this.$summary = $('<span class="summary"></span>');
this.$node
.on('summaryUpdated', $.proxy(this.onSummaryUpdated, this))
.trigger('summaryUpdated');
},
/**
* Initialize and setup legend markup.
*/
setupLegend() {
// Turn the summary into a clickable link.
const $legend = this.$node.find('> summary');
$('<span class="details-summary-prefix visually-hidden"></span>')
.append(this.$node.attr('open') ? Drupal.t('Hide') : Drupal.t('Show'))
.prependTo($legend)
.after(document.createTextNode(' '));
// .wrapInner() does not retain bound events.
$('<a class="details-title"></a>')
.attr('href', `#${this.$node.attr('id')}`)
.prepend($legend.contents())
.appendTo($legend);
$legend
.append(this.$summary)
.on('click', $.proxy(this.onLegendClick, this));
$.extend(
CollapsibleDetails,
/** @lends Drupal.CollapsibleDetails */ {
/**
* Holds references to instantiated CollapsibleDetails objects.
*
* @type {Array.<Drupal.CollapsibleDetails>}
*/
instances: [],
},
/**
* Handle legend clicks.
*
* @param {jQuery.Event} e
* The event triggered.
*/
onLegendClick(e) {
this.toggle();
e.preventDefault();
},
/**
* Update summary.
*/
onSummaryUpdated() {
const text = $.trim(this.$node.drupalGetSummary());
this.$summary.html(text ? ` (${text})` : '');
},
/**
* Toggle the visibility of a details element using smooth animations.
*/
toggle() {
const isOpen = !!this.$node.attr('open');
const $summaryPrefix = this.$node.find('> summary span.details-summary-prefix');
if (isOpen) {
$summaryPrefix.html(Drupal.t('Show'));
}
else {
$summaryPrefix.html(Drupal.t('Hide'));
}
// Delay setting the attribute to emulate chrome behavior and make
// details-aria.js work as expected with this polyfill.
setTimeout(() => {
this.$node.attr('open', !isOpen);
}, 0);
);
$.extend(
CollapsibleDetails.prototype,
/** @lends Drupal.CollapsibleDetails# */ {
/**
* Initialize and setup summary events and markup.
*
* @fires event:summaryUpdated
*
* @listens event:summaryUpdated
*/
setupSummary() {
this.$summary = $('<span class="summary"></span>');
this.$node
.on('summaryUpdated', $.proxy(this.onSummaryUpdated, this))
.trigger('summaryUpdated');
},
/**
* Initialize and setup legend markup.
*/
setupLegend() {
// Turn the summary into a clickable link.
const $legend = this.$node.find('> summary');
$('<span class="details-summary-prefix visually-hidden"></span>')
.append(this.$node.attr('open') ? Drupal.t('Hide') : Drupal.t('Show'))
.prependTo($legend)
.after(document.createTextNode(' '));
// .wrapInner() does not retain bound events.
$('<a class="details-title"></a>')
.attr('href', `#${this.$node.attr('id')}`)
.prepend($legend.contents())
.appendTo($legend);
$legend
.append(this.$summary)
.on('click', $.proxy(this.onLegendClick, this));
},
/**
* Handle legend clicks.
*
* @param {jQuery.Event} e
* The event triggered.
*/
onLegendClick(e) {
this.toggle();
e.preventDefault();
},
/**
* Update summary.
*/
onSummaryUpdated() {
const text = $.trim(this.$node.drupalGetSummary());
this.$summary.html(text ? ` (${text})` : '');
},
/**
* Toggle the visibility of a details element using smooth animations.
*/
toggle() {
const isOpen = !!this.$node.attr('open');
const $summaryPrefix = this.$node.find(
'> summary span.details-summary-prefix',
);
if (isOpen) {
$summaryPrefix.html(Drupal.t('Show'));
} else {
$summaryPrefix.html(Drupal.t('Hide'));
}
// Delay setting the attribute to emulate chrome behavior and make
// details-aria.js work as expected with this polyfill.
setTimeout(() => {
this.$node.attr('open', !isOpen);
}, 0);
},
},
});
);
/**
* Polyfill HTML5 details element.
......@@ -128,10 +136,15 @@
if (Modernizr.details) {
return;
}
const $collapsibleDetails = $(context).find('details').once('collapse').addClass('collapse-processed');
const $collapsibleDetails = $(context)
.find('details')
.once('collapse')
.addClass('collapse-processed');
if ($collapsibleDetails.length) {
for (let i = 0; i < $collapsibleDetails.length; i++) {
CollapsibleDetails.instances.push(new CollapsibleDetails($collapsibleDetails[i]));
CollapsibleDetails.instances.push(
new CollapsibleDetails($collapsibleDetails[i]),
);
}
}
},
......@@ -151,14 +164,21 @@
* The targeted node as a jQuery object.
*/
const handleFragmentLinkClickOrHashChange = (e, $target) => {
$target.parents('details').not('[open]').find('> summary').trigger('click');
$target
.parents('details')
.not('[open]')
.find('> summary')
.trigger('click');
};
/**
* Binds a listener to handle fragment link clicks and URL hash changes.
*/
$('body').on('formFragmentLinkClickOrHashChange.details', handleFragmentLinkClickOrHashChange);
$('body').on(
'formFragmentLinkClickOrHashChange.details',
handleFragmentLinkClickOrHashChange,
);
// Expose constructor in the public space.
Drupal.CollapsibleDetails = CollapsibleDetails;
}(jQuery, Modernizr, Drupal));
})(jQuery, Modernizr, Drupal);
......@@ -3,7 +3,7 @@
* Polyfill for HTML5 date input.
*/
(function ($, Modernizr, Drupal) {
(function($, Modernizr, Drupal) {
/**
* Attach datepicker fallback on date elements.
*
......@@ -23,30 +23,36 @@
if (Modernizr.inputtypes.date === true) {
return;
}
$context.find('input[data-drupal-date-format]').once('datePicker').each(function () {
const $input = $(this);
const datepickerSettings = {};
const dateFormat = $input.data('drupalDateFormat');
// The date format is saved in PHP style, we need to convert to jQuery
// datepicker.
datepickerSettings.dateFormat = dateFormat
.replace('Y', 'yy')
.replace('m', 'mm')
.replace('d', 'dd');
// Add min and max date if set on the input.
if ($input.attr('min')) {
datepickerSettings.minDate = $input.attr('min');
}
if ($input.attr('max')) {
datepickerSettings.maxDate = $input.attr('max');
}
$input.datepicker(datepickerSettings);
});
$context
.find('input[data-drupal-date-format]')
.once('datePicker')
.each(function() {
const $input = $(this);
const datepickerSettings = {};
const dateFormat = $input.data('drupalDateFormat');
// The date format is saved in PHP style, we need to convert to jQuery
// datepicker.
datepickerSettings.dateFormat = dateFormat
.replace('Y', 'yy')
.replace('m', 'mm')
.replace('d', 'dd');
// Add min and max date if set on the input.
if ($input.attr('min')) {
datepickerSettings.minDate = $input.attr('min');
}
if ($input.attr('max')) {
datepickerSettings.maxDate = $input.attr('max');
}
$input.datepicker(datepickerSettings);
});
},
detach(context, settings, trigger) {
if (trigger === 'unload') {
$(context).find('input[data-drupal-date-format]').findOnce('datePicker').datepicker('destroy');
$(context)
.find('input[data-drupal-date-format]')
.findOnce('datePicker')
.datepicker('destroy');
}
},
};
}(jQuery, Modernizr, Drupal));
})(jQuery, Modernizr, Drupal);
......@@ -26,12 +26,12 @@
* @return {function}
* The debounced function.
*/
Drupal.debounce = function (func, wait, immediate) {
Drupal.debounce = function(func, wait, immediate) {
let timeout;
let result;
return function (...args) {
return function(...args) {
const context = this;
const later = function () {
const later = function() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
......
......@@ -3,7 +3,7 @@
* Add aria attribute handling for details and summary elements.
*/
(function ($, Drupal) {
(function($, Drupal) {
/**
* Handles `aria-expanded` and `aria-pressed` attributes on details elements.
*
......@@ -11,15 +11,20 @@
*/
Drupal.behaviors.detailsAria = {
attach() {
$('body').once('detailsAria').on('click.detailsAria', 'summary', (event) => {
const $summary = $(event.currentTarget);
const open = $(event.currentTarget.parentNode).attr('open') === 'open' ? 'false' : 'true';
$('body')
.once('detailsAria')
.on('click.detailsAria', 'summary', event => {
const $summary = $(event.currentTarget);
const open =
$(event.currentTarget.parentNode).attr('open') === 'open'
? 'false'
: 'true';
$summary.attr({
'aria-expanded': open,
'aria-pressed': open,
$summary.attr({
'aria-expanded': open,
'aria-pressed': open,
});
});
});
},
};
}(jQuery, Drupal));
})(jQuery, Drupal);
......@@ -3,7 +3,7 @@
* Extends the Drupal AJAX functionality to integrate the dialog API.
*/
(function ($, Drupal) {