overlay-parent.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. /**
  2. * @file
  3. * Attaches the behaviors for the Overlay parent pages.
  4. */
  5. (function ($) {
  6. /**
  7. * Open the overlay, or load content into it, when an admin link is clicked.
  8. */
  9. Drupal.behaviors.overlayParent = {
  10. attach: function (context, settings) {
  11. if (Drupal.overlay.isOpen) {
  12. Drupal.overlay.makeDocumentUntabbable(context);
  13. }
  14. if (this.processed) {
  15. return;
  16. }
  17. this.processed = true;
  18. $(window)
  19. // When the hash (URL fragment) changes, open the overlay if needed.
  20. .bind('hashchange.drupal-overlay', $.proxy(Drupal.overlay, 'eventhandlerOperateByURLFragment'))
  21. // Trigger the hashchange handler once, after the page is loaded, so that
  22. // permalinks open the overlay.
  23. .triggerHandler('hashchange.drupal-overlay');
  24. $(document)
  25. // Instead of binding a click event handler to every link we bind one to
  26. // the document and only handle events that bubble up. This allows other
  27. // scripts to bind their own handlers to links and also to prevent
  28. // overlay's handling.
  29. .bind('click.drupal-overlay mouseup.drupal-overlay', $.proxy(Drupal.overlay, 'eventhandlerOverrideLink'));
  30. }
  31. };
  32. /**
  33. * Overlay object for parent windows.
  34. *
  35. * Events
  36. * Overlay triggers a number of events that can be used by other scripts.
  37. * - drupalOverlayOpen: This event is triggered when the overlay is opened.
  38. * - drupalOverlayBeforeClose: This event is triggered when the overlay attempts
  39. * to close. If an event handler returns false, the close will be prevented.
  40. * - drupalOverlayClose: This event is triggered when the overlay is closed.
  41. * - drupalOverlayBeforeLoad: This event is triggered right before a new URL
  42. * is loaded into the overlay.
  43. * - drupalOverlayReady: This event is triggered when the DOM of the overlay
  44. * child document is fully loaded.
  45. * - drupalOverlayLoad: This event is triggered when the overlay is finished
  46. * loading.
  47. * - drupalOverlayResize: This event is triggered when the overlay is being
  48. * resized to match the parent window.
  49. */
  50. Drupal.overlay = Drupal.overlay || {
  51. isOpen: false,
  52. isOpening: false,
  53. isClosing: false,
  54. isLoading: false
  55. };
  56. Drupal.overlay.prototype = {};
  57. /**
  58. * Open the overlay.
  59. *
  60. * @param url
  61. * The URL of the page to open in the overlay.
  62. *
  63. * @return
  64. * TRUE if the overlay was opened, FALSE otherwise.
  65. */
  66. Drupal.overlay.open = function (url) {
  67. // Just one overlay is allowed.
  68. if (this.isOpen || this.isOpening) {
  69. return this.load(url);
  70. }
  71. this.isOpening = true;
  72. // Store the original document title.
  73. this.originalTitle = document.title;
  74. // Create the dialog and related DOM elements.
  75. this.create();
  76. this.isOpening = false;
  77. this.isOpen = true;
  78. $(document.documentElement).addClass('overlay-open');
  79. this.makeDocumentUntabbable();
  80. // Allow other scripts to respond to this event.
  81. $(document).trigger('drupalOverlayOpen');
  82. return this.load(url);
  83. };
  84. /**
  85. * Create the underlying markup and behaviors for the overlay.
  86. */
  87. Drupal.overlay.create = function () {
  88. this.$container = $(Drupal.theme('overlayContainer'))
  89. .appendTo(document.body);
  90. // Overlay uses transparent iframes that cover the full parent window.
  91. // When the overlay is open the scrollbar of the parent window is hidden.
  92. // Because some browsers show a white iframe background for a short moment
  93. // while loading a page into an iframe, overlay uses two iframes. By loading
  94. // the page in a hidden (inactive) iframe the user doesn't see the white
  95. // background. When the page is loaded the active and inactive iframes
  96. // are switched.
  97. this.activeFrame = this.$iframeA = $(Drupal.theme('overlayElement'))
  98. .appendTo(this.$container);
  99. this.inactiveFrame = this.$iframeB = $(Drupal.theme('overlayElement'))
  100. .appendTo(this.$container);
  101. this.$iframeA.bind('load.drupal-overlay', { self: this.$iframeA[0], sibling: this.$iframeB }, $.proxy(this, 'loadChild'));
  102. this.$iframeB.bind('load.drupal-overlay', { self: this.$iframeB[0], sibling: this.$iframeA }, $.proxy(this, 'loadChild'));
  103. // Add a second class "drupal-overlay-open" to indicate these event handlers
  104. // should only be bound when the overlay is open.
  105. var eventClass = '.drupal-overlay.drupal-overlay-open';
  106. $(window)
  107. .bind('resize' + eventClass, $.proxy(this, 'eventhandlerOuterResize'));
  108. $(document)
  109. .bind('drupalOverlayLoad' + eventClass, $.proxy(this, 'eventhandlerOuterResize'))
  110. .bind('drupalOverlayReady' + eventClass +
  111. ' drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerSyncURLFragment'))
  112. .bind('drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerRefreshPage'))
  113. .bind('drupalOverlayBeforeClose' + eventClass +
  114. ' drupalOverlayBeforeLoad' + eventClass +
  115. ' drupalOverlayResize' + eventClass, $.proxy(this, 'eventhandlerDispatchEvent'));
  116. if ($('.overlay-displace-top, .overlay-displace-bottom').length) {
  117. $(document)
  118. .bind('drupalOverlayResize' + eventClass, $.proxy(this, 'eventhandlerAlterDisplacedElements'))
  119. .bind('drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerRestoreDisplacedElements'));
  120. }
  121. };
  122. /**
  123. * Load the given URL into the overlay iframe.
  124. *
  125. * Use this method to change the URL being loaded in the overlay if it is
  126. * already open.
  127. *
  128. * @return
  129. * TRUE if URL is loaded into the overlay, FALSE otherwise.
  130. */
  131. Drupal.overlay.load = function (url) {
  132. if (!this.isOpen) {
  133. return false;
  134. }
  135. // Allow other scripts to respond to this event.
  136. $(document).trigger('drupalOverlayBeforeLoad');
  137. $(document.documentElement).addClass('overlay-loading');
  138. // The contentDocument property is not supported in IE until IE8.
  139. var iframeDocument = this.inactiveFrame[0].contentDocument || this.inactiveFrame[0].contentWindow.document;
  140. // location.replace doesn't create a history entry. location.href does.
  141. // In this case, we want location.replace, as we're creating the history
  142. // entry using URL fragments.
  143. iframeDocument.location.replace(url);
  144. return true;
  145. };
  146. /**
  147. * Close the overlay and remove markup related to it from the document.
  148. *
  149. * @return
  150. * TRUE if the overlay was closed, FALSE otherwise.
  151. */
  152. Drupal.overlay.close = function () {
  153. // Prevent double execution when close is requested more than once.
  154. if (!this.isOpen || this.isClosing) {
  155. return false;
  156. }
  157. // Allow other scripts to respond to this event.
  158. var event = $.Event('drupalOverlayBeforeClose');
  159. $(document).trigger(event);
  160. // If a handler returned false, the close will be prevented.
  161. if (event.isDefaultPrevented()) {
  162. return false;
  163. }
  164. this.isClosing = true;
  165. this.isOpen = false;
  166. $(document.documentElement).removeClass('overlay-open');
  167. // Restore the original document title.
  168. document.title = this.originalTitle;
  169. this.makeDocumentTabbable();
  170. // Allow other scripts to respond to this event.
  171. $(document).trigger('drupalOverlayClose');
  172. // When the iframe is still loading don't destroy it immediately but after
  173. // the content is loaded (see Drupal.overlay.loadChild).
  174. if (!this.isLoading) {
  175. this.destroy();
  176. this.isClosing = false;
  177. }
  178. return true;
  179. };
  180. /**
  181. * Destroy the overlay.
  182. */
  183. Drupal.overlay.destroy = function () {
  184. $([document, window]).unbind('.drupal-overlay-open');
  185. this.$container.remove();
  186. this.$container = null;
  187. this.$iframeA = null;
  188. this.$iframeB = null;
  189. this.iframeWindow = null;
  190. };
  191. /**
  192. * Redirect the overlay parent window to the given URL.
  193. *
  194. * @param url
  195. * Can be an absolute URL or a relative link to the domain root.
  196. */
  197. Drupal.overlay.redirect = function (url) {
  198. // Create a native Link object, so we can use its object methods.
  199. var link = $(url.link(url)).get(0);
  200. // If the link is already open, force the hashchange event to simulate reload.
  201. if (window.location.href == link.href) {
  202. $(window).triggerHandler('hashchange.drupal-overlay');
  203. }
  204. window.location.href = link.href;
  205. return true;
  206. };
  207. /**
  208. * Bind the child window.
  209. *
  210. * Note that this function is fired earlier than Drupal.overlay.loadChild.
  211. */
  212. Drupal.overlay.bindChild = function (iframeWindow, isClosing) {
  213. this.iframeWindow = iframeWindow;
  214. // We are done if the child window is closing.
  215. if (isClosing || this.isClosing || !this.isOpen) {
  216. return;
  217. }
  218. // Allow other scripts to respond to this event.
  219. $(document).trigger('drupalOverlayReady');
  220. };
  221. /**
  222. * Event handler: load event handler for the overlay iframe.
  223. *
  224. * @param event
  225. * Event being triggered, with the following restrictions:
  226. * - event.type: load
  227. * - event.currentTarget: iframe
  228. */
  229. Drupal.overlay.loadChild = function (event) {
  230. var iframe = event.data.self;
  231. var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
  232. var iframeWindow = iframeDocument.defaultView || iframeDocument.parentWindow;
  233. if (iframeWindow.location == 'about:blank') {
  234. return;
  235. }
  236. this.isLoading = false;
  237. $(document.documentElement).removeClass('overlay-loading');
  238. event.data.sibling.removeClass('overlay-active').attr({ 'tabindex': -1 });
  239. // Only continue when overlay is still open and not closing.
  240. if (this.isOpen && !this.isClosing) {
  241. // And child document is an actual overlayChild.
  242. if (iframeWindow.Drupal && iframeWindow.Drupal.overlayChild) {
  243. // Replace the document title with title of iframe.
  244. document.title = iframeWindow.document.title;
  245. this.activeFrame = $(iframe)
  246. .addClass('overlay-active')
  247. // Add a title attribute to the iframe for accessibility.
  248. .attr('title', Drupal.t('@title dialog', { '@title': iframeWindow.jQuery('#overlay-title').text() })).removeAttr('tabindex');
  249. this.inactiveFrame = event.data.sibling;
  250. // Load an empty document into the inactive iframe.
  251. (this.inactiveFrame[0].contentDocument || this.inactiveFrame[0].contentWindow.document).location.replace('about:blank');
  252. // Move the focus to just before the "skip to main content" link inside
  253. // the overlay.
  254. this.activeFrame.focus();
  255. var skipLink = iframeWindow.jQuery('a:first');
  256. Drupal.overlay.setFocusBefore(skipLink, iframeWindow.document);
  257. // Allow other scripts to respond to this event.
  258. $(document).trigger('drupalOverlayLoad');
  259. }
  260. else {
  261. window.location = iframeWindow.location.href.replace(/([?&]?)render=overlay&?/g, '$1').replace(/\?$/, '');
  262. }
  263. }
  264. else {
  265. this.destroy();
  266. }
  267. };
  268. /**
  269. * Creates a placeholder element to receive document focus.
  270. *
  271. * Setting the document focus to a link will make it visible, even if it's a
  272. * "skip to main content" link that should normally be visible only when the
  273. * user tabs to it. This function can be used to set the document focus to
  274. * just before such an invisible link.
  275. *
  276. * @param $element
  277. * The jQuery element that should receive focus on the next tab press.
  278. * @param document
  279. * The iframe window element to which the placeholder should be added. The
  280. * placeholder element has to be created inside the same iframe as the element
  281. * it precedes, to keep IE happy. (http://bugs.jquery.com/ticket/4059)
  282. */
  283. Drupal.overlay.setFocusBefore = function ($element, document) {
  284. // Create an anchor inside the placeholder document.
  285. var placeholder = document.createElement('a');
  286. var $placeholder = $(placeholder).addClass('element-invisible').attr('href', '#');
  287. // Put the placeholder where it belongs, and set the document focus to it.
  288. $placeholder.insertBefore($element);
  289. $placeholder.focus();
  290. // Make the placeholder disappear as soon as it loses focus, so that it
  291. // doesn't appear in the tab order again.
  292. $placeholder.one('blur', function () {
  293. $(this).remove();
  294. });
  295. };
  296. /**
  297. * Check if the given link is in the administrative section of the site.
  298. *
  299. * @param url
  300. * The URL to be tested.
  301. *
  302. * @return boolean
  303. * TRUE if the URL represents an administrative link, FALSE otherwise.
  304. */
  305. Drupal.overlay.isAdminLink = function (url) {
  306. if (Drupal.overlay.isExternalLink(url)) {
  307. return false;
  308. }
  309. var path = this.getPath(url);
  310. // Turn the list of administrative paths into a regular expression.
  311. if (!this.adminPathRegExp) {
  312. var prefix = '';
  313. if (Drupal.settings.overlay.pathPrefixes.length) {
  314. // Allow path prefixes used for language negatiation followed by slash,
  315. // and the empty string.
  316. prefix = '(' + Drupal.settings.overlay.pathPrefixes.join('/|') + '/|)';
  317. }
  318. var adminPaths = '^' + prefix + '(' + Drupal.settings.overlay.paths.admin.replace(/\s+/g, '|') + ')$';
  319. var nonAdminPaths = '^' + prefix + '(' + Drupal.settings.overlay.paths.non_admin.replace(/\s+/g, '|') + ')$';
  320. adminPaths = adminPaths.replace(/\*/g, '.*');
  321. nonAdminPaths = nonAdminPaths.replace(/\*/g, '.*');
  322. this.adminPathRegExp = new RegExp(adminPaths);
  323. this.nonAdminPathRegExp = new RegExp(nonAdminPaths);
  324. }
  325. return this.adminPathRegExp.exec(path) && !this.nonAdminPathRegExp.exec(path);
  326. };
  327. /**
  328. * Determine whether a link is external to the site.
  329. *
  330. * @param url
  331. * The URL to be tested.
  332. *
  333. * @return boolean
  334. * TRUE if the URL is external to the site, FALSE otherwise.
  335. */
  336. Drupal.overlay.isExternalLink = function (url) {
  337. var re = RegExp('^((f|ht)tps?:)?//(?!' + window.location.host + ')');
  338. return re.test(url);
  339. };
  340. /**
  341. * Event handler: resizes overlay according to the size of the parent window.
  342. *
  343. * @param event
  344. * Event being triggered, with the following restrictions:
  345. * - event.type: any
  346. * - event.currentTarget: any
  347. */
  348. Drupal.overlay.eventhandlerOuterResize = function (event) {
  349. // Proceed only if the overlay still exists.
  350. if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
  351. return;
  352. }
  353. // IE6 uses position:absolute instead of position:fixed.
  354. if (typeof document.body.style.maxHeight != 'string') {
  355. this.activeFrame.height($(window).height());
  356. }
  357. // Allow other scripts to respond to this event.
  358. $(document).trigger('drupalOverlayResize');
  359. };
  360. /**
  361. * Event handler: resizes displaced elements so they won't overlap the scrollbar
  362. * of overlay's iframe.
  363. *
  364. * @param event
  365. * Event being triggered, with the following restrictions:
  366. * - event.type: any
  367. * - event.currentTarget: any
  368. */
  369. Drupal.overlay.eventhandlerAlterDisplacedElements = function (event) {
  370. // Proceed only if the overlay still exists.
  371. if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
  372. return;
  373. }
  374. $(this.iframeWindow.document.body).css({
  375. marginTop: Drupal.overlay.getDisplacement('top'),
  376. marginBottom: Drupal.overlay.getDisplacement('bottom')
  377. })
  378. // IE7 isn't reflowing the document immediately.
  379. // @todo This might be fixed in a cleaner way.
  380. .addClass('overlay-trigger-reflow').removeClass('overlay-trigger-reflow');
  381. var documentHeight = this.iframeWindow.document.body.clientHeight;
  382. var documentWidth = this.iframeWindow.document.body.clientWidth;
  383. // IE6 doesn't support maxWidth, use width instead.
  384. var maxWidthName = (typeof document.body.style.maxWidth == 'string') ? 'maxWidth' : 'width';
  385. if (Drupal.overlay.leftSidedScrollbarOffset === undefined && $(document.documentElement).attr('dir') === 'rtl') {
  386. // We can't use element.clientLeft to detect whether scrollbars are placed
  387. // on the left side of the element when direction is set to "rtl" as most
  388. // browsers dont't support it correctly.
  389. // http://www.gtalbot.org/BugzillaSection/DocumentAllDHTMLproperties.html
  390. // There seems to be absolutely no way to detect whether the scrollbar
  391. // is on the left side in Opera; always expect scrollbar to be on the left.
  392. if ($.browser.opera) {
  393. Drupal.overlay.leftSidedScrollbarOffset = document.documentElement.clientWidth - this.iframeWindow.document.documentElement.clientWidth + this.iframeWindow.document.documentElement.clientLeft;
  394. }
  395. else if (this.iframeWindow.document.documentElement.clientLeft) {
  396. Drupal.overlay.leftSidedScrollbarOffset = this.iframeWindow.document.documentElement.clientLeft;
  397. }
  398. else {
  399. var el1 = $('<div style="direction: rtl; overflow: scroll;"></div>').appendTo(document.body);
  400. var el2 = $('<div></div>').appendTo(el1);
  401. Drupal.overlay.leftSidedScrollbarOffset = parseInt(el2[0].offsetLeft - el1[0].offsetLeft);
  402. el1.remove();
  403. }
  404. }
  405. // Consider any element that should be visible above the overlay (such as
  406. // a toolbar).
  407. $('.overlay-displace-top, .overlay-displace-bottom').each(function () {
  408. var data = $(this).data();
  409. var maxWidth = documentWidth;
  410. // In IE, Shadow filter makes element to overlap the scrollbar with 1px.
  411. if (this.filters && this.filters.length && this.filters.item('DXImageTransform.Microsoft.Shadow')) {
  412. maxWidth -= 1;
  413. }
  414. if (Drupal.overlay.leftSidedScrollbarOffset) {
  415. $(this).css('left', Drupal.overlay.leftSidedScrollbarOffset);
  416. }
  417. // Prevent displaced elements overlapping window's scrollbar.
  418. var currentMaxWidth = parseInt($(this).css(maxWidthName));
  419. if ((data.drupalOverlay && data.drupalOverlay.maxWidth) || isNaN(currentMaxWidth) || currentMaxWidth > maxWidth || currentMaxWidth <= 0) {
  420. $(this).css(maxWidthName, maxWidth);
  421. (data.drupalOverlay = data.drupalOverlay || {}).maxWidth = true;
  422. }
  423. // Use a more rigorous approach if the displaced element still overlaps
  424. // window's scrollbar; clip the element on the right.
  425. var offset = $(this).offset();
  426. var offsetRight = offset.left + $(this).outerWidth();
  427. if ((data.drupalOverlay && data.drupalOverlay.clip) || offsetRight > maxWidth) {
  428. if (Drupal.overlay.leftSidedScrollbarOffset) {
  429. $(this).css('clip', 'rect(auto, auto, ' + (documentHeight - offset.top) + 'px, ' + (Drupal.overlay.leftSidedScrollbarOffset + 2) + 'px)');
  430. }
  431. else {
  432. $(this).css('clip', 'rect(auto, ' + (maxWidth - offset.left) + 'px, ' + (documentHeight - offset.top) + 'px, auto)');
  433. }
  434. (data.drupalOverlay = data.drupalOverlay || {}).clip = true;
  435. }
  436. });
  437. };
  438. /**
  439. * Event handler: restores size of displaced elements as they were before
  440. * overlay was opened.
  441. *
  442. * @param event
  443. * Event being triggered, with the following restrictions:
  444. * - event.type: any
  445. * - event.currentTarget: any
  446. */
  447. Drupal.overlay.eventhandlerRestoreDisplacedElements = function (event) {
  448. var $displacedElements = $('.overlay-displace-top, .overlay-displace-bottom');
  449. try {
  450. $displacedElements.css({ maxWidth: '', clip: '' });
  451. }
  452. // IE bug that doesn't allow unsetting style.clip (http://dev.jquery.com/ticket/6512).
  453. catch (err) {
  454. $displacedElements.attr('style', function (index, attr) {
  455. return attr.replace(/clip\s*:\s*rect\([^)]+\);?/i, '');
  456. });
  457. }
  458. };
  459. /**
  460. * Event handler: overrides href of administrative links to be opened in
  461. * the overlay.
  462. *
  463. * This click event handler should be bound to any document (for example the
  464. * overlay iframe) of which you want links to open in the overlay.
  465. *
  466. * @param event
  467. * Event being triggered, with the following restrictions:
  468. * - event.type: click, mouseup
  469. * - event.currentTarget: document
  470. *
  471. * @see Drupal.overlayChild.behaviors.addClickHandler
  472. */
  473. Drupal.overlay.eventhandlerOverrideLink = function (event) {
  474. // In some browsers the click event isn't fired for right-clicks. Use the
  475. // mouseup event for right-clicks and the click event for everything else.
  476. if ((event.type == 'click' && event.button == 2) || (event.type == 'mouseup' && event.button != 2)) {
  477. return;
  478. }
  479. var $target = $(event.target);
  480. // Only continue if clicked target (or one of its parents) is a link.
  481. if (!$target.is('a')) {
  482. $target = $target.closest('a');
  483. if (!$target.length) {
  484. return;
  485. }
  486. }
  487. // Never open links in the overlay that contain the overlay-exclude class.
  488. if ($target.hasClass('overlay-exclude')) {
  489. return;
  490. }
  491. // Close the overlay when the link contains the overlay-close class.
  492. if ($target.hasClass('overlay-close')) {
  493. // Clearing the overlay URL fragment will close the overlay.
  494. $.bbq.removeState('overlay');
  495. return;
  496. }
  497. var target = $target[0];
  498. var href = target.href;
  499. // Only handle links that have an href attribute and use the HTTP(S) protocol.
  500. if (href != undefined && href != '' && target.protocol.match(/^https?\:/)) {
  501. var anchor = href.replace(target.ownerDocument.location.href, '');
  502. // Skip anchor links.
  503. if (anchor.length == 0 || anchor.charAt(0) == '#') {
  504. return;
  505. }
  506. // Open admin links in the overlay.
  507. else if (this.isAdminLink(href)) {
  508. // If the link contains the overlay-restore class and the overlay-context
  509. // state is set, also update the parent window's location.
  510. var parentLocation = ($target.hasClass('overlay-restore') && typeof $.bbq.getState('overlay-context') == 'string')
  511. ? Drupal.settings.basePath + $.bbq.getState('overlay-context')
  512. : null;
  513. href = this.fragmentizeLink($target.get(0), parentLocation);
  514. // Only override default behavior when left-clicking and user is not
  515. // pressing the ALT, CTRL, META (Command key on the Macintosh keyboard)
  516. // or SHIFT key.
  517. if (event.button == 0 && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
  518. // Redirect to a fragmentized href. This will trigger a hashchange event.
  519. this.redirect(href);
  520. // Prevent default action and further propagation of the event.
  521. return false;
  522. }
  523. // Otherwise alter clicked link's href. This is being picked up by
  524. // the default action handler.
  525. else {
  526. $target
  527. // Restore link's href attribute on blur or next click.
  528. .one('blur mousedown', { target: target, href: target.href }, function (event) { $(event.data.target).attr('href', event.data.href); })
  529. .attr('href', href);
  530. }
  531. }
  532. // Non-admin links should close the overlay and open in the main window,
  533. // which is the default action for a link. We only need to handle them
  534. // if the overlay is open and the clicked link is inside the overlay iframe.
  535. else if (this.isOpen && target.ownerDocument === this.iframeWindow.document) {
  536. // Open external links in the immediate parent of the frame, unless the
  537. // link already has a different target.
  538. if (target.hostname != window.location.hostname) {
  539. if (!$target.attr('target')) {
  540. $target.attr('target', '_parent');
  541. }
  542. }
  543. else {
  544. // Add the overlay-context state to the link, so "overlay-restore" links
  545. // can restore the context.
  546. if ($target[0].hash) {
  547. // Leave links with an existing fragment alone. Adding an extra
  548. // parameter to a link like "node/1#section-1" breaks the link.
  549. }
  550. else {
  551. // For links with no existing fragment, add the overlay context.
  552. $target.attr('href', $.param.fragment(href, { 'overlay-context': this.getPath(window.location) + window.location.search }));
  553. }
  554. // When the link has a destination query parameter and that destination
  555. // is an admin link we need to fragmentize it. This will make it reopen
  556. // in the overlay.
  557. var params = $.deparam.querystring(href);
  558. if (params.destination && this.isAdminLink(params.destination)) {
  559. var fragmentizedDestination = $.param.fragment(this.getPath(window.location), { overlay: params.destination });
  560. $target.attr('href', $.param.querystring(href, { destination: fragmentizedDestination }));
  561. }
  562. // Make the link open in the immediate parent of the frame, unless the
  563. // link already has a different target.
  564. if (!$target.attr('target')) {
  565. $target.attr('target', '_parent');
  566. }
  567. }
  568. }
  569. }
  570. };
  571. /**
  572. * Event handler: opens or closes the overlay based on the current URL fragment.
  573. *
  574. * @param event
  575. * Event being triggered, with the following restrictions:
  576. * - event.type: hashchange
  577. * - event.currentTarget: document
  578. */
  579. Drupal.overlay.eventhandlerOperateByURLFragment = function (event) {
  580. // If we changed the hash to reflect an internal redirect in the overlay,
  581. // its location has already been changed, so don't do anything.
  582. if ($.data(window.location, window.location.href) === 'redirect') {
  583. $.data(window.location, window.location.href, null);
  584. return;
  585. }
  586. // Get the overlay URL from the current URL fragment.
  587. var state = $.bbq.getState('overlay');
  588. if (state) {
  589. // Append render variable, so the server side can choose the right
  590. // rendering and add child frame code to the page if needed.
  591. var url = $.param.querystring(Drupal.settings.basePath + state, { render: 'overlay' });
  592. this.open(url);
  593. this.resetActiveClass(this.getPath(Drupal.settings.basePath + state));
  594. }
  595. // If there is no overlay URL in the fragment and the overlay is (still)
  596. // open, close the overlay.
  597. else if (this.isOpen && !this.isClosing) {
  598. this.close();
  599. this.resetActiveClass(this.getPath(window.location));
  600. }
  601. };
  602. /**
  603. * Event handler: makes sure the internal overlay URL is reflected in the parent
  604. * URL fragment.
  605. *
  606. * Normally the parent URL fragment determines the overlay location. However, if
  607. * the overlay redirects internally, the parent doesn't get informed, and the
  608. * parent URL fragment will be out of date. This is a sanity check to make
  609. * sure we're in the right place.
  610. *
  611. * The parent URL fragment is also not updated automatically when overlay's
  612. * open, close or load functions are used directly (instead of through
  613. * eventhandlerOperateByURLFragment).
  614. *
  615. * @param event
  616. * Event being triggered, with the following restrictions:
  617. * - event.type: drupalOverlayReady, drupalOverlayClose
  618. * - event.currentTarget: document
  619. */
  620. Drupal.overlay.eventhandlerSyncURLFragment = function (event) {
  621. if (this.isOpen) {
  622. var expected = $.bbq.getState('overlay');
  623. // This is just a sanity check, so we're comparing paths, not query strings.
  624. if (this.getPath(Drupal.settings.basePath + expected) != this.getPath(this.iframeWindow.document.location)) {
  625. // There may have been a redirect inside the child overlay window that the
  626. // parent wasn't aware of. Update the parent URL fragment appropriately.
  627. var newLocation = Drupal.overlay.fragmentizeLink(this.iframeWindow.document.location);
  628. // Set a 'redirect' flag on the new location so the hashchange event handler
  629. // knows not to change the overlay's content.
  630. $.data(window.location, newLocation, 'redirect');
  631. // Use location.replace() so we don't create an extra history entry.
  632. window.location.replace(newLocation);
  633. }
  634. }
  635. else {
  636. $.bbq.removeState('overlay');
  637. }
  638. };
  639. /**
  640. * Event handler: if the child window suggested that the parent refresh on
  641. * close, force a page refresh.
  642. *
  643. * @param event
  644. * Event being triggered, with the following restrictions:
  645. * - event.type: drupalOverlayClose
  646. * - event.currentTarget: document
  647. */
  648. Drupal.overlay.eventhandlerRefreshPage = function (event) {
  649. if (Drupal.overlay.refreshPage) {
  650. window.location.reload(true);
  651. }
  652. };
  653. /**
  654. * Event handler: dispatches events to the overlay document.
  655. *
  656. * @param event
  657. * Event being triggered, with the following restrictions:
  658. * - event.type: any
  659. * - event.currentTarget: any
  660. */
  661. Drupal.overlay.eventhandlerDispatchEvent = function (event) {
  662. if (this.iframeWindow && this.iframeWindow.document) {
  663. this.iframeWindow.jQuery(this.iframeWindow.document).trigger(event);
  664. }
  665. };
  666. /**
  667. * Make a regular admin link into a URL that will trigger the overlay to open.
  668. *
  669. * @param link
  670. * A JavaScript Link object (i.e. an <a> element).
  671. * @param parentLocation
  672. * (optional) URL to override the parent window's location with.
  673. *
  674. * @return
  675. * A URL that will trigger the overlay (in the form
  676. * /node/1#overlay=admin/config).
  677. */
  678. Drupal.overlay.fragmentizeLink = function (link, parentLocation) {
  679. // Don't operate on links that are already overlay-ready.
  680. var params = $.deparam.fragment(link.href);
  681. if (params.overlay) {
  682. return link.href;
  683. }
  684. // Determine the link's original destination. Set ignorePathFromQueryString to
  685. // true to prevent transforming this link into a clean URL while clean URLs
  686. // may be disabled.
  687. var path = this.getPath(link, true);
  688. // Preserve existing query and fragment parameters in the URL, except for
  689. // "render=overlay" which is re-added in Drupal.overlay.eventhandlerOperateByURLFragment.
  690. var destination = path + link.search.replace(/&?render=overlay/, '').replace(/\?$/, '') + link.hash;
  691. // Assemble and return the overlay-ready link.
  692. return $.param.fragment(parentLocation || window.location.href, { overlay: destination });
  693. };
  694. /**
  695. * Refresh any regions of the page that are displayed outside the overlay.
  696. *
  697. * @param data
  698. * An array of objects with information on the page regions to be refreshed.
  699. * For each object, the key is a CSS class identifying the region to be
  700. * refreshed, and the value represents the section of the Drupal $page array
  701. * corresponding to this region.
  702. */
  703. Drupal.overlay.refreshRegions = function (data) {
  704. $.each(data, function () {
  705. var region_info = this;
  706. $.each(region_info, function (regionClass) {
  707. var regionName = region_info[regionClass];
  708. var regionSelector = '.' + regionClass;
  709. // Allow special behaviors to detach.
  710. Drupal.detachBehaviors($(regionSelector));
  711. $.get(Drupal.settings.basePath + Drupal.settings.overlay.ajaxCallback + '/' + regionName, function (newElement) {
  712. $(regionSelector).replaceWith($(newElement));
  713. Drupal.attachBehaviors($(regionSelector), Drupal.settings);
  714. });
  715. });
  716. });
  717. };
  718. /**
  719. * Reset the active class on links in displaced elements according to
  720. * given path.
  721. *
  722. * @param activePath
  723. * Path to match links against.
  724. */
  725. Drupal.overlay.resetActiveClass = function(activePath) {
  726. var self = this;
  727. var windowDomain = window.location.protocol + window.location.hostname;
  728. $('.overlay-displace-top, .overlay-displace-bottom')
  729. .find('a[href]')
  730. // Remove active class from all links in displaced elements.
  731. .removeClass('active')
  732. // Add active class to links that match activePath.
  733. .each(function () {
  734. var linkDomain = this.protocol + this.hostname;
  735. var linkPath = self.getPath(this);
  736. // A link matches if it is part of the active trail of activePath, except
  737. // for frontpage links.
  738. if (linkDomain == windowDomain && (activePath + '/').indexOf(linkPath + '/') === 0 && (linkPath !== '' || activePath === '')) {
  739. $(this).addClass('active');
  740. }
  741. });
  742. };
  743. /**
  744. * Helper function to get the (corrected) Drupal path of a link.
  745. *
  746. * @param link
  747. * Link object or string to get the Drupal path from.
  748. * @param ignorePathFromQueryString
  749. * Boolean whether to ignore path from query string if path appears empty.
  750. *
  751. * @return
  752. * The Drupal path.
  753. */
  754. Drupal.overlay.getPath = function (link, ignorePathFromQueryString) {
  755. if (typeof link == 'string') {
  756. // Create a native Link object, so we can use its object methods.
  757. link = $(link.link(link)).get(0);
  758. }
  759. var path = link.pathname;
  760. // Ensure a leading slash on the path, omitted in some browsers.
  761. if (path.charAt(0) != '/') {
  762. path = '/' + path;
  763. }
  764. path = path.replace(new RegExp(Drupal.settings.basePath + '(?:index.php)?'), '');
  765. if (path == '' && !ignorePathFromQueryString) {
  766. // If the path appears empty, it might mean the path is represented in the
  767. // query string (clean URLs are not used).
  768. var match = new RegExp('([?&])q=(.+)([&#]|$)').exec(link.search);
  769. if (match && match.length == 4) {
  770. path = match[2];
  771. }
  772. }
  773. return path;
  774. };
  775. /**
  776. * Get the total displacement of given region.
  777. *
  778. * @param region
  779. * Region name. Either "top" or "bottom".
  780. *
  781. * @return
  782. * The total displacement of given region in pixels.
  783. */
  784. Drupal.overlay.getDisplacement = function (region) {
  785. var displacement = 0;
  786. var lastDisplaced = $('.overlay-displace-' + region + ':last');
  787. if (lastDisplaced.length) {
  788. displacement = lastDisplaced.offset().top + lastDisplaced.outerHeight();
  789. // In modern browsers (including IE9), when box-shadow is defined, use the
  790. // normal height.
  791. var cssBoxShadowValue = lastDisplaced.css('box-shadow');
  792. var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none');
  793. // In IE8 and below, we use the shadow filter to apply box-shadow styles to
  794. // the toolbar. It adds some extra height that we need to remove.
  795. if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test(lastDisplaced.css('filter'))) {
  796. displacement -= lastDisplaced[0].filters.item('DXImageTransform.Microsoft.Shadow').strength;
  797. displacement = Math.max(0, displacement);
  798. }
  799. }
  800. return displacement;
  801. };
  802. /**
  803. * Makes elements outside the overlay unreachable via the tab key.
  804. *
  805. * @param context
  806. * The part of the DOM that should have its tabindexes changed. Defaults to
  807. * the entire page.
  808. */
  809. Drupal.overlay.makeDocumentUntabbable = function (context) {
  810. // Manipulating tabindexes for the entire document is unacceptably slow in IE6
  811. // and IE7, so in those browsers, the underlying page will still be reachable
  812. // via the tab key. However, we still make the links within the Disable
  813. // message unreachable, because the same message also exists within the
  814. // child document. The duplicate copy in the underlying document is only for
  815. // assisting screen-reader users navigating the document with reading commands
  816. // that follow markup order rather than tab order.
  817. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
  818. $('#overlay-disable-message a', context).attr('tabindex', -1);
  819. return;
  820. }
  821. context = context || document.body;
  822. var $overlay, $tabbable, $hasTabindex;
  823. // Determine which elements on the page already have a tabindex.
  824. $hasTabindex = $('[tabindex] :not(.overlay-element)', context);
  825. // Record the tabindex for each element, so we can restore it later.
  826. $hasTabindex.each(Drupal.overlay._recordTabindex);
  827. // Add the tabbable elements from the current context to any that we might
  828. // have previously recorded.
  829. Drupal.overlay._hasTabindex = $hasTabindex.add(Drupal.overlay._hasTabindex);
  830. // Set tabindex to -1 on everything outside the overlay and toolbars, so that
  831. // the underlying page is unreachable.
  832. // By default, browsers make a, area, button, input, object, select, textarea,
  833. // and iframe elements reachable via the tab key.
  834. $tabbable = $('a, area, button, input, object, select, textarea, iframe');
  835. // If another element (like a div) has a tabindex, it's also tabbable.
  836. $tabbable = $tabbable.add($hasTabindex);
  837. // Leave links inside the overlay and toolbars alone.
  838. $overlay = $('.overlay-element, #overlay-container, .overlay-displace-top, .overlay-displace-bottom').find('*');
  839. $tabbable = $tabbable.not($overlay);
  840. // We now have a list of everything in the underlying document that could
  841. // possibly be reachable via the tab key. Make it all unreachable.
  842. $tabbable.attr('tabindex', -1);
  843. };
  844. /**
  845. * Restores the original tabindex value of a group of elements.
  846. *
  847. * @param context
  848. * The part of the DOM that should have its tabindexes restored. Defaults to
  849. * the entire page.
  850. */
  851. Drupal.overlay.makeDocumentTabbable = function (context) {
  852. // Manipulating tabindexes is unacceptably slow in IE6 and IE7. In those
  853. // browsers, the underlying page was never made unreachable via tab, so
  854. // there is no work to be done here.
  855. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
  856. return;
  857. }
  858. var $needsTabindex;
  859. context = context || document.body;
  860. // Make the underlying document tabbable again by removing all existing
  861. // tabindex attributes.
  862. var $tabindex = $('[tabindex]', context);
  863. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
  864. // removeAttr('tabindex') is broken in IE6-7, but the DOM function
  865. // removeAttribute works.
  866. var i;
  867. var length = $tabindex.length;
  868. for (i = 0; i < length; i++) {
  869. $tabindex[i].removeAttribute('tabIndex');
  870. }
  871. }
  872. else {
  873. $tabindex.removeAttr('tabindex');
  874. }
  875. // Restore the tabindex attributes that existed before the overlay was opened.
  876. $needsTabindex = $(Drupal.overlay._hasTabindex, context);
  877. $needsTabindex.each(Drupal.overlay._restoreTabindex);
  878. Drupal.overlay._hasTabindex = Drupal.overlay._hasTabindex.not($needsTabindex);
  879. };
  880. /**
  881. * Record the tabindex for an element, using $.data.
  882. *
  883. * Meant to be used as a jQuery.fn.each callback.
  884. */
  885. Drupal.overlay._recordTabindex = function () {
  886. var $element = $(this);
  887. var tabindex = $(this).attr('tabindex');
  888. $element.data('drupalOverlayOriginalTabIndex', tabindex);
  889. };
  890. /**
  891. * Restore an element's original tabindex.
  892. *
  893. * Meant to be used as a jQuery.fn.each callback.
  894. */
  895. Drupal.overlay._restoreTabindex = function () {
  896. var $element = $(this);
  897. var tabindex = $element.data('drupalOverlayOriginalTabIndex');
  898. $element.attr('tabindex', tabindex);
  899. };
  900. /**
  901. * Theme function to create the overlay iframe element.
  902. */
  903. Drupal.theme.prototype.overlayContainer = function () {
  904. return '<div id="overlay-container"><div class="overlay-modal-background"></div></div>';
  905. };
  906. /**
  907. * Theme function to create an overlay iframe element.
  908. */
  909. Drupal.theme.prototype.overlayElement = function (url) {
  910. return '<iframe class="overlay-element" frameborder="0" scrolling="auto" allowtransparency="true"></iframe>';
  911. };
  912. })(jQuery);