overlay-parent.js 38 KB

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