ajax_view.es6.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /**
  2. * @file
  3. * Handles AJAX fetching of views, including filter submission and response.
  4. */
  5. (function($, Drupal, drupalSettings) {
  6. /**
  7. * Attaches the AJAX behavior to exposed filters forms and key View links.
  8. *
  9. * @type {Drupal~behavior}
  10. *
  11. * @prop {Drupal~behaviorAttach} attach
  12. * Attaches ajaxView functionality to relevant elements.
  13. */
  14. Drupal.behaviors.ViewsAjaxView = {};
  15. Drupal.behaviors.ViewsAjaxView.attach = function(context, settings) {
  16. if (settings && settings.views && settings.views.ajaxViews) {
  17. const {
  18. views: { ajaxViews },
  19. } = settings;
  20. Object.keys(ajaxViews || {}).forEach(i => {
  21. Drupal.views.instances[i] = new Drupal.views.ajaxView(ajaxViews[i]);
  22. });
  23. }
  24. };
  25. Drupal.behaviors.ViewsAjaxView.detach = (context, settings, trigger) => {
  26. if (trigger === 'unload') {
  27. if (settings && settings.views && settings.views.ajaxViews) {
  28. const {
  29. views: { ajaxViews },
  30. } = settings;
  31. Object.keys(ajaxViews || {}).forEach(i => {
  32. const selector = `.js-view-dom-id-${ajaxViews[i].view_dom_id}`;
  33. if ($(selector, context).length) {
  34. delete Drupal.views.instances[i];
  35. delete settings.views.ajaxViews[i];
  36. }
  37. });
  38. }
  39. }
  40. };
  41. /**
  42. * @namespace
  43. */
  44. Drupal.views = {};
  45. /**
  46. * @type {object.<string, Drupal.views.ajaxView>}
  47. */
  48. Drupal.views.instances = {};
  49. /**
  50. * Javascript object for a certain view.
  51. *
  52. * @constructor
  53. *
  54. * @param {object} settings
  55. * Settings object for the ajax view.
  56. * @param {string} settings.view_dom_id
  57. * The DOM id of the view.
  58. */
  59. Drupal.views.ajaxView = function(settings) {
  60. const selector = `.js-view-dom-id-${settings.view_dom_id}`;
  61. this.$view = $(selector);
  62. // Retrieve the path to use for views' ajax.
  63. let ajaxPath = drupalSettings.views.ajax_path;
  64. // If there are multiple views this might've ended up showing up multiple
  65. // times.
  66. if (ajaxPath.constructor.toString().indexOf('Array') !== -1) {
  67. ajaxPath = ajaxPath[0];
  68. }
  69. // Check if there are any GET parameters to send to views.
  70. let queryString = window.location.search || '';
  71. if (queryString !== '') {
  72. // Remove the question mark and Drupal path component if any.
  73. queryString = queryString
  74. .slice(1)
  75. .replace(/q=[^&]+&?|&?render=[^&]+/, '');
  76. if (queryString !== '') {
  77. // If there is a '?' in ajaxPath, clean url are on and & should be
  78. // used to add parameters.
  79. queryString = (/\?/.test(ajaxPath) ? '&' : '?') + queryString;
  80. }
  81. }
  82. this.element_settings = {
  83. url: ajaxPath + queryString,
  84. submit: settings,
  85. setClick: true,
  86. event: 'click',
  87. selector,
  88. progress: { type: 'fullscreen' },
  89. };
  90. this.settings = settings;
  91. // Add the ajax to exposed forms.
  92. this.$exposed_form = $(
  93. `form#views-exposed-form-${settings.view_name.replace(
  94. /_/g,
  95. '-',
  96. )}-${settings.view_display_id.replace(/_/g, '-')}`,
  97. );
  98. this.$exposed_form
  99. .once('exposed-form')
  100. .each($.proxy(this.attachExposedFormAjax, this));
  101. // Add the ajax to pagers.
  102. this.$view
  103. // Don't attach to nested views. Doing so would attach multiple behaviors
  104. // to a given element.
  105. .filter($.proxy(this.filterNestedViews, this))
  106. .once('ajax-pager')
  107. .each($.proxy(this.attachPagerAjax, this));
  108. // Add a trigger to update this view specifically. In order to trigger a
  109. // refresh use the following code.
  110. //
  111. // @code
  112. // $('.view-name').trigger('RefreshView');
  113. // @endcode
  114. const selfSettings = $.extend({}, this.element_settings, {
  115. event: 'RefreshView',
  116. base: this.selector,
  117. element: this.$view.get(0),
  118. });
  119. this.refreshViewAjax = Drupal.ajax(selfSettings);
  120. };
  121. /**
  122. * @method
  123. */
  124. Drupal.views.ajaxView.prototype.attachExposedFormAjax = function() {
  125. const that = this;
  126. this.exposedFormAjax = [];
  127. // Exclude the reset buttons so no AJAX behaviors are bound. Many things
  128. // break during the form reset phase if using AJAX.
  129. $('input[type=submit], input[type=image]', this.$exposed_form)
  130. .not('[data-drupal-selector=edit-reset]')
  131. .each(function(index) {
  132. const selfSettings = $.extend({}, that.element_settings, {
  133. base: $(this).attr('id'),
  134. element: this,
  135. });
  136. that.exposedFormAjax[index] = Drupal.ajax(selfSettings);
  137. });
  138. };
  139. /**
  140. * @return {bool}
  141. * If there is at least one parent with a view class return false.
  142. */
  143. Drupal.views.ajaxView.prototype.filterNestedViews = function() {
  144. // If there is at least one parent with a view class, this view
  145. // is nested (e.g., an attachment). Bail.
  146. return !this.$view.parents('.view').length;
  147. };
  148. /**
  149. * Attach the ajax behavior to each link.
  150. */
  151. Drupal.views.ajaxView.prototype.attachPagerAjax = function() {
  152. this.$view
  153. .find(
  154. 'ul.js-pager__items > li > a, th.views-field a, .attachment .views-summary a',
  155. )
  156. .each($.proxy(this.attachPagerLinkAjax, this));
  157. };
  158. /**
  159. * Attach the ajax behavior to a singe link.
  160. *
  161. * @param {string} [id]
  162. * The ID of the link.
  163. * @param {HTMLElement} link
  164. * The link element.
  165. */
  166. Drupal.views.ajaxView.prototype.attachPagerLinkAjax = function(id, link) {
  167. const $link = $(link);
  168. const viewData = {};
  169. const href = $link.attr('href');
  170. // Construct an object using the settings defaults and then overriding
  171. // with data specific to the link.
  172. $.extend(
  173. viewData,
  174. this.settings,
  175. Drupal.Views.parseQueryString(href),
  176. // Extract argument data from the URL.
  177. Drupal.Views.parseViewArgs(href, this.settings.view_base_path),
  178. );
  179. const selfSettings = $.extend({}, this.element_settings, {
  180. submit: viewData,
  181. base: false,
  182. element: link,
  183. });
  184. this.pagerAjax = Drupal.ajax(selfSettings);
  185. };
  186. /**
  187. * Views scroll to top ajax command.
  188. *
  189. * @param {Drupal.Ajax} [ajax]
  190. * A {@link Drupal.ajax} object.
  191. * @param {object} response
  192. * Ajax response.
  193. * @param {string} response.selector
  194. * Selector to use.
  195. */
  196. Drupal.AjaxCommands.prototype.viewsScrollTop = function(ajax, response) {
  197. // Scroll to the top of the view. This will allow users
  198. // to browse newly loaded content after e.g. clicking a pager
  199. // link.
  200. const offset = $(response.selector).offset();
  201. // We can't guarantee that the scrollable object should be
  202. // the body, as the view could be embedded in something
  203. // more complex such as a modal popup. Recurse up the DOM
  204. // and scroll the first element that has a non-zero top.
  205. let scrollTarget = response.selector;
  206. while ($(scrollTarget).scrollTop() === 0 && $(scrollTarget).parent()) {
  207. scrollTarget = $(scrollTarget).parent();
  208. }
  209. // Only scroll upward.
  210. if (offset.top - 10 < $(scrollTarget).scrollTop()) {
  211. $(scrollTarget).animate({ scrollTop: offset.top - 10 }, 500);
  212. }
  213. };
  214. })(jQuery, Drupal, drupalSettings);