overlay-parent.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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.
  563. $target.attr('target', '_parent');
  564. }
  565. }
  566. }
  567. };
  568. /**
  569. * Event handler: opens or closes the overlay based on the current URL fragment.
  570. *
  571. * @param event
  572. * Event being triggered, with the following restrictions:
  573. * - event.type: hashchange
  574. * - event.currentTarget: document
  575. */
  576. Drupal.overlay.eventhandlerOperateByURLFragment = function (event) {
  577. // If we changed the hash to reflect an internal redirect in the overlay,
  578. // its location has already been changed, so don't do anything.
  579. if ($.data(window.location, window.location.href) === 'redirect') {
  580. $.data(window.location, window.location.href, null);
  581. return;
  582. }
  583. // Get the overlay URL from the current URL fragment.
  584. var state = $.bbq.getState('overlay');
  585. if (state) {
  586. // Append render variable, so the server side can choose the right
  587. // rendering and add child frame code to the page if needed.
  588. var url = $.param.querystring(Drupal.settings.basePath + state, { render: 'overlay' });
  589. this.open(url);
  590. this.resetActiveClass(this.getPath(Drupal.settings.basePath + state));
  591. }
  592. // If there is no overlay URL in the fragment and the overlay is (still)
  593. // open, close the overlay.
  594. else if (this.isOpen && !this.isClosing) {
  595. this.close();
  596. this.resetActiveClass(this.getPath(window.location));
  597. }
  598. };
  599. /**
  600. * Event handler: makes sure the internal overlay URL is reflected in the parent
  601. * URL fragment.
  602. *
  603. * Normally the parent URL fragment determines the overlay location. However, if
  604. * the overlay redirects internally, the parent doesn't get informed, and the
  605. * parent URL fragment will be out of date. This is a sanity check to make
  606. * sure we're in the right place.
  607. *
  608. * The parent URL fragment is also not updated automatically when overlay's
  609. * open, close or load functions are used directly (instead of through
  610. * eventhandlerOperateByURLFragment).
  611. *
  612. * @param event
  613. * Event being triggered, with the following restrictions:
  614. * - event.type: drupalOverlayReady, drupalOverlayClose
  615. * - event.currentTarget: document
  616. */
  617. Drupal.overlay.eventhandlerSyncURLFragment = function (event) {
  618. if (this.isOpen) {
  619. var expected = $.bbq.getState('overlay');
  620. // This is just a sanity check, so we're comparing paths, not query strings.
  621. if (this.getPath(Drupal.settings.basePath + expected) != this.getPath(this.iframeWindow.document.location)) {
  622. // There may have been a redirect inside the child overlay window that the
  623. // parent wasn't aware of. Update the parent URL fragment appropriately.
  624. var newLocation = Drupal.overlay.fragmentizeLink(this.iframeWindow.document.location);
  625. // Set a 'redirect' flag on the new location so the hashchange event handler
  626. // knows not to change the overlay's content.
  627. $.data(window.location, newLocation, 'redirect');
  628. // Use location.replace() so we don't create an extra history entry.
  629. window.location.replace(newLocation);
  630. }
  631. }
  632. else {
  633. $.bbq.removeState('overlay');
  634. }
  635. };
  636. /**
  637. * Event handler: if the child window suggested that the parent refresh on
  638. * close, force a page refresh.
  639. *
  640. * @param event
  641. * Event being triggered, with the following restrictions:
  642. * - event.type: drupalOverlayClose
  643. * - event.currentTarget: document
  644. */
  645. Drupal.overlay.eventhandlerRefreshPage = function (event) {
  646. if (Drupal.overlay.refreshPage) {
  647. window.location.reload(true);
  648. }
  649. };
  650. /**
  651. * Event handler: dispatches events to the overlay document.
  652. *
  653. * @param event
  654. * Event being triggered, with the following restrictions:
  655. * - event.type: any
  656. * - event.currentTarget: any
  657. */
  658. Drupal.overlay.eventhandlerDispatchEvent = function (event) {
  659. if (this.iframeWindow && this.iframeWindow.document) {
  660. this.iframeWindow.jQuery(this.iframeWindow.document).trigger(event);
  661. }
  662. };
  663. /**
  664. * Make a regular admin link into a URL that will trigger the overlay to open.
  665. *
  666. * @param link
  667. * A JavaScript Link object (i.e. an <a> element).
  668. * @param parentLocation
  669. * (optional) URL to override the parent window's location with.
  670. *
  671. * @return
  672. * A URL that will trigger the overlay (in the form
  673. * /node/1#overlay=admin/config).
  674. */
  675. Drupal.overlay.fragmentizeLink = function (link, parentLocation) {
  676. // Don't operate on links that are already overlay-ready.
  677. var params = $.deparam.fragment(link.href);
  678. if (params.overlay) {
  679. return link.href;
  680. }
  681. // Determine the link's original destination. Set ignorePathFromQueryString to
  682. // true to prevent transforming this link into a clean URL while clean URLs
  683. // may be disabled.
  684. var path = this.getPath(link, true);
  685. // Preserve existing query and fragment parameters in the URL, except for
  686. // "render=overlay" which is re-added in Drupal.overlay.eventhandlerOperateByURLFragment.
  687. var destination = path + link.search.replace(/&?render=overlay/, '').replace(/\?$/, '') + link.hash;
  688. // Assemble and return the overlay-ready link.
  689. return $.param.fragment(parentLocation || window.location.href, { overlay: destination });
  690. };
  691. /**
  692. * Refresh any regions of the page that are displayed outside the overlay.
  693. *
  694. * @param data
  695. * An array of objects with information on the page regions to be refreshed.
  696. * For each object, the key is a CSS class identifying the region to be
  697. * refreshed, and the value represents the section of the Drupal $page array
  698. * corresponding to this region.
  699. */
  700. Drupal.overlay.refreshRegions = function (data) {
  701. $.each(data, function () {
  702. var region_info = this;
  703. $.each(region_info, function (regionClass) {
  704. var regionName = region_info[regionClass];
  705. var regionSelector = '.' + regionClass;
  706. // Allow special behaviors to detach.
  707. Drupal.detachBehaviors($(regionSelector));
  708. $.get(Drupal.settings.basePath + Drupal.settings.overlay.ajaxCallback + '/' + regionName, function (newElement) {
  709. $(regionSelector).replaceWith($(newElement));
  710. Drupal.attachBehaviors($(regionSelector), Drupal.settings);
  711. });
  712. });
  713. });
  714. };
  715. /**
  716. * Reset the active class on links in displaced elements according to
  717. * given path.
  718. *
  719. * @param activePath
  720. * Path to match links against.
  721. */
  722. Drupal.overlay.resetActiveClass = function(activePath) {
  723. var self = this;
  724. var windowDomain = window.location.protocol + window.location.hostname;
  725. $('.overlay-displace-top, .overlay-displace-bottom')
  726. .find('a[href]')
  727. // Remove active class from all links in displaced elements.
  728. .removeClass('active')
  729. // Add active class to links that match activePath.
  730. .each(function () {
  731. var linkDomain = this.protocol + this.hostname;
  732. var linkPath = self.getPath(this);
  733. // A link matches if it is part of the active trail of activePath, except
  734. // for frontpage links.
  735. if (linkDomain == windowDomain && (activePath + '/').indexOf(linkPath + '/') === 0 && (linkPath !== '' || activePath === '')) {
  736. $(this).addClass('active');
  737. }
  738. });
  739. };
  740. /**
  741. * Helper function to get the (corrected) Drupal path of a link.
  742. *
  743. * @param link
  744. * Link object or string to get the Drupal path from.
  745. * @param ignorePathFromQueryString
  746. * Boolean whether to ignore path from query string if path appears empty.
  747. *
  748. * @return
  749. * The Drupal path.
  750. */
  751. Drupal.overlay.getPath = function (link, ignorePathFromQueryString) {
  752. if (typeof link == 'string') {
  753. // Create a native Link object, so we can use its object methods.
  754. link = $(link.link(link)).get(0);
  755. }
  756. var path = link.pathname;
  757. // Ensure a leading slash on the path, omitted in some browsers.
  758. if (path.charAt(0) != '/') {
  759. path = '/' + path;
  760. }
  761. path = path.replace(new RegExp(Drupal.settings.basePath + '(?:index.php)?'), '');
  762. if (path == '' && !ignorePathFromQueryString) {
  763. // If the path appears empty, it might mean the path is represented in the
  764. // query string (clean URLs are not used).
  765. var match = new RegExp('([?&])q=(.+)([&#]|$)').exec(link.search);
  766. if (match && match.length == 4) {
  767. path = match[2];
  768. }
  769. }
  770. return path;
  771. };
  772. /**
  773. * Get the total displacement of given region.
  774. *
  775. * @param region
  776. * Region name. Either "top" or "bottom".
  777. *
  778. * @return
  779. * The total displacement of given region in pixels.
  780. */
  781. Drupal.overlay.getDisplacement = function (region) {
  782. var displacement = 0;
  783. var lastDisplaced = $('.overlay-displace-' + region + ':last');
  784. if (lastDisplaced.length) {
  785. displacement = lastDisplaced.offset().top + lastDisplaced.outerHeight();
  786. // In modern browsers (including IE9), when box-shadow is defined, use the
  787. // normal height.
  788. var cssBoxShadowValue = lastDisplaced.css('box-shadow');
  789. var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none');
  790. // In IE8 and below, we use the shadow filter to apply box-shadow styles to
  791. // the toolbar. It adds some extra height that we need to remove.
  792. if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test(lastDisplaced.css('filter'))) {
  793. displacement -= lastDisplaced[0].filters.item('DXImageTransform.Microsoft.Shadow').strength;
  794. displacement = Math.max(0, displacement);
  795. }
  796. }
  797. return displacement;
  798. };
  799. /**
  800. * Makes elements outside the overlay unreachable via the tab key.
  801. *
  802. * @param context
  803. * The part of the DOM that should have its tabindexes changed. Defaults to
  804. * the entire page.
  805. */
  806. Drupal.overlay.makeDocumentUntabbable = function (context) {
  807. // Manipulating tabindexes for the entire document is unacceptably slow in IE6
  808. // and IE7, so in those browsers, the underlying page will still be reachable
  809. // via the tab key. However, we still make the links within the Disable
  810. // message unreachable, because the same message also exists within the
  811. // child document. The duplicate copy in the underlying document is only for
  812. // assisting screen-reader users navigating the document with reading commands
  813. // that follow markup order rather than tab order.
  814. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
  815. $('#overlay-disable-message a', context).attr('tabindex', -1);
  816. return;
  817. }
  818. context = context || document.body;
  819. var $overlay, $tabbable, $hasTabindex;
  820. // Determine which elements on the page already have a tabindex.
  821. $hasTabindex = $('[tabindex] :not(.overlay-element)', context);
  822. // Record the tabindex for each element, so we can restore it later.
  823. $hasTabindex.each(Drupal.overlay._recordTabindex);
  824. // Add the tabbable elements from the current context to any that we might
  825. // have previously recorded.
  826. Drupal.overlay._hasTabindex = $hasTabindex.add(Drupal.overlay._hasTabindex);
  827. // Set tabindex to -1 on everything outside the overlay and toolbars, so that
  828. // the underlying page is unreachable.
  829. // By default, browsers make a, area, button, input, object, select, textarea,
  830. // and iframe elements reachable via the tab key.
  831. $tabbable = $('a, area, button, input, object, select, textarea, iframe');
  832. // If another element (like a div) has a tabindex, it's also tabbable.
  833. $tabbable = $tabbable.add($hasTabindex);
  834. // Leave links inside the overlay and toolbars alone.
  835. $overlay = $('.overlay-element, #overlay-container, .overlay-displace-top, .overlay-displace-bottom').find('*');
  836. $tabbable = $tabbable.not($overlay);
  837. // We now have a list of everything in the underlying document that could
  838. // possibly be reachable via the tab key. Make it all unreachable.
  839. $tabbable.attr('tabindex', -1);
  840. };
  841. /**
  842. * Restores the original tabindex value of a group of elements.
  843. *
  844. * @param context
  845. * The part of the DOM that should have its tabindexes restored. Defaults to
  846. * the entire page.
  847. */
  848. Drupal.overlay.makeDocumentTabbable = function (context) {
  849. // Manipulating tabindexes is unacceptably slow in IE6 and IE7. In those
  850. // browsers, the underlying page was never made unreachable via tab, so
  851. // there is no work to be done here.
  852. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
  853. return;
  854. }
  855. var $needsTabindex;
  856. context = context || document.body;
  857. // Make the underlying document tabbable again by removing all existing
  858. // tabindex attributes.
  859. var $tabindex = $('[tabindex]', context);
  860. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
  861. // removeAttr('tabindex') is broken in IE6-7, but the DOM function
  862. // removeAttribute works.
  863. var i;
  864. var length = $tabindex.length;
  865. for (i = 0; i < length; i++) {
  866. $tabindex[i].removeAttribute('tabIndex');
  867. }
  868. }
  869. else {
  870. $tabindex.removeAttr('tabindex');
  871. }
  872. // Restore the tabindex attributes that existed before the overlay was opened.
  873. $needsTabindex = $(Drupal.overlay._hasTabindex, context);
  874. $needsTabindex.each(Drupal.overlay._restoreTabindex);
  875. Drupal.overlay._hasTabindex = Drupal.overlay._hasTabindex.not($needsTabindex);
  876. };
  877. /**
  878. * Record the tabindex for an element, using $.data.
  879. *
  880. * Meant to be used as a jQuery.fn.each callback.
  881. */
  882. Drupal.overlay._recordTabindex = function () {
  883. var $element = $(this);
  884. var tabindex = $(this).attr('tabindex');
  885. $element.data('drupalOverlayOriginalTabIndex', tabindex);
  886. };
  887. /**
  888. * Restore an element's original tabindex.
  889. *
  890. * Meant to be used as a jQuery.fn.each callback.
  891. */
  892. Drupal.overlay._restoreTabindex = function () {
  893. var $element = $(this);
  894. var tabindex = $element.data('drupalOverlayOriginalTabIndex');
  895. $element.attr('tabindex', tabindex);
  896. };
  897. /**
  898. * Theme function to create the overlay iframe element.
  899. */
  900. Drupal.theme.prototype.overlayContainer = function () {
  901. return '<div id="overlay-container"><div class="overlay-modal-background"></div></div>';
  902. };
  903. /**
  904. * Theme function to create an overlay iframe element.
  905. */
  906. Drupal.theme.prototype.overlayElement = function (url) {
  907. return '<iframe class="overlay-element" frameborder="0" scrolling="auto" allowtransparency="true"></iframe>';
  908. };
  909. })(jQuery);