views-admin.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. /**
  2. * @file
  3. * Some basic behaviors and utility functions for Views UI.
  4. */
  5. Drupal.viewsUi = {};
  6. Drupal.behaviors.viewsUiEditView = {};
  7. /**
  8. * Improve the user experience of the views edit interface.
  9. */
  10. Drupal.behaviors.viewsUiEditView.attach = function (context, settings) {
  11. // Only show the SQL rewrite warning when the user has chosen the
  12. // corresponding checkbox.
  13. jQuery('#edit-query-options-disable-sql-rewrite').click(function () {
  14. jQuery('.sql-rewrite-warning').toggleClass('js-hide');
  15. });
  16. };
  17. Drupal.behaviors.viewsUiAddView = {};
  18. /**
  19. * In the add view wizard, use the view name to prepopulate form fields such as
  20. * page title and menu link.
  21. */
  22. Drupal.behaviors.viewsUiAddView.attach = function (context, settings) {
  23. var $ = jQuery;
  24. var exclude, replace, suffix;
  25. // Set up regular expressions to allow only numbers, letters, and dashes.
  26. exclude = new RegExp('[^a-z0-9\\-]+', 'g');
  27. replace = '-';
  28. // The page title, block title, and menu link fields can all be prepopulated
  29. // with the view name - no regular expression needed.
  30. var $fields = $(context).find('[id^="edit-page-title"], [id^="edit-block-title"], [id^="edit-page-link-properties-title"]');
  31. if ($fields.length) {
  32. if (!this.fieldsFiller) {
  33. this.fieldsFiller = new Drupal.viewsUi.FormFieldFiller($fields);
  34. }
  35. else {
  36. // After an AJAX response, this.fieldsFiller will still have event
  37. // handlers bound to the old version of the form fields (which don't exist
  38. // anymore). The event handlers need to be unbound and then rebound to the
  39. // new markup. Note that jQuery.live is difficult to make work in this
  40. // case because the IDs of the form fields change on every AJAX response.
  41. this.fieldsFiller.rebind($fields);
  42. }
  43. }
  44. // Prepopulate the path field with a URLified version of the view name.
  45. var $pathField = $(context).find('[id^="edit-page-path"]');
  46. if ($pathField.length) {
  47. if (!this.pathFiller) {
  48. this.pathFiller = new Drupal.viewsUi.FormFieldFiller($pathField, exclude, replace);
  49. }
  50. else {
  51. this.pathFiller.rebind($pathField);
  52. }
  53. }
  54. // Populate the RSS feed field with a URLified version of the view name, and
  55. // an .xml suffix (to make it unique).
  56. var $feedField = $(context).find('[id^="edit-page-feed-properties-path"]');
  57. if ($feedField.length) {
  58. if (!this.feedFiller) {
  59. suffix = '.xml';
  60. this.feedFiller = new Drupal.viewsUi.FormFieldFiller($feedField, exclude, replace, suffix);
  61. }
  62. else {
  63. this.feedFiller.rebind($feedField);
  64. }
  65. }
  66. };
  67. /**
  68. * Constructor for the Drupal.viewsUi.FormFieldFiller object.
  69. *
  70. * Prepopulates a form field based on the view name.
  71. *
  72. * @param $target
  73. * A jQuery object representing the form field to prepopulate.
  74. * @param exclude
  75. * Optional. A regular expression representing characters to exclude from the
  76. * target field.
  77. * @param replace
  78. * Optional. A string to use as the replacement value for disallowed
  79. * characters.
  80. * @param suffix
  81. * Optional. A suffix to append at the end of the target field content.
  82. */
  83. Drupal.viewsUi.FormFieldFiller = function ($target, exclude, replace, suffix) {
  84. var $ = jQuery;
  85. this.source = $('#edit-human-name');
  86. this.target = $target;
  87. this.exclude = exclude || false;
  88. this.replace = replace || '';
  89. this.suffix = suffix || '';
  90. // Create bound versions of this instance's object methods to use as event
  91. // handlers. This will let us easily unbind those specific handlers later on.
  92. // NOTE: jQuery.proxy will not work for this because it assumes we want only
  93. // one bound version of an object method, whereas we need one version per
  94. // object instance.
  95. var self = this;
  96. this.populate = function () {return self._populate.call(self);};
  97. this.unbind = function () {return self._unbind.call(self);};
  98. this.bind();
  99. // Object constructor; no return value.
  100. };
  101. /**
  102. * Bind the form-filling behavior.
  103. */
  104. Drupal.viewsUi.FormFieldFiller.prototype.bind = function () {
  105. this.unbind();
  106. // Populate the form field when the source changes.
  107. this.source.bind('keyup.viewsUi change.viewsUi', this.populate);
  108. // Quit populating the field as soon as it gets focus.
  109. this.target.bind('focus.viewsUi', this.unbind);
  110. };
  111. /**
  112. * Get the source form field value as altered by the passed-in parameters.
  113. */
  114. Drupal.viewsUi.FormFieldFiller.prototype.getTransliterated = function () {
  115. var from = this.source.val();
  116. if (this.exclude) {
  117. from = from.toLowerCase().replace(this.exclude, this.replace);
  118. }
  119. return from + this.suffix;
  120. };
  121. /**
  122. * Populate the target form field with the altered source field value.
  123. */
  124. Drupal.viewsUi.FormFieldFiller.prototype._populate = function () {
  125. var transliterated = this.getTransliterated();
  126. this.target.val(transliterated);
  127. };
  128. /**
  129. * Stop prepopulating the form fields.
  130. */
  131. Drupal.viewsUi.FormFieldFiller.prototype._unbind = function () {
  132. this.source.unbind('keyup.viewsUi change.viewsUi', this.populate);
  133. this.target.unbind('focus.viewsUi', this.unbind);
  134. };
  135. /**
  136. * Bind event handlers to the new form fields, after they're replaced via AJAX.
  137. */
  138. Drupal.viewsUi.FormFieldFiller.prototype.rebind = function ($fields) {
  139. this.target = $fields;
  140. this.bind();
  141. }
  142. Drupal.behaviors.addItemForm = {};
  143. Drupal.behaviors.addItemForm.attach = function (context) {
  144. var $ = jQuery;
  145. // The add item form may have an id of views-ui-add-item-form--n.
  146. var $form = $(context).find('form[id^="views-ui-add-item-form"]').first();
  147. // Make sure we don't add more than one event handler to the same form.
  148. $form = $form.once('views-ui-add-item-form');
  149. if ($form.length) {
  150. new Drupal.viewsUi.addItemForm($form);
  151. }
  152. }
  153. Drupal.viewsUi.addItemForm = function($form) {
  154. this.$form = $form;
  155. this.$form.find('.views-filterable-options :checkbox').click(jQuery.proxy(this.handleCheck, this));
  156. // Find the wrapper of the displayed text.
  157. this.$selected_div = this.$form.find('.views-selected-options').parent();
  158. this.$selected_div.hide();
  159. this.checkedItems = [];
  160. }
  161. Drupal.viewsUi.addItemForm.prototype.handleCheck = function (event) {
  162. var $target = jQuery(event.target);
  163. var label = jQuery.trim($target.next().text());
  164. // Add/remove the checked item to the list.
  165. if ($target.is(':checked')) {
  166. this.$selected_div.show();
  167. this.checkedItems.push(label);
  168. }
  169. else {
  170. var length = this.checkedItems.length;
  171. var position = jQuery.inArray(label, this.checkedItems);
  172. // Delete the item from the list and take sure that the list doesn't have undefined items left.
  173. for (var i = 0; i < this.checkedItems.length; i++) {
  174. if (i == position) {
  175. this.checkedItems.splice(i, 1);
  176. i--;
  177. break;
  178. }
  179. }
  180. // Hide it again if none item is selected.
  181. if (this.checkedItems.length == 0) {
  182. this.$selected_div.hide();
  183. }
  184. }
  185. this.refreshCheckedItems();
  186. }
  187. /**
  188. * Refresh the display of the checked items.
  189. */
  190. Drupal.viewsUi.addItemForm.prototype.refreshCheckedItems = function() {
  191. // Perhaps we should precache the text div, too.
  192. this.$selected_div.find('.views-selected-options').html(this.checkedItems.join(', '));
  193. Drupal.viewsUi.resizeModal('', true);
  194. }
  195. /**
  196. * The input field items that add displays must be rendered as <input> elements.
  197. * The following behavior detaches the <input> elements from the DOM, wraps them
  198. * in an unordered list, then appends them to the list of tabs.
  199. */
  200. Drupal.behaviors.viewsUiRenderAddViewButton = {};
  201. Drupal.behaviors.viewsUiRenderAddViewButton.attach = function (context, settings) {
  202. var $ = jQuery;
  203. // Build the add display menu and pull the display input buttons into it.
  204. var $menu = $('#views-display-menu-tabs', context).once('views-ui-render-add-view-button-processed');
  205. if (!$menu.length) {
  206. return;
  207. }
  208. var $addDisplayDropdown = $('<li class="add"><a href="#"><span class="icon add"></span>' + Drupal.t('Add') + '</a><ul class="action-list" style="display:none;"></ul></li>');
  209. var $displayButtons = $menu.nextAll('input.add-display').detach();
  210. $displayButtons.appendTo($addDisplayDropdown.find('.action-list')).wrap('<li>')
  211. .parent().first().addClass('first').end().last().addClass('last');
  212. // Remove the 'Add ' prefix from the button labels since they're being palced
  213. // in an 'Add' dropdown.
  214. // @todo This assumes English, but so does $addDisplayDropdown above. Add
  215. // support for translation.
  216. $displayButtons.each(function () {
  217. var label = $(this).val();
  218. if (label.substr(0, 4) == 'Add ') {
  219. $(this).val(label.substr(4));
  220. }
  221. });
  222. $addDisplayDropdown.appendTo($menu);
  223. // Add the click handler for the add display button
  224. $('li.add > a', $menu).bind('click', function (event) {
  225. event.preventDefault();
  226. var $trigger = $(this);
  227. Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu($trigger);
  228. });
  229. // Add a mouseleave handler to close the dropdown when the user mouses
  230. // away from the item. We use mouseleave instead of mouseout because
  231. // the user is going to trigger mouseout when she moves from the trigger
  232. // link to the sub menu items.
  233. // We use the live binder because the open class on this item will be
  234. // toggled on and off and we want the handler to take effect in the cases
  235. // that the class is present, but not when it isn't.
  236. $('li.add', $menu).live('mouseleave', function (event) {
  237. var $this = $(this);
  238. var $trigger = $this.children('a[href="#"]');
  239. if ($this.children('.action-list').is(':visible')) {
  240. Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu($trigger);
  241. }
  242. });
  243. };
  244. /**
  245. * @note [@jessebeach] I feel like the following should be a more generic function and
  246. * not written specifically for this UI, but I'm not sure where to put it.
  247. */
  248. Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu = function ($trigger) {
  249. $trigger.parent().toggleClass('open');
  250. $trigger.next().slideToggle('fast');
  251. }
  252. Drupal.behaviors.viewsUiSearchOptions = {};
  253. Drupal.behaviors.viewsUiSearchOptions.attach = function (context) {
  254. var $ = jQuery;
  255. // The add item form may have an id of views-ui-add-item-form--n.
  256. var $form = $(context).find('form[id^="views-ui-add-item-form"]').first();
  257. // Make sure we don't add more than one event handler to the same form.
  258. $form = $form.once('views-ui-filter-options');
  259. if ($form.length) {
  260. new Drupal.viewsUi.OptionsSearch($form);
  261. }
  262. };
  263. /**
  264. * Constructor for the viewsUi.OptionsSearch object.
  265. *
  266. * The OptionsSearch object filters the available options on a form according
  267. * to the user's search term. Typing in "taxonomy" will show only those options
  268. * containing "taxonomy" in their label.
  269. */
  270. Drupal.viewsUi.OptionsSearch = function ($form) {
  271. this.$form = $form;
  272. // Add a keyup handler to the search box.
  273. this.$searchBox = this.$form.find('#edit-options-search');
  274. this.$searchBox.keyup(jQuery.proxy(this.handleKeyup, this));
  275. // Get a list of option labels and their corresponding divs and maintain it
  276. // in memory, so we have as little overhead as possible at keyup time.
  277. this.options = this.getOptions(this.$form.find('.filterable-option'));
  278. // Restripe on initial loading.
  279. this.handleKeyup();
  280. // Trap the ENTER key in the search box so that it doesn't submit the form.
  281. this.$searchBox.keypress(function(event) {
  282. if (event.which == 13) {
  283. event.preventDefault();
  284. }
  285. });
  286. };
  287. /**
  288. * Assemble a list of all the filterable options on the form.
  289. *
  290. * @param $allOptions
  291. * A jQuery object representing the rows of filterable options to be
  292. * shown and hidden depending on the user's search terms.
  293. */
  294. Drupal.viewsUi.OptionsSearch.prototype.getOptions = function ($allOptions) {
  295. var $ = jQuery;
  296. var i, $label, $description, $option;
  297. var options = [];
  298. var length = $allOptions.length;
  299. for (i = 0; i < length; i++) {
  300. $option = $($allOptions[i]);
  301. $label = $option.find('label');
  302. $description = $option.find('div.description');
  303. options[i] = {
  304. // Search on the lowercase version of the label text + description.
  305. 'searchText': $label.text().toLowerCase() + " " + $description.text().toLowerCase(),
  306. // Maintain a reference to the jQuery object for each row, so we don't
  307. // have to create a new object inside the performance-sensitive keyup
  308. // handler.
  309. '$div': $option
  310. }
  311. }
  312. return options;
  313. };
  314. /**
  315. * Keyup handler for the search box that hides or shows the relevant options.
  316. */
  317. Drupal.viewsUi.OptionsSearch.prototype.handleKeyup = function (event) {
  318. var found, i, j, option, search, words, wordsLength, zebraClass, zebraCounter;
  319. // Determine the user's search query. The search text has been converted to
  320. // lowercase.
  321. search = this.$searchBox.val().toLowerCase();
  322. words = search.split(' ');
  323. wordsLength = words.length;
  324. // Start the counter for restriping rows.
  325. zebraCounter = 0;
  326. // Search through the search texts in the form for matching text.
  327. var length = this.options.length;
  328. for (i = 0; i < length; i++) {
  329. // Use a local variable for the option being searched, for performance.
  330. option = this.options[i];
  331. found = true;
  332. // Each word in the search string has to match the item in order for the
  333. // item to be shown.
  334. for (j = 0; j < wordsLength; j++) {
  335. if (option.searchText.indexOf(words[j]) === -1) {
  336. found = false;
  337. }
  338. }
  339. if (found) {
  340. // Show the checkbox row, and restripe it.
  341. zebraClass = (zebraCounter % 2) ? 'odd' : 'even';
  342. option.$div.show();
  343. option.$div.removeClass('even odd');
  344. option.$div.addClass(zebraClass);
  345. zebraCounter++;
  346. }
  347. else {
  348. // The search string wasn't found; hide this item.
  349. option.$div.hide();
  350. }
  351. }
  352. };
  353. Drupal.behaviors.viewsUiPreview = {};
  354. Drupal.behaviors.viewsUiPreview.attach = function (context, settings) {
  355. var $ = jQuery;
  356. // Only act on the edit view form.
  357. var contextualFiltersBucket = $('.views-display-column .views-ui-display-tab-bucket.contextual-filters', context);
  358. if (contextualFiltersBucket.length == 0) {
  359. return;
  360. }
  361. // If the display has no contextual filters, hide the form where you enter
  362. // the contextual filters for the live preview. If it has contextual filters,
  363. // show the form.
  364. var contextualFilters = $('.views-display-setting a', contextualFiltersBucket);
  365. if (contextualFilters.length) {
  366. $('#preview-args').parent().show();
  367. }
  368. else {
  369. $('#preview-args').parent().hide();
  370. }
  371. // Executes an initial preview.
  372. if ($('#edit-displays-live-preview').once('edit-displays-live-preview').is(':checked')) {
  373. $('#preview-submit').once('edit-displays-live-preview').click();
  374. }
  375. };
  376. Drupal.behaviors.viewsUiRearrangeFilter = {};
  377. Drupal.behaviors.viewsUiRearrangeFilter.attach = function (context, settings) {
  378. var $ = jQuery;
  379. // Only act on the rearrange filter form.
  380. if (typeof Drupal.tableDrag == 'undefined' || typeof Drupal.tableDrag['views-rearrange-filters'] == 'undefined') {
  381. return;
  382. }
  383. var table = $('#views-rearrange-filters', context).once('views-rearrange-filters');
  384. var operator = $('.form-item-filter-groups-operator', context).once('views-rearrange-filters');
  385. if (table.length) {
  386. new Drupal.viewsUi.rearrangeFilterHandler(table, operator);
  387. }
  388. };
  389. /**
  390. * Improve the UI of the rearrange filters dialog box.
  391. */
  392. Drupal.viewsUi.rearrangeFilterHandler = function (table, operator) {
  393. var $ = jQuery;
  394. // Keep a reference to the <table> being altered and to the div containing
  395. // the filter groups operator dropdown (if it exists).
  396. this.table = table;
  397. this.operator = operator;
  398. this.hasGroupOperator = this.operator.length > 0;
  399. // Keep a reference to all draggable rows within the table.
  400. this.draggableRows = $('.draggable', table);
  401. // Keep a reference to the buttons for adding and removing filter groups.
  402. this.addGroupButton = $('input#views-add-group');
  403. this.removeGroupButtons = $('input.views-remove-group', table);
  404. // Add links that duplicate the functionality of the (hidden) add and remove
  405. // buttons.
  406. this.insertAddRemoveFilterGroupLinks();
  407. // When there is a filter groups operator dropdown on the page, create
  408. // duplicates of the dropdown between each pair of filter groups.
  409. if (this.hasGroupOperator) {
  410. this.dropdowns = this.duplicateGroupsOperator();
  411. this.syncGroupsOperators();
  412. }
  413. // Add methods to the tableDrag instance to account for operator cells (which
  414. // span multiple rows), the operator labels next to each filter (e.g., "And"
  415. // or "Or"), the filter groups, and other special aspects of this tableDrag
  416. // instance.
  417. this.modifyTableDrag();
  418. // Initialize the operator labels (e.g., "And" or "Or") that are displayed
  419. // next to the filters in each group, and bind a handler so that they change
  420. // based on the values of the operator dropdown within that group.
  421. this.redrawOperatorLabels();
  422. $('.views-group-title select', table)
  423. .once('views-rearrange-filter-handler')
  424. .bind('change.views-rearrange-filter-handler', $.proxy(this, 'redrawOperatorLabels'));
  425. // Bind handlers so that when a "Remove" link is clicked, we:
  426. // - Update the rowspans of cells containing an operator dropdown (since they
  427. // need to change to reflect the number of rows in each group).
  428. // - Redraw the operator labels next to the filters in the group (since the
  429. // filter that is currently displayed last in each group is not supposed to
  430. // have a label display next to it).
  431. $('a.views-groups-remove-link', this.table)
  432. .once('views-rearrange-filter-handler')
  433. .bind('click.views-rearrange-filter-handler', $.proxy(this, 'updateRowspans'))
  434. .bind('click.views-rearrange-filter-handler', $.proxy(this, 'redrawOperatorLabels'));
  435. };
  436. /**
  437. * Insert links that allow filter groups to be added and removed.
  438. */
  439. Drupal.viewsUi.rearrangeFilterHandler.prototype.insertAddRemoveFilterGroupLinks = function () {
  440. var $ = jQuery;
  441. // Insert a link for adding a new group at the top of the page, and make it
  442. // match the action links styling used in a typical page.tpl.php. Note that
  443. // Drupal does not provide a theme function for this markup, so this is the
  444. // best we can do.
  445. $('<ul class="action-links"><li><a id="views-add-group-link" href="#">' + this.addGroupButton.val() + '</a></li></ul>')
  446. .prependTo(this.table.parent())
  447. // When the link is clicked, dynamically click the hidden form button for
  448. // adding a new filter group.
  449. .once('views-rearrange-filter-handler')
  450. .bind('click.views-rearrange-filter-handler', $.proxy(this, 'clickAddGroupButton'));
  451. // Find each (visually hidden) button for removing a filter group and insert
  452. // a link next to it.
  453. var length = this.removeGroupButtons.length;
  454. for (i = 0; i < length; i++) {
  455. var $removeGroupButton = $(this.removeGroupButtons[i]);
  456. var buttonId = $removeGroupButton.attr('id');
  457. $('<a href="#" class="views-remove-group-link">' + Drupal.t('Remove group') + '</a>')
  458. .insertBefore($removeGroupButton)
  459. // When the link is clicked, dynamically click the corresponding form
  460. // button.
  461. .once('views-rearrange-filter-handler')
  462. .bind('click.views-rearrange-filter-handler', {buttonId: buttonId}, $.proxy(this, 'clickRemoveGroupButton'));
  463. }
  464. };
  465. /**
  466. * Dynamically click the button that adds a new filter group.
  467. */
  468. Drupal.viewsUi.rearrangeFilterHandler.prototype.clickAddGroupButton = function () {
  469. // Due to conflicts between Drupal core's AJAX system and the Views AJAX
  470. // system, the only way to get this to work seems to be to trigger both the
  471. // .mousedown() and .submit() events.
  472. this.addGroupButton.mousedown();
  473. this.addGroupButton.submit();
  474. return false;
  475. };
  476. /**
  477. * Dynamically click a button for removing a filter group.
  478. *
  479. * @param event
  480. * Event being triggered, with event.data.buttonId set to the ID of the
  481. * form button that should be clicked.
  482. */
  483. Drupal.viewsUi.rearrangeFilterHandler.prototype.clickRemoveGroupButton = function (event) {
  484. // For some reason, here we only need to trigger .submit(), unlike for
  485. // Drupal.viewsUi.rearrangeFilterHandler.prototype.clickAddGroupButton()
  486. // where we had to trigger .mousedown() also.
  487. jQuery('input#' + event.data.buttonId, this.table).submit();
  488. return false;
  489. };
  490. /**
  491. * Move the groups operator so that it's between the first two groups, and
  492. * duplicate it between any subsequent groups.
  493. */
  494. Drupal.viewsUi.rearrangeFilterHandler.prototype.duplicateGroupsOperator = function () {
  495. var $ = jQuery;
  496. var dropdowns, newRow;
  497. var titleRows = $('tr.views-group-title'), titleRow;
  498. // Get rid of the explanatory text around the operator; its placement is
  499. // explanatory enough.
  500. this.operator.find('label').add('div.description').addClass('element-invisible');
  501. this.operator.find('select').addClass('form-select');
  502. // Keep a list of the operator dropdowns, so we can sync their behavior later.
  503. dropdowns = this.operator;
  504. // Move the operator to a new row just above the second group.
  505. titleRow = $('tr#views-group-title-2');
  506. newRow = $('<tr class="filter-group-operator-row"><td colspan="5"></td></tr>');
  507. newRow.find('td').append(this.operator);
  508. newRow.insertBefore(titleRow);
  509. var i, length = titleRows.length;
  510. // Starting with the third group, copy the operator to a new row above the
  511. // group title.
  512. for (i = 2; i < length; i++) {
  513. titleRow = $(titleRows[i]);
  514. // Make a copy of the operator dropdown and put it in a new table row.
  515. var fakeOperator = this.operator.clone();
  516. fakeOperator.attr('id', '');
  517. newRow = $('<tr class="filter-group-operator-row"><td colspan="5"></td></tr>');
  518. newRow.find('td').append(fakeOperator);
  519. newRow.insertBefore(titleRow);
  520. dropdowns = dropdowns.add(fakeOperator);
  521. }
  522. return dropdowns;
  523. };
  524. /**
  525. * Make the duplicated groups operators change in sync with each other.
  526. */
  527. Drupal.viewsUi.rearrangeFilterHandler.prototype.syncGroupsOperators = function () {
  528. if (this.dropdowns.length < 2) {
  529. // We only have one dropdown (or none at all), so there's nothing to sync.
  530. return;
  531. }
  532. this.dropdowns.change(jQuery.proxy(this, 'operatorChangeHandler'));
  533. };
  534. /**
  535. * Click handler for the operators that appear between filter groups.
  536. *
  537. * Forces all operator dropdowns to have the same value.
  538. */
  539. Drupal.viewsUi.rearrangeFilterHandler.prototype.operatorChangeHandler = function (event) {
  540. var $ = jQuery;
  541. var $target = $(event.target);
  542. var operators = this.dropdowns.find('select').not($target);
  543. // Change the other operators to match this new value.
  544. operators.val($target.val());
  545. };
  546. Drupal.viewsUi.rearrangeFilterHandler.prototype.modifyTableDrag = function () {
  547. var tableDrag = Drupal.tableDrag['views-rearrange-filters'];
  548. var filterHandler = this;
  549. /**
  550. * Override the row.onSwap method from tabledrag.js.
  551. *
  552. * When a row is dragged to another place in the table, several things need
  553. * to occur.
  554. * - The row needs to be moved so that it's within one of the filter groups.
  555. * - The operator cells that span multiple rows need their rowspan attributes
  556. * updated to reflect the number of rows in each group.
  557. * - The operator labels that are displayed next to each filter need to be
  558. * redrawn, to account for the row's new location.
  559. */
  560. tableDrag.row.prototype.onSwap = function () {
  561. if (filterHandler.hasGroupOperator) {
  562. // Make sure the row that just got moved (this.group) is inside one of
  563. // the filter groups (i.e. below an empty marker row or a draggable). If
  564. // it isn't, move it down one.
  565. var thisRow = jQuery(this.group);
  566. var previousRow = thisRow.prev('tr');
  567. if (previousRow.length && !previousRow.hasClass('group-message') && !previousRow.hasClass('draggable')) {
  568. // Move the dragged row down one.
  569. var next = thisRow.next();
  570. if (next.is('tr')) {
  571. this.swap('after', next);
  572. }
  573. }
  574. filterHandler.updateRowspans();
  575. }
  576. // Redraw the operator labels that are displayed next to each filter, to
  577. // account for the row's new location.
  578. filterHandler.redrawOperatorLabels();
  579. };
  580. /**
  581. * Override the onDrop method from tabledrag.js.
  582. */
  583. tableDrag.onDrop = function () {
  584. var $ = jQuery;
  585. // If the tabledrag change marker (i.e., the "*") has been inserted inside
  586. // a row after the operator label (i.e., "And" or "Or") rearrange the items
  587. // so the operator label continues to appear last.
  588. var changeMarker = $(this.oldRowElement).find('.tabledrag-changed');
  589. if (changeMarker.length) {
  590. // Search for occurrences of the operator label before the change marker,
  591. // and reverse them.
  592. var operatorLabel = changeMarker.prevAll('.views-operator-label');
  593. if (operatorLabel.length) {
  594. operatorLabel.insertAfter(changeMarker);
  595. }
  596. }
  597. // Make sure the "group" dropdown is properly updated when rows are dragged
  598. // into an empty filter group. This is borrowed heavily from the block.js
  599. // implementation of tableDrag.onDrop().
  600. var groupRow = $(this.rowObject.element).prevAll('tr.group-message').get(0);
  601. var groupName = groupRow.className.replace(/([^ ]+[ ]+)*group-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
  602. var groupField = $('select.views-group-select', this.rowObject.element);
  603. if ($(this.rowObject.element).prev('tr').is('.group-message') && !groupField.is('.views-group-select-' + groupName)) {
  604. var oldGroupName = groupField.attr('class').replace(/([^ ]+[ ]+)*views-group-select-([^ ]+)([ ]+[^ ]+)*/, '$2');
  605. groupField.removeClass('views-group-select-' + oldGroupName).addClass('views-group-select-' + groupName);
  606. groupField.val(groupName);
  607. }
  608. };
  609. };
  610. /**
  611. * Redraw the operator labels that are displayed next to each filter.
  612. */
  613. Drupal.viewsUi.rearrangeFilterHandler.prototype.redrawOperatorLabels = function () {
  614. var $ = jQuery;
  615. for (i = 0; i < this.draggableRows.length; i++) {
  616. // Within the row, the operator labels are displayed inside the first table
  617. // cell (next to the filter name).
  618. var $draggableRow = $(this.draggableRows[i]);
  619. var $firstCell = $('td:first', $draggableRow);
  620. if ($firstCell.length) {
  621. // The value of the operator label ("And" or "Or") is taken from the
  622. // first operator dropdown we encounter, going backwards from the current
  623. // row. This dropdown is the one associated with the current row's filter
  624. // group.
  625. var operatorValue = $draggableRow.prevAll('.views-group-title').find('option:selected').html();
  626. var operatorLabel = '<span class="views-operator-label">' + operatorValue + '</span>';
  627. // If the next visible row after this one is a draggable filter row,
  628. // display the operator label next to the current row. (Checking for
  629. // visibility is necessary here since the "Remove" links hide the removed
  630. // row but don't actually remove it from the document).
  631. var $nextRow = $draggableRow.nextAll(':visible').eq(0);
  632. var $existingOperatorLabel = $firstCell.find('.views-operator-label');
  633. if ($nextRow.hasClass('draggable')) {
  634. // If an operator label was already there, replace it with the new one.
  635. if ($existingOperatorLabel.length) {
  636. $existingOperatorLabel.replaceWith(operatorLabel);
  637. }
  638. // Otherwise, append the operator label to the end of the table cell.
  639. else {
  640. $firstCell.append(operatorLabel);
  641. }
  642. }
  643. // If the next row doesn't contain a filter, then this is the last row
  644. // in the group. We don't want to display the operator there (since
  645. // operators should only display between two related filters, e.g.
  646. // "filter1 AND filter2 AND filter3"). So we remove any existing label
  647. // that this row has.
  648. else {
  649. $existingOperatorLabel.remove();
  650. }
  651. }
  652. }
  653. };
  654. /**
  655. * Update the rowspan attribute of each cell containing an operator dropdown.
  656. */
  657. Drupal.viewsUi.rearrangeFilterHandler.prototype.updateRowspans = function () {
  658. var $ = jQuery;
  659. var i, $row, $currentEmptyRow, draggableCount, $operatorCell;
  660. var rows = $(this.table).find('tr');
  661. var length = rows.length;
  662. for (i = 0; i < length; i++) {
  663. $row = $(rows[i]);
  664. if ($row.hasClass('views-group-title')) {
  665. // This row is a title row.
  666. // Keep a reference to the cell containing the dropdown operator.
  667. $operatorCell = $($row.find('td.group-operator'));
  668. // Assume this filter group is empty, until we find otherwise.
  669. draggableCount = 0;
  670. $currentEmptyRow = $row.next('tr');
  671. $currentEmptyRow.removeClass('group-populated').addClass('group-empty');
  672. // The cell with the dropdown operator should span the title row and
  673. // the "this group is empty" row.
  674. $operatorCell.attr('rowspan', 2);
  675. }
  676. else if (($row).hasClass('draggable') && $row.is(':visible')) {
  677. // We've found a visible filter row, so we now know the group isn't empty.
  678. draggableCount++;
  679. $currentEmptyRow.removeClass('group-empty').addClass('group-populated');
  680. // The operator cell should span all draggable rows, plus the title.
  681. $operatorCell.attr('rowspan', draggableCount + 1);
  682. }
  683. }
  684. };
  685. Drupal.behaviors.viewsFilterConfigSelectAll = {};
  686. /**
  687. * Add a select all checkbox, which checks each checkbox at once.
  688. */
  689. Drupal.behaviors.viewsFilterConfigSelectAll.attach = function(context) {
  690. var $ = jQuery;
  691. // Show the select all checkbox.
  692. $('#views-ui-config-item-form div.form-item-options-value-all', context).once(function() {
  693. $(this).show();
  694. })
  695. .find('input[type=checkbox]')
  696. .click(function() {
  697. var checked = $(this).is(':checked');
  698. // Update all checkbox beside the select all checkbox.
  699. $(this).parents('.form-checkboxes').find('input[type=checkbox]').each(function() {
  700. $(this).attr('checked', checked);
  701. });
  702. });
  703. // Uncheck the select all checkbox if any of the others are unchecked.
  704. $('#views-ui-config-item-form div.form-type-checkbox').not($('.form-item-options-value-all')).find('input[type=checkbox]').each(function() {
  705. $(this).click(function() {
  706. if ($(this).is('checked') == 0) {
  707. $('#edit-options-value-all').removeAttr('checked');
  708. }
  709. });
  710. });
  711. };
  712. /**
  713. * Ensure the desired default button is used when a form is implicitly submitted via an ENTER press on textfields, radios, and checkboxes.
  714. *
  715. * @see http://www.w3.org/TR/html5/association-of-controls-and-forms.html#implicit-submission
  716. */
  717. Drupal.behaviors.viewsImplicitFormSubmission = {};
  718. Drupal.behaviors.viewsImplicitFormSubmission.attach = function (context, settings) {
  719. var $ = jQuery;
  720. $(':text, :password, :radio, :checkbox', context).once('viewsImplicitFormSubmission', function() {
  721. $(this).keypress(function(event) {
  722. if (event.which == 13) {
  723. var formId = this.form.id;
  724. if (formId && settings.viewsImplicitFormSubmission && settings.viewsImplicitFormSubmission[formId] && settings.viewsImplicitFormSubmission[formId].defaultButton) {
  725. event.preventDefault();
  726. var buttonId = settings.viewsImplicitFormSubmission[formId].defaultButton;
  727. var $button = $('#' + buttonId, this.form);
  728. if ($button.length == 1 && $button.is(':enabled')) {
  729. if (Drupal.ajax && Drupal.ajax[buttonId]) {
  730. $button.trigger(Drupal.ajax[buttonId].element_settings.event);
  731. }
  732. else {
  733. $button.click();
  734. }
  735. }
  736. }
  737. }
  738. });
  739. });
  740. };
  741. /**
  742. * Remove icon class from elements that are themed as buttons or dropbuttons.
  743. */
  744. Drupal.behaviors.viewsRemoveIconClass = {};
  745. Drupal.behaviors.viewsRemoveIconClass.attach = function (context, settings) {
  746. jQuery('.ctools-button', context).once('RemoveIconClass', function () {
  747. var $ = jQuery;
  748. var $this = $(this);
  749. $('.icon', $this).removeClass('icon');
  750. $('.horizontal', $this).removeClass('horizontal');
  751. });
  752. };
  753. /**
  754. * Change "Expose filter" buttons into checkboxes.
  755. */
  756. Drupal.behaviors.viewsUiCheckboxify = {};
  757. Drupal.behaviors.viewsUiCheckboxify.attach = function (context, settings) {
  758. var $ = jQuery;
  759. var $buttons = $('#edit-options-expose-button-button, #edit-options-group-button-button').once('views-ui-checkboxify');
  760. var length = $buttons.length;
  761. var i;
  762. for (i = 0; i < length; i++) {
  763. new Drupal.viewsUi.Checkboxifier($buttons[i]);
  764. }
  765. };
  766. /**
  767. * Change the default widget to select the default group according to the
  768. * selected widget for the exposed group.
  769. */
  770. Drupal.behaviors.viewsUiChangeDefaultWidget = {};
  771. Drupal.behaviors.viewsUiChangeDefaultWidget.attach = function (context, settings) {
  772. var $ = jQuery;
  773. function change_default_widget(multiple) {
  774. if (multiple) {
  775. $('input.default-radios').hide();
  776. $('td.any-default-radios-row').parent().hide();
  777. $('input.default-checkboxes').show();
  778. }
  779. else {
  780. $('input.default-checkboxes').hide();
  781. $('td.any-default-radios-row').parent().show();
  782. $('input.default-radios').show();
  783. }
  784. }
  785. // Update on widget change.
  786. $('input[name="options[group_info][multiple]"]').change(function() {
  787. change_default_widget($(this).attr("checked"));
  788. });
  789. // Update the first time the form is rendered.
  790. $('input[name="options[group_info][multiple]"]').trigger('change');
  791. };
  792. /**
  793. * Attaches an expose filter button to a checkbox that triggers its click event.
  794. *
  795. * @param button
  796. * The DOM object representing the button to be checkboxified.
  797. */
  798. Drupal.viewsUi.Checkboxifier = function (button) {
  799. var $ = jQuery;
  800. this.$button = $(button);
  801. this.$parent = this.$button.parent('div.views-expose, div.views-grouped');
  802. this.$input = this.$parent.find('input:checkbox, input:radio');
  803. // Hide the button and its description.
  804. this.$button.hide();
  805. this.$parent.find('.exposed-description, .grouped-description').hide();
  806. this.$input.click($.proxy(this, 'clickHandler'));
  807. };
  808. /**
  809. * When the checkbox is checked or unchecked, simulate a button press.
  810. */
  811. Drupal.viewsUi.Checkboxifier.prototype.clickHandler = function (e) {
  812. this.$button.mousedown();
  813. this.$button.submit();
  814. };
  815. /**
  816. * Change the Apply button text based upon the override select state.
  817. */
  818. Drupal.behaviors.viewsUiOverrideSelect = {};
  819. Drupal.behaviors.viewsUiOverrideSelect.attach = function (context, settings) {
  820. var $ = jQuery;
  821. $('#edit-override-dropdown', context).once('views-ui-override-button-text', function() {
  822. // Closures! :(
  823. var $submit = $('#edit-submit', context);
  824. var old_value = $submit.val();
  825. $submit.once('views-ui-override-button-text')
  826. .bind('mouseup', function() {
  827. $(this).val(old_value);
  828. return true;
  829. });
  830. $(this).bind('change', function() {
  831. if ($(this).val() == 'default') {
  832. $submit.val(Drupal.t('Apply (all displays)'));
  833. }
  834. else if ($(this).val() == 'default_revert') {
  835. $submit.val(Drupal.t('Revert to default'));
  836. }
  837. else {
  838. $submit.val(Drupal.t('Apply (this display)'));
  839. }
  840. })
  841. .trigger('change');
  842. });
  843. };
  844. Drupal.viewsUi.resizeModal = function (e, no_shrink) {
  845. var $ = jQuery;
  846. var $modal = $('.views-ui-dialog');
  847. var $scroll = $('.scroll', $modal);
  848. if ($modal.size() == 0 || $modal.css('display') == 'none') {
  849. return;
  850. }
  851. var maxWidth = parseInt($(window).width() * .85); // 70% of window
  852. var minWidth = parseInt($(window).width() * .6); // 70% of window
  853. // Set the modal to the minwidth so that our width calculation of
  854. // children works.
  855. $modal.css('width', minWidth);
  856. var width = minWidth;
  857. // Don't let the window get more than 80% of the display high.
  858. var maxHeight = parseInt($(window).height() * .8);
  859. var minHeight = 200;
  860. if (no_shrink) {
  861. minHeight = $modal.height();
  862. }
  863. if (minHeight > maxHeight) {
  864. minHeight = maxHeight;
  865. }
  866. var height = 0;
  867. // Calculate the height of the 'scroll' region.
  868. var scrollHeight = 0;
  869. scrollHeight += parseInt($scroll.css('padding-top'));
  870. scrollHeight += parseInt($scroll.css('padding-bottom'));
  871. $scroll.children().each(function() {
  872. var w = $(this).innerWidth();
  873. if (w > width) {
  874. width = w;
  875. }
  876. scrollHeight += $(this).outerHeight(true);
  877. });
  878. // Now, calculate what the difference between the scroll and the modal
  879. // will be.
  880. var difference = 0;
  881. difference += parseInt($scroll.css('padding-top'));
  882. difference += parseInt($scroll.css('padding-bottom'));
  883. difference += $('.views-override').outerHeight(true);
  884. difference += $('.views-messages').outerHeight(true);
  885. difference += $('#views-ajax-title').outerHeight(true);
  886. difference += $('.views-add-form-selected').outerHeight(true);
  887. difference += $('.form-buttons', $modal).outerHeight(true);
  888. height = scrollHeight + difference;
  889. if (height > maxHeight) {
  890. height = maxHeight;
  891. scrollHeight = maxHeight - difference;
  892. }
  893. else if (height < minHeight) {
  894. height = minHeight;
  895. scrollHeight = minHeight - difference;
  896. }
  897. if (width > maxWidth) {
  898. width = maxWidth;
  899. }
  900. // Get where we should move content to
  901. var top = ($(window).height() / 2) - (height / 2);
  902. var left = ($(window).width() / 2) - (width / 2);
  903. $modal.css({
  904. 'top': top + 'px',
  905. 'left': left + 'px',
  906. 'width': width + 'px',
  907. 'height': height + 'px'
  908. });
  909. // Ensure inner popup height matches.
  910. $(Drupal.settings.views.ajax.popup).css('height', height + 'px');
  911. $scroll.css({
  912. 'height': scrollHeight + 'px',
  913. 'max-height': scrollHeight + 'px'
  914. });
  915. };
  916. jQuery(function() {
  917. jQuery(window).bind('resize', Drupal.viewsUi.resizeModal);
  918. jQuery(window).bind('scroll', Drupal.viewsUi.resizeModal);
  919. });