overlay-parent.js 36 KB

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