overlay-parent.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. * Constructs an internal URL (relative to this site) from the provided path.
  342. *
  343. * For example, if the provided path is 'admin' and the site is installed at
  344. * http://example.com/drupal, this function will return '/drupal/admin'.
  345. *
  346. * @param path
  347. * The internal path, without any leading slash.
  348. *
  349. * @return
  350. * The internal URL derived from the provided path, or null if a valid
  351. * internal path cannot be constructed (for example, if an attempt to create
  352. * an external link is detected).
  353. */
  354. Drupal.overlay.getInternalUrl = function (path) {
  355. var url = Drupal.settings.basePath + path;
  356. if (!this.isExternalLink(url)) {
  357. return url;
  358. }
  359. };
  360. /**
  361. * Event handler: resizes overlay according to the size of the parent window.
  362. *
  363. * @param event
  364. * Event being triggered, with the following restrictions:
  365. * - event.type: any
  366. * - event.currentTarget: any
  367. */
  368. Drupal.overlay.eventhandlerOuterResize = function (event) {
  369. // Proceed only if the overlay still exists.
  370. if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
  371. return;
  372. }
  373. // IE6 uses position:absolute instead of position:fixed.
  374. if (typeof document.body.style.maxHeight != 'string') {
  375. this.activeFrame.height($(window).height());
  376. }
  377. // Allow other scripts to respond to this event.
  378. $(document).trigger('drupalOverlayResize');
  379. };
  380. /**
  381. * Event handler: resizes displaced elements so they won't overlap the scrollbar
  382. * of overlay's iframe.
  383. *
  384. * @param event
  385. * Event being triggered, with the following restrictions:
  386. * - event.type: any
  387. * - event.currentTarget: any
  388. */
  389. Drupal.overlay.eventhandlerAlterDisplacedElements = function (event) {
  390. // Proceed only if the overlay still exists.
  391. if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
  392. return;
  393. }
  394. $(this.iframeWindow.document.body).css({
  395. marginTop: Drupal.overlay.getDisplacement('top'),
  396. marginBottom: Drupal.overlay.getDisplacement('bottom')
  397. })
  398. // IE7 isn't reflowing the document immediately.
  399. // @todo This might be fixed in a cleaner way.
  400. .addClass('overlay-trigger-reflow').removeClass('overlay-trigger-reflow');
  401. var documentHeight = this.iframeWindow.document.body.clientHeight;
  402. var documentWidth = this.iframeWindow.document.body.clientWidth;
  403. // IE6 doesn't support maxWidth, use width instead.
  404. var maxWidthName = (typeof document.body.style.maxWidth == 'string') ? 'maxWidth' : 'width';
  405. if (Drupal.overlay.leftSidedScrollbarOffset === undefined && $(document.documentElement).attr('dir') === 'rtl') {
  406. // We can't use element.clientLeft to detect whether scrollbars are placed
  407. // on the left side of the element when direction is set to "rtl" as most
  408. // browsers dont't support it correctly.
  409. // http://www.gtalbot.org/BugzillaSection/DocumentAllDHTMLproperties.html
  410. // There seems to be absolutely no way to detect whether the scrollbar
  411. // is on the left side in Opera; always expect scrollbar to be on the left.
  412. if ($.browser.opera) {
  413. Drupal.overlay.leftSidedScrollbarOffset = document.documentElement.clientWidth - this.iframeWindow.document.documentElement.clientWidth + this.iframeWindow.document.documentElement.clientLeft;
  414. }
  415. else if (this.iframeWindow.document.documentElement.clientLeft) {
  416. Drupal.overlay.leftSidedScrollbarOffset = this.iframeWindow.document.documentElement.clientLeft;
  417. }
  418. else {
  419. var el1 = $('<div style="direction: rtl; overflow: scroll;"></div>').appendTo(document.body);
  420. var el2 = $('<div></div>').appendTo(el1);
  421. Drupal.overlay.leftSidedScrollbarOffset = parseInt(el2[0].offsetLeft - el1[0].offsetLeft);
  422. el1.remove();
  423. }
  424. }
  425. // Consider any element that should be visible above the overlay (such as
  426. // a toolbar).
  427. $('.overlay-displace-top, .overlay-displace-bottom').each(function () {
  428. var data = $(this).data();
  429. var maxWidth = documentWidth;
  430. // In IE, Shadow filter makes element to overlap the scrollbar with 1px.
  431. if (this.filters && this.filters.length && this.filters.item('DXImageTransform.Microsoft.Shadow')) {
  432. maxWidth -= 1;
  433. }
  434. if (Drupal.overlay.leftSidedScrollbarOffset) {
  435. $(this).css('left', Drupal.overlay.leftSidedScrollbarOffset);
  436. }
  437. // Prevent displaced elements overlapping window's scrollbar.
  438. var currentMaxWidth = parseInt($(this).css(maxWidthName));
  439. if ((data.drupalOverlay && data.drupalOverlay.maxWidth) || isNaN(currentMaxWidth) || currentMaxWidth > maxWidth || currentMaxWidth <= 0) {
  440. $(this).css(maxWidthName, maxWidth);
  441. (data.drupalOverlay = data.drupalOverlay || {}).maxWidth = true;
  442. }
  443. // Use a more rigorous approach if the displaced element still overlaps
  444. // window's scrollbar; clip the element on the right.
  445. var offset = $(this).offset();
  446. var offsetRight = offset.left + $(this).outerWidth();
  447. if ((data.drupalOverlay && data.drupalOverlay.clip) || offsetRight > maxWidth) {
  448. if (Drupal.overlay.leftSidedScrollbarOffset) {
  449. $(this).css('clip', 'rect(auto, auto, ' + (documentHeight - offset.top) + 'px, ' + (Drupal.overlay.leftSidedScrollbarOffset + 2) + 'px)');
  450. }
  451. else {
  452. $(this).css('clip', 'rect(auto, ' + (maxWidth - offset.left) + 'px, ' + (documentHeight - offset.top) + 'px, auto)');
  453. }
  454. (data.drupalOverlay = data.drupalOverlay || {}).clip = true;
  455. }
  456. });
  457. };
  458. /**
  459. * Event handler: restores size of displaced elements as they were before
  460. * overlay was opened.
  461. *
  462. * @param event
  463. * Event being triggered, with the following restrictions:
  464. * - event.type: any
  465. * - event.currentTarget: any
  466. */
  467. Drupal.overlay.eventhandlerRestoreDisplacedElements = function (event) {
  468. var $displacedElements = $('.overlay-displace-top, .overlay-displace-bottom');
  469. try {
  470. $displacedElements.css({ maxWidth: '', clip: '' });
  471. }
  472. // IE bug that doesn't allow unsetting style.clip (http://dev.jquery.com/ticket/6512).
  473. catch (err) {
  474. $displacedElements.attr('style', function (index, attr) {
  475. return attr.replace(/clip\s*:\s*rect\([^)]+\);?/i, '');
  476. });
  477. }
  478. };
  479. /**
  480. * Event handler: overrides href of administrative links to be opened in
  481. * the overlay.
  482. *
  483. * This click event handler should be bound to any document (for example the
  484. * overlay iframe) of which you want links to open in the overlay.
  485. *
  486. * @param event
  487. * Event being triggered, with the following restrictions:
  488. * - event.type: click, mouseup
  489. * - event.currentTarget: document
  490. *
  491. * @see Drupal.overlayChild.behaviors.addClickHandler
  492. */
  493. Drupal.overlay.eventhandlerOverrideLink = function (event) {
  494. // In some browsers the click event isn't fired for right-clicks. Use the
  495. // mouseup event for right-clicks and the click event for everything else.
  496. if ((event.type == 'click' && event.button == 2) || (event.type == 'mouseup' && event.button != 2)) {
  497. return;
  498. }
  499. var $target = $(event.target);
  500. // Only continue if clicked target (or one of its parents) is a link.
  501. if (!$target.is('a')) {
  502. $target = $target.closest('a');
  503. if (!$target.length) {
  504. return;
  505. }
  506. }
  507. // Never open links in the overlay that contain the overlay-exclude class.
  508. if ($target.hasClass('overlay-exclude')) {
  509. return;
  510. }
  511. // Close the overlay when the link contains the overlay-close class.
  512. if ($target.hasClass('overlay-close')) {
  513. // Clearing the overlay URL fragment will close the overlay.
  514. $.bbq.removeState('overlay');
  515. return;
  516. }
  517. var target = $target[0];
  518. var href = target.href;
  519. // Only handle links that have an href attribute and use the HTTP(S) protocol.
  520. if (href != undefined && href != '' && target.protocol.match(/^https?\:/)) {
  521. var anchor = href.replace(target.ownerDocument.location.href, '');
  522. // Skip anchor links.
  523. if (anchor.length == 0 || anchor.charAt(0) == '#') {
  524. return;
  525. }
  526. // Open admin links in the overlay.
  527. else if (this.isAdminLink(href)) {
  528. // If the link contains the overlay-restore class and the overlay-context
  529. // state is set, also update the parent window's location.
  530. var parentLocation = ($target.hasClass('overlay-restore') && typeof $.bbq.getState('overlay-context') == 'string')
  531. ? this.getInternalUrl($.bbq.getState('overlay-context'))
  532. : null;
  533. href = this.fragmentizeLink($target.get(0), parentLocation);
  534. // Only override default behavior when left-clicking and user is not
  535. // pressing the ALT, CTRL, META (Command key on the Macintosh keyboard)
  536. // or SHIFT key.
  537. if (event.button == 0 && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
  538. // Redirect to a fragmentized href. This will trigger a hashchange event.
  539. this.redirect(href);
  540. // Prevent default action and further propagation of the event.
  541. return false;
  542. }
  543. // Otherwise alter clicked link's href. This is being picked up by
  544. // the default action handler.
  545. else {
  546. $target
  547. // Restore link's href attribute on blur or next click.
  548. .one('blur mousedown', { target: target, href: target.href }, function (event) { $(event.data.target).attr('href', event.data.href); })
  549. .attr('href', href);
  550. }
  551. }
  552. // Non-admin links should close the overlay and open in the main window,
  553. // which is the default action for a link. We only need to handle them
  554. // if the overlay is open and the clicked link is inside the overlay iframe.
  555. else if (this.isOpen && target.ownerDocument === this.iframeWindow.document) {
  556. // Open external links in the immediate parent of the frame, unless the
  557. // link already has a different target.
  558. if (target.hostname != window.location.hostname) {
  559. if (!$target.attr('target')) {
  560. $target.attr('target', '_parent');
  561. }
  562. }
  563. else {
  564. // Add the overlay-context state to the link, so "overlay-restore" links
  565. // can restore the context.
  566. if ($target[0].hash) {
  567. // Leave links with an existing fragment alone. Adding an extra
  568. // parameter to a link like "node/1#section-1" breaks the link.
  569. }
  570. else {
  571. // For links with no existing fragment, add the overlay context.
  572. $target.attr('href', $.param.fragment(href, { 'overlay-context': this.getPath(window.location) + window.location.search }));
  573. }
  574. // When the link has a destination query parameter and that destination
  575. // is an admin link we need to fragmentize it. This will make it reopen
  576. // in the overlay.
  577. var params = $.deparam.querystring(href);
  578. if (params.destination && this.isAdminLink(params.destination)) {
  579. var fragmentizedDestination = $.param.fragment(this.getPath(window.location), { overlay: params.destination });
  580. $target.attr('href', $.param.querystring(href, { destination: fragmentizedDestination }));
  581. }
  582. // Make the link open in the immediate parent of the frame, unless the
  583. // link already has a different target.
  584. if (!$target.attr('target')) {
  585. $target.attr('target', '_parent');
  586. }
  587. }
  588. }
  589. }
  590. };
  591. /**
  592. * Event handler: opens or closes the overlay based on the current URL fragment.
  593. *
  594. * @param event
  595. * Event being triggered, with the following restrictions:
  596. * - event.type: hashchange
  597. * - event.currentTarget: document
  598. */
  599. Drupal.overlay.eventhandlerOperateByURLFragment = function (event) {
  600. // If we changed the hash to reflect an internal redirect in the overlay,
  601. // its location has already been changed, so don't do anything.
  602. if ($.data(window.location, window.location.href) === 'redirect') {
  603. $.data(window.location, window.location.href, null);
  604. return;
  605. }
  606. // Get the overlay URL from the current URL fragment.
  607. var internalUrl = null;
  608. var state = $.bbq.getState('overlay');
  609. if (state) {
  610. internalUrl = this.getInternalUrl(state);
  611. }
  612. if (internalUrl) {
  613. // Append render variable, so the server side can choose the right
  614. // rendering and add child frame code to the page if needed.
  615. var url = $.param.querystring(internalUrl, { render: 'overlay' });
  616. this.open(url);
  617. this.resetActiveClass(this.getPath(Drupal.settings.basePath + state));
  618. }
  619. // If there is no overlay URL in the fragment and the overlay is (still)
  620. // open, close the overlay.
  621. else if (this.isOpen && !this.isClosing) {
  622. this.close();
  623. this.resetActiveClass(this.getPath(window.location));
  624. }
  625. };
  626. /**
  627. * Event handler: makes sure the internal overlay URL is reflected in the parent
  628. * URL fragment.
  629. *
  630. * Normally the parent URL fragment determines the overlay location. However, if
  631. * the overlay redirects internally, the parent doesn't get informed, and the
  632. * parent URL fragment will be out of date. This is a sanity check to make
  633. * sure we're in the right place.
  634. *
  635. * The parent URL fragment is also not updated automatically when overlay's
  636. * open, close or load functions are used directly (instead of through
  637. * eventhandlerOperateByURLFragment).
  638. *
  639. * @param event
  640. * Event being triggered, with the following restrictions:
  641. * - event.type: drupalOverlayReady, drupalOverlayClose
  642. * - event.currentTarget: document
  643. */
  644. Drupal.overlay.eventhandlerSyncURLFragment = function (event) {
  645. if (this.isOpen) {
  646. var expected = $.bbq.getState('overlay');
  647. // This is just a sanity check, so we're comparing paths, not query strings.
  648. if (this.getPath(Drupal.settings.basePath + expected) != this.getPath(this.iframeWindow.document.location)) {
  649. // There may have been a redirect inside the child overlay window that the
  650. // parent wasn't aware of. Update the parent URL fragment appropriately.
  651. var newLocation = Drupal.overlay.fragmentizeLink(this.iframeWindow.document.location);
  652. // Set a 'redirect' flag on the new location so the hashchange event handler
  653. // knows not to change the overlay's content.
  654. $.data(window.location, newLocation, 'redirect');
  655. // Use location.replace() so we don't create an extra history entry.
  656. window.location.replace(newLocation);
  657. }
  658. }
  659. else {
  660. $.bbq.removeState('overlay');
  661. }
  662. };
  663. /**
  664. * Event handler: if the child window suggested that the parent refresh on
  665. * close, force a page refresh.
  666. *
  667. * @param event
  668. * Event being triggered, with the following restrictions:
  669. * - event.type: drupalOverlayClose
  670. * - event.currentTarget: document
  671. */
  672. Drupal.overlay.eventhandlerRefreshPage = function (event) {
  673. if (Drupal.overlay.refreshPage) {
  674. window.location.reload(true);
  675. }
  676. };
  677. /**
  678. * Event handler: dispatches events to the overlay document.
  679. *
  680. * @param event
  681. * Event being triggered, with the following restrictions:
  682. * - event.type: any
  683. * - event.currentTarget: any
  684. */
  685. Drupal.overlay.eventhandlerDispatchEvent = function (event) {
  686. if (this.iframeWindow && this.iframeWindow.document) {
  687. this.iframeWindow.jQuery(this.iframeWindow.document).trigger(event);
  688. }
  689. };
  690. /**
  691. * Make a regular admin link into a URL that will trigger the overlay to open.
  692. *
  693. * @param link
  694. * A JavaScript Link object (i.e. an <a> element).
  695. * @param parentLocation
  696. * (optional) URL to override the parent window's location with.
  697. *
  698. * @return
  699. * A URL that will trigger the overlay (in the form
  700. * /node/1#overlay=admin/config).
  701. */
  702. Drupal.overlay.fragmentizeLink = function (link, parentLocation) {
  703. // Don't operate on links that are already overlay-ready.
  704. var params = $.deparam.fragment(link.href);
  705. if (params.overlay) {
  706. return link.href;
  707. }
  708. // Determine the link's original destination. Set ignorePathFromQueryString to
  709. // true to prevent transforming this link into a clean URL while clean URLs
  710. // may be disabled.
  711. var path = this.getPath(link, true);
  712. // Preserve existing query and fragment parameters in the URL, except for
  713. // "render=overlay" which is re-added in Drupal.overlay.eventhandlerOperateByURLFragment.
  714. var destination = path + link.search.replace(/&?render=overlay/, '').replace(/\?$/, '') + link.hash;
  715. // Assemble and return the overlay-ready link.
  716. return $.param.fragment(parentLocation || window.location.href, { overlay: destination });
  717. };
  718. /**
  719. * Refresh any regions of the page that are displayed outside the overlay.
  720. *
  721. * @param data
  722. * An array of objects with information on the page regions to be refreshed.
  723. * For each object, the key is a CSS class identifying the region to be
  724. * refreshed, and the value represents the section of the Drupal $page array
  725. * corresponding to this region.
  726. */
  727. Drupal.overlay.refreshRegions = function (data) {
  728. $.each(data, function () {
  729. var region_info = this;
  730. $.each(region_info, function (regionClass) {
  731. var regionName = region_info[regionClass];
  732. var regionSelector = '.' + regionClass;
  733. // Allow special behaviors to detach.
  734. Drupal.detachBehaviors($(regionSelector));
  735. $.get(Drupal.settings.basePath + Drupal.settings.overlay.ajaxCallback + '/' + regionName, function (newElement) {
  736. $(regionSelector).replaceWith($(newElement));
  737. Drupal.attachBehaviors($(regionSelector), Drupal.settings);
  738. });
  739. });
  740. });
  741. };
  742. /**
  743. * Reset the active class on links in displaced elements according to
  744. * given path.
  745. *
  746. * @param activePath
  747. * Path to match links against.
  748. */
  749. Drupal.overlay.resetActiveClass = function(activePath) {
  750. var self = this;
  751. var windowDomain = window.location.protocol + window.location.hostname;
  752. $('.overlay-displace-top, .overlay-displace-bottom')
  753. .find('a[href]')
  754. // Remove active class from all links in displaced elements.
  755. .removeClass('active')
  756. // Add active class to links that match activePath.
  757. .each(function () {
  758. var linkDomain = this.protocol + this.hostname;
  759. var linkPath = self.getPath(this);
  760. // A link matches if it is part of the active trail of activePath, except
  761. // for frontpage links.
  762. if (linkDomain == windowDomain && (activePath + '/').indexOf(linkPath + '/') === 0 && (linkPath !== '' || activePath === '')) {
  763. $(this).addClass('active');
  764. }
  765. });
  766. };
  767. /**
  768. * Helper function to get the (corrected) Drupal path of a link.
  769. *
  770. * @param link
  771. * Link object or string to get the Drupal path from.
  772. * @param ignorePathFromQueryString
  773. * Boolean whether to ignore path from query string if path appears empty.
  774. *
  775. * @return
  776. * The Drupal path.
  777. */
  778. Drupal.overlay.getPath = function (link, ignorePathFromQueryString) {
  779. if (typeof link == 'string') {
  780. // Create a native Link object, so we can use its object methods.
  781. link = $(link.link(link)).get(0);
  782. }
  783. var path = link.pathname;
  784. // Ensure a leading slash on the path, omitted in some browsers.
  785. if (path.charAt(0) != '/') {
  786. path = '/' + path;
  787. }
  788. path = path.replace(new RegExp(Drupal.settings.basePath + '(?:index.php)?'), '');
  789. if (path == '' && !ignorePathFromQueryString) {
  790. // If the path appears empty, it might mean the path is represented in the
  791. // query string (clean URLs are not used).
  792. var match = new RegExp('([?&])q=(.+)([&#]|$)').exec(link.search);
  793. if (match && match.length == 4) {
  794. path = match[2];
  795. }
  796. }
  797. return path;
  798. };
  799. /**
  800. * Get the total displacement of given region.
  801. *
  802. * @param region
  803. * Region name. Either "top" or "bottom".
  804. *
  805. * @return
  806. * The total displacement of given region in pixels.
  807. */
  808. Drupal.overlay.getDisplacement = function (region) {
  809. var displacement = 0;
  810. var lastDisplaced = $('.overlay-displace-' + region + ':last');
  811. if (lastDisplaced.length) {
  812. displacement = lastDisplaced.offset().top + lastDisplaced.outerHeight();
  813. // In modern browsers (including IE9), when box-shadow is defined, use the
  814. // normal height.
  815. var cssBoxShadowValue = lastDisplaced.css('box-shadow');
  816. var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none');
  817. // In IE8 and below, we use the shadow filter to apply box-shadow styles to
  818. // the toolbar. It adds some extra height that we need to remove.
  819. if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test(lastDisplaced.css('filter'))) {
  820. displacement -= lastDisplaced[0].filters.item('DXImageTransform.Microsoft.Shadow').strength;
  821. displacement = Math.max(0, displacement);
  822. }
  823. }
  824. return displacement;
  825. };
  826. /**
  827. * Makes elements outside the overlay unreachable via the tab key.
  828. *
  829. * @param context
  830. * The part of the DOM that should have its tabindexes changed. Defaults to
  831. * the entire page.
  832. */
  833. Drupal.overlay.makeDocumentUntabbable = function (context) {
  834. // Manipulating tabindexes for the entire document is unacceptably slow in IE6
  835. // and IE7, so in those browsers, the underlying page will still be reachable
  836. // via the tab key. However, we still make the links within the Disable
  837. // message unreachable, because the same message also exists within the
  838. // child document. The duplicate copy in the underlying document is only for
  839. // assisting screen-reader users navigating the document with reading commands
  840. // that follow markup order rather than tab order.
  841. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
  842. $('#overlay-disable-message a', context).attr('tabindex', -1);
  843. return;
  844. }
  845. context = context || document.body;
  846. var $overlay, $tabbable, $hasTabindex;
  847. // Determine which elements on the page already have a tabindex.
  848. $hasTabindex = $('[tabindex] :not(.overlay-element)', context);
  849. // Record the tabindex for each element, so we can restore it later.
  850. $hasTabindex.each(Drupal.overlay._recordTabindex);
  851. // Add the tabbable elements from the current context to any that we might
  852. // have previously recorded.
  853. Drupal.overlay._hasTabindex = $hasTabindex.add(Drupal.overlay._hasTabindex);
  854. // Set tabindex to -1 on everything outside the overlay and toolbars, so that
  855. // the underlying page is unreachable.
  856. // By default, browsers make a, area, button, input, object, select, textarea,
  857. // and iframe elements reachable via the tab key.
  858. $tabbable = $('a, area, button, input, object, select, textarea, iframe');
  859. // If another element (like a div) has a tabindex, it's also tabbable.
  860. $tabbable = $tabbable.add($hasTabindex);
  861. // Leave links inside the overlay and toolbars alone.
  862. $overlay = $('.overlay-element, #overlay-container, .overlay-displace-top, .overlay-displace-bottom').find('*');
  863. $tabbable = $tabbable.not($overlay);
  864. // We now have a list of everything in the underlying document that could
  865. // possibly be reachable via the tab key. Make it all unreachable.
  866. $tabbable.attr('tabindex', -1);
  867. };
  868. /**
  869. * Restores the original tabindex value of a group of elements.
  870. *
  871. * @param context
  872. * The part of the DOM that should have its tabindexes restored. Defaults to
  873. * the entire page.
  874. */
  875. Drupal.overlay.makeDocumentTabbable = function (context) {
  876. // Manipulating tabindexes is unacceptably slow in IE6 and IE7. In those
  877. // browsers, the underlying page was never made unreachable via tab, so
  878. // there is no work to be done here.
  879. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
  880. return;
  881. }
  882. var $needsTabindex;
  883. context = context || document.body;
  884. // Make the underlying document tabbable again by removing all existing
  885. // tabindex attributes.
  886. var $tabindex = $('[tabindex]', context);
  887. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
  888. // removeAttr('tabindex') is broken in IE6-7, but the DOM function
  889. // removeAttribute works.
  890. var i;
  891. var length = $tabindex.length;
  892. for (i = 0; i < length; i++) {
  893. $tabindex[i].removeAttribute('tabIndex');
  894. }
  895. }
  896. else {
  897. $tabindex.removeAttr('tabindex');
  898. }
  899. // Restore the tabindex attributes that existed before the overlay was opened.
  900. $needsTabindex = $(Drupal.overlay._hasTabindex, context);
  901. $needsTabindex.each(Drupal.overlay._restoreTabindex);
  902. Drupal.overlay._hasTabindex = Drupal.overlay._hasTabindex.not($needsTabindex);
  903. };
  904. /**
  905. * Record the tabindex for an element, using $.data.
  906. *
  907. * Meant to be used as a jQuery.fn.each callback.
  908. */
  909. Drupal.overlay._recordTabindex = function () {
  910. var $element = $(this);
  911. var tabindex = $(this).attr('tabindex');
  912. $element.data('drupalOverlayOriginalTabIndex', tabindex);
  913. };
  914. /**
  915. * Restore an element's original tabindex.
  916. *
  917. * Meant to be used as a jQuery.fn.each callback.
  918. */
  919. Drupal.overlay._restoreTabindex = function () {
  920. var $element = $(this);
  921. var tabindex = $element.data('drupalOverlayOriginalTabIndex');
  922. $element.attr('tabindex', tabindex);
  923. };
  924. /**
  925. * Theme function to create the overlay iframe element.
  926. */
  927. Drupal.theme.prototype.overlayContainer = function () {
  928. return '<div id="overlay-container"><div class="overlay-modal-background"></div></div>';
  929. };
  930. /**
  931. * Theme function to create an overlay iframe element.
  932. */
  933. Drupal.theme.prototype.overlayElement = function (url) {
  934. return '<iframe class="overlay-element" frameborder="0" scrolling="auto" allowtransparency="true"></iframe>';
  935. };
  936. })(jQuery);