From 29c7ccab715136559f9a75ee7911f63003c09c06 Mon Sep 17 00:00:00 2001 From: BE-Webdesign Date: Fri, 8 Sep 2017 16:16:19 -0400 Subject: [PATCH] Making metaboxes interact with redux. Making metaboxes properly interact with redux. Observer state changes in metaboxes to mark state as dirty etc. Only save a metabox if it has changed. --- assets/css/metabox.css | 4 + assets/js/iframeResizer.contentWindow.js | 1102 ------------------ assets/js/iframeResizer.contentWindow.min.js | 10 - assets/js/iframeResizer.js | 1053 ----------------- assets/js/iframeResizer.min.js | 9 - assets/js/metabox.js | 50 +- editor/actions.js | 38 +- editor/effects.js | 16 +- editor/index.js | 3 + editor/layout/index.js | 4 +- editor/metaboxes/index.js | 212 ++++ editor/metaboxes/main.js | 61 - editor/metaboxes/sidebar.js | 60 - editor/reducer.js | 21 +- editor/selectors.js | 49 +- editor/sidebar/index.js | 4 +- editor/test/actions.js | 39 +- editor/test/reducer.js | 61 +- editor/test/selectors.js | 196 +++- lib/client-assets.php | 17 - lib/metabox-partial-page.php | 9 +- 21 files changed, 593 insertions(+), 2425 deletions(-) delete mode 100644 assets/js/iframeResizer.contentWindow.js delete mode 100644 assets/js/iframeResizer.contentWindow.min.js delete mode 100644 assets/js/iframeResizer.js delete mode 100644 assets/js/iframeResizer.min.js create mode 100644 editor/metaboxes/index.js delete mode 100644 editor/metaboxes/main.js delete mode 100644 editor/metaboxes/sidebar.js diff --git a/assets/css/metabox.css b/assets/css/metabox.css index 615c3365747b0e..d2eea69408a73a 100644 --- a/assets/css/metabox.css +++ b/assets/css/metabox.css @@ -145,3 +145,7 @@ textarea { .acf_postbox .inside { padding: 15px !important; } + +#post { + margin: 0; +} diff --git a/assets/js/iframeResizer.contentWindow.js b/assets/js/iframeResizer.contentWindow.js deleted file mode 100644 index b87a28fbb9021c..00000000000000 --- a/assets/js/iframeResizer.contentWindow.js +++ /dev/null @@ -1,1102 +0,0 @@ -/* - * File: iframeResizer.contentWindow.js - * Desc: Include this file in any page being loaded into an iframe - * to force the iframe to resize to the content size. - * Requires: iframeResizer.js on host page. - * Doc: https://github.com/davidjbradshaw/iframe-resizer - * Author: David J. Bradshaw - dave@bradshaw.net - * Contributor: Jure Mav - jure.mav@gmail.com - * Contributor: Ian Caunce - ian@hallnet.co.uk - */ - -( function( undefined ) { - 'use strict'; - - if ( typeof window === 'undefined' ) { - return; - } // don't run for server side render - - let - autoResize = true, - base = 10, - bodyBackground = '', - bodyMargin = 0, - bodyMarginStr = '', - bodyObserver = null, - bodyPadding = '', - calculateWidth = false, - doubleEventList = { resize: 1, click: 1 }, - eventCancelTimer = 128, - firstRun = true, - height = 1, - heightCalcModeDefault = 'bodyOffset', - heightCalcMode = heightCalcModeDefault, - initLock = true, - initMsg = '', - inPageLinks = {}, - interval = 32, - intervalTimer = null, - logging = false, - msgID = '[iFrameSizer]', //Must match host page msg ID - msgIdLen = msgID.length, - myID = '', - observer = null, - resetRequiredMethods = { max: 1, min: 1, bodyScroll: 1, documentElementScroll: 1 }, - resizeFrom = 'child', - sendPermit = true, - target = window.parent, - targetOriginDefault = '*', - tolerance = 0, - triggerLocked = false, - triggerLockedTimer = null, - throttledTimer = 16, - width = 1, - widthCalcModeDefault = 'scroll', - widthCalcMode = widthCalcModeDefault, - win = window, - messageCallback = function() { - warn( 'MessageCallback function not defined' ); - }, - readyCallback = function() {}, - pageInfoCallback = function() {}, - customCalcMethods = { - height: function() { - warn( 'Custom height calculation function not defined' ); - return document.documentElement.offsetHeight; - }, - width: function() { - warn( 'Custom width calculation function not defined' ); - return document.body.scrollWidth; - }, - }, - eventHandlersByName = {}; - - function addEventListener( el, evt, func ) { - /* istanbul ignore else */ // Not testable in phantonJS - if ( 'addEventListener' in window ) { - el.addEventListener( evt, func, false ); - } else if ( 'attachEvent' in window ) { //IE - el.attachEvent( 'on' + evt, func ); - } - } - - function removeEventListener( el, evt, func ) { - /* istanbul ignore else */ // Not testable in phantonJS - if ( 'removeEventListener' in window ) { - el.removeEventListener( evt, func, false ); - } else if ( 'detachEvent' in window ) { //IE - el.detachEvent( 'on' + evt, func ); - } - } - - function capitalizeFirstLetter( string ) { - return string.charAt( 0 ).toUpperCase() + string.slice( 1 ); - } - - //Based on underscore.js - function throttle( func ) { - let - context, args, result, - timeout = null, - previous = 0, - later = function() { - previous = getNow(); - timeout = null; - result = func.apply( context, args ); - if ( ! timeout ) { - context = args = null; - } - }; - - return function() { - const now = getNow(); - - if ( ! previous ) { - previous = now; - } - - const remaining = throttledTimer - ( now - previous ); - - context = this; - args = arguments; - - if ( remaining <= 0 || remaining > throttledTimer ) { - if ( timeout ) { - clearTimeout( timeout ); - timeout = null; - } - - previous = now; - result = func.apply( context, args ); - - if ( ! timeout ) { - context = args = null; - } - } else if ( ! timeout ) { - timeout = setTimeout( later, remaining ); - } - - return result; - }; - } - - var getNow = Date.now || function() { - /* istanbul ignore next */ // Not testable in PhantonJS - return new Date().getTime(); - }; - - function formatLogMsg( msg ) { - return msgID + '[' + myID + ']' + ' ' + msg; - } - - function log( msg ) { - if ( logging && ( 'object' === typeof window.console ) ) { - console.log( formatLogMsg( msg ) ); - } - } - - function warn( msg ) { - if ( 'object' === typeof window.console ) { - console.warn( formatLogMsg( msg ) ); - } - } - - function init() { - readDataFromParent(); - log( 'Initialising iFrame (' + location.href + ')' ); - readDataFromPage(); - setMargin(); - setBodyStyle( 'background', bodyBackground ); - setBodyStyle( 'padding', bodyPadding ); - injectClearFixIntoBodyElement(); - checkHeightMode(); - checkWidthMode(); - stopInfiniteResizingOfIFrame(); - setupPublicMethods(); - startEventListeners(); - inPageLinks = setupInPageLinks(); - sendSize( 'init', 'Init message from host page' ); - readyCallback(); - } - - function readDataFromParent() { - function strBool( str ) { - return 'true' === str ? true : false; - } - - const data = initMsg.substr( msgIdLen ).split( ':' ); - - myID = data[ 0 ]; - bodyMargin = ( undefined !== data[ 1 ] ) ? Number( data[ 1 ] ) : bodyMargin; //For V1 compatibility - calculateWidth = ( undefined !== data[ 2 ] ) ? strBool( data[ 2 ] ) : calculateWidth; - logging = ( undefined !== data[ 3 ] ) ? strBool( data[ 3 ] ) : logging; - interval = ( undefined !== data[ 4 ] ) ? Number( data[ 4 ] ) : interval; - autoResize = ( undefined !== data[ 6 ] ) ? strBool( data[ 6 ] ) : autoResize; - bodyMarginStr = data[ 7 ]; - heightCalcMode = ( undefined !== data[ 8 ] ) ? data[ 8 ] : heightCalcMode; - bodyBackground = data[ 9 ]; - bodyPadding = data[ 10 ]; - tolerance = ( undefined !== data[ 11 ] ) ? Number( data[ 11 ] ) : tolerance; - inPageLinks.enable = ( undefined !== data[ 12 ] ) ? strBool( data[ 12 ] ) : false; - resizeFrom = ( undefined !== data[ 13 ] ) ? data[ 13 ] : resizeFrom; - widthCalcMode = ( undefined !== data[ 14 ] ) ? data[ 14 ] : widthCalcMode; - } - - function readDataFromPage() { - function readData() { - const data = window.iFrameResizer; - - log( 'Reading data from page: ' + JSON.stringify( data ) ); - - messageCallback = ( 'messageCallback' in data ) ? data.messageCallback : messageCallback; - readyCallback = ( 'readyCallback' in data ) ? data.readyCallback : readyCallback; - targetOriginDefault = ( 'targetOrigin' in data ) ? data.targetOrigin : targetOriginDefault; - heightCalcMode = ( 'heightCalculationMethod' in data ) ? data.heightCalculationMethod : heightCalcMode; - widthCalcMode = ( 'widthCalculationMethod' in data ) ? data.widthCalculationMethod : widthCalcMode; - } - - function setupCustomCalcMethods( calcMode, calcFunc ) { - if ( 'function' === typeof calcMode ) { - log( 'Setup custom ' + calcFunc + 'CalcMethod' ); - customCalcMethods[ calcFunc ] = calcMode; - calcMode = 'custom'; - } - - return calcMode; - } - - if ( ( 'iFrameResizer' in window ) && ( Object === window.iFrameResizer.constructor ) ) { - readData(); - heightCalcMode = setupCustomCalcMethods( heightCalcMode, 'height' ); - widthCalcMode = setupCustomCalcMethods( widthCalcMode, 'width' ); - } - - log( 'TargetOrigin for parent set to: ' + targetOriginDefault ); - } - - function chkCSS( attr, value ) { - if ( -1 !== value.indexOf( '-' ) ) { - warn( 'Negative CSS value ignored for ' + attr ); - value = ''; - } - return value; - } - - function setBodyStyle( attr, value ) { - if ( ( undefined !== value ) && ( '' !== value ) && ( 'null' !== value ) ) { - document.body.style[ attr ] = value; - log( 'Body ' + attr + ' set to "' + value + '"' ); - } - } - - function setMargin() { - //If called via V1 script, convert bodyMargin from int to str - if ( undefined === bodyMarginStr ) { - bodyMarginStr = bodyMargin + 'px'; - } - - setBodyStyle( 'margin', chkCSS( 'margin', bodyMarginStr ) ); - } - - function stopInfiniteResizingOfIFrame() { - document.documentElement.style.height = ''; - document.body.style.height = ''; - log( 'HTML & body height set to "auto"' ); - } - - function manageTriggerEvent( options ) { - const listener = { - add: function( eventName ) { - function handleEvent() { - sendSize( options.eventName, options.eventType ); - } - - eventHandlersByName[ eventName ] = handleEvent; - - addEventListener( window, eventName, handleEvent ); - }, - remove: function( eventName ) { - const handleEvent = eventHandlersByName[ eventName ]; - delete eventHandlersByName[ eventName ]; - - removeEventListener( window, eventName, handleEvent ); - }, - }; - - if ( options.eventNames && Array.prototype.map ) { - options.eventName = options.eventNames[ 0 ]; - options.eventNames.map( listener[ options.method ] ); - } else { - listener[ options.method ]( options.eventName ); - } - - log( capitalizeFirstLetter( options.method ) + ' event listener: ' + options.eventType ); - } - - function manageEventListeners( method ) { - manageTriggerEvent( { method: method, eventType: 'Animation Start', eventNames: [ 'animationstart', 'webkitAnimationStart' ] } ); - manageTriggerEvent( { method: method, eventType: 'Animation Iteration', eventNames: [ 'animationiteration', 'webkitAnimationIteration' ] } ); - manageTriggerEvent( { method: method, eventType: 'Animation End', eventNames: [ 'animationend', 'webkitAnimationEnd' ] } ); - manageTriggerEvent( { method: method, eventType: 'Input', eventName: 'input' } ); - manageTriggerEvent( { method: method, eventType: 'Mouse Up', eventName: 'mouseup' } ); - manageTriggerEvent( { method: method, eventType: 'Mouse Down', eventName: 'mousedown' } ); - manageTriggerEvent( { method: method, eventType: 'Orientation Change', eventName: 'orientationchange' } ); - manageTriggerEvent( { method: method, eventType: 'Print', eventName: [ 'afterprint', 'beforeprint' ] } ); - manageTriggerEvent( { method: method, eventType: 'Ready State Change', eventName: 'readystatechange' } ); - manageTriggerEvent( { method: method, eventType: 'Touch Start', eventName: 'touchstart' } ); - manageTriggerEvent( { method: method, eventType: 'Touch End', eventName: 'touchend' } ); - manageTriggerEvent( { method: method, eventType: 'Touch Cancel', eventName: 'touchcancel' } ); - manageTriggerEvent( { method: method, eventType: 'Transition Start', eventNames: [ 'transitionstart', 'webkitTransitionStart', 'MSTransitionStart', 'oTransitionStart', 'otransitionstart' ] } ); - manageTriggerEvent( { method: method, eventType: 'Transition Iteration', eventNames: [ 'transitioniteration', 'webkitTransitionIteration', 'MSTransitionIteration', 'oTransitionIteration', 'otransitioniteration' ] } ); - manageTriggerEvent( { method: method, eventType: 'Transition End', eventNames: [ 'transitionend', 'webkitTransitionEnd', 'MSTransitionEnd', 'oTransitionEnd', 'otransitionend' ] } ); - if ( 'child' === resizeFrom ) { - manageTriggerEvent( { method: method, eventType: 'IFrame Resized', eventName: 'resize' } ); - } - } - - function checkCalcMode( calcMode, calcModeDefault, modes, type ) { - if ( calcModeDefault !== calcMode ) { - if ( ! ( calcMode in modes ) ) { - warn( calcMode + ' is not a valid option for ' + type + 'CalculationMethod.' ); - calcMode = calcModeDefault; - } - log( type + ' calculation method set to "' + calcMode + '"' ); - } - - return calcMode; - } - - function checkHeightMode() { - heightCalcMode = checkCalcMode( heightCalcMode, heightCalcModeDefault, getHeight, 'height' ); - } - - function checkWidthMode() { - widthCalcMode = checkCalcMode( widthCalcMode, widthCalcModeDefault, getWidth, 'width' ); - } - - function startEventListeners() { - if ( true === autoResize ) { - manageEventListeners( 'add' ); - setupMutationObserver(); - } else { - log( 'Auto Resize disabled' ); - } - } - - function stopMsgsToParent() { - log( 'Disable outgoing messages' ); - sendPermit = false; - } - - function removeMsgListener() { - log( 'Remove event listener: Message' ); - removeEventListener( window, 'message', receiver ); - } - - function disconnectMutationObserver() { - if ( null !== bodyObserver ) { - /* istanbul ignore next */ // Not testable in PhantonJS - bodyObserver.disconnect(); - } - } - - function stopEventListeners() { - manageEventListeners( 'remove' ); - disconnectMutationObserver(); - clearInterval( intervalTimer ); - } - - function teardown() { - stopMsgsToParent(); - removeMsgListener(); - if ( true === autoResize ) { - stopEventListeners(); - } - } - - function injectClearFixIntoBodyElement() { - const clearFix = document.createElement( 'div' ); - clearFix.style.clear = 'both'; - clearFix.style.display = 'block'; //Guard against this having been globally redefined in CSS. - document.body.appendChild( clearFix ); - } - - function setupInPageLinks() { - function getPagePosition() { - return { - x: ( window.pageXOffset !== undefined ) ? window.pageXOffset : document.documentElement.scrollLeft, - y: ( window.pageYOffset !== undefined ) ? window.pageYOffset : document.documentElement.scrollTop, - }; - } - - function getElementPosition( el ) { - let - elPosition = el.getBoundingClientRect(), - pagePosition = getPagePosition(); - - return { - x: parseInt( elPosition.left, 10 ) + parseInt( pagePosition.x, 10 ), - y: parseInt( elPosition.top, 10 ) + parseInt( pagePosition.y, 10 ), - }; - } - - function findTarget( location ) { - function jumpToTarget( target ) { - const jumpPosition = getElementPosition( target ); - - log( 'Moving to in page link (#' + hash + ') at x: ' + jumpPosition.x + ' y: ' + jumpPosition.y ); - sendMsg( jumpPosition.y, jumpPosition.x, 'scrollToOffset' ); // X&Y reversed at sendMsg uses height/width - } - - var - hash = location.split( '#' )[ 1 ] || location, //Remove # if present - hashData = decodeURIComponent( hash ), - target = document.getElementById( hashData ) || document.getElementsByName( hashData )[ 0 ]; - - if ( undefined !== target ) { - jumpToTarget( target ); - } else { - log( 'In page link (#' + hash + ') not found in iFrame, so sending to parent' ); - sendMsg( 0, 0, 'inPageLink', '#' + hash ); - } - } - - function checkLocationHash() { - if ( '' !== location.hash && '#' !== location.hash ) { - findTarget( location.href ); - } - } - - function bindAnchors() { - function setupLink( el ) { - function linkClicked( e ) { - e.preventDefault(); - - /*jshint validthis:true */ - findTarget( this.getAttribute( 'href' ) ); - } - - if ( '#' !== el.getAttribute( 'href' ) ) { - addEventListener( el, 'click', linkClicked ); - } - } - - Array.prototype.forEach.call( document.querySelectorAll( 'a[href^="#"]' ), setupLink ); - } - - function bindLocationHash() { - addEventListener( window, 'hashchange', checkLocationHash ); - } - - function initCheck() { //check if page loaded with location hash after init resize - setTimeout( checkLocationHash, eventCancelTimer ); - } - - function enableInPageLinks() { - /* istanbul ignore else */ // Not testable in phantonJS - if ( Array.prototype.forEach && document.querySelectorAll ) { - log( 'Setting up location.hash handlers' ); - bindAnchors(); - bindLocationHash(); - initCheck(); - } else { - warn( 'In page linking not fully supported in this browser! (See README.md for IE8 workaround)' ); - } - } - - if ( inPageLinks.enable ) { - enableInPageLinks(); - } else { - log( 'In page linking not enabled' ); - } - - return { - findTarget: findTarget, - }; - } - - function setupPublicMethods() { - log( 'Enable public methods' ); - - win.parentIFrame = { - - autoResize: function autoResizeF( resize ) { - if ( true === resize && false === autoResize ) { - autoResize = true; - startEventListeners(); - //sendSize('autoResize','Auto Resize enabled'); - } else if ( false === resize && true === autoResize ) { - autoResize = false; - stopEventListeners(); - } - - return autoResize; - }, - - close: function closeF() { - sendMsg( 0, 0, 'close' ); - teardown(); - }, - - getId: function getIdF() { - return myID; - }, - - getPageInfo: function getPageInfoF( callback ) { - if ( 'function' === typeof callback ) { - pageInfoCallback = callback; - sendMsg( 0, 0, 'pageInfo' ); - } else { - pageInfoCallback = function() {}; - sendMsg( 0, 0, 'pageInfoStop' ); - } - }, - - moveToAnchor: function moveToAnchorF( hash ) { - inPageLinks.findTarget( hash ); - }, - - reset: function resetF() { - resetIFrame( 'parentIFrame.reset' ); - }, - - scrollTo: function scrollToF( x, y ) { - sendMsg( y, x, 'scrollTo' ); // X&Y reversed at sendMsg uses height/width - }, - - scrollToOffset: function scrollToF( x, y ) { - sendMsg( y, x, 'scrollToOffset' ); // X&Y reversed at sendMsg uses height/width - }, - - sendMessage: function sendMessageF( msg, targetOrigin ) { - sendMsg( 0, 0, 'message', JSON.stringify( msg ), targetOrigin ); - }, - - setHeightCalculationMethod: function setHeightCalculationMethodF( heightCalculationMethod ) { - heightCalcMode = heightCalculationMethod; - checkHeightMode(); - }, - - setWidthCalculationMethod: function setWidthCalculationMethodF( widthCalculationMethod ) { - widthCalcMode = widthCalculationMethod; - checkWidthMode(); - }, - - setTargetOrigin: function setTargetOriginF( targetOrigin ) { - log( 'Set targetOrigin: ' + targetOrigin ); - targetOriginDefault = targetOrigin; - }, - - size: function sizeF( customHeight, customWidth ) { - const valString = '' + ( customHeight ? customHeight : '' ) + ( customWidth ? ',' + customWidth : '' ); - //lockTrigger(); - sendSize( 'size', 'parentIFrame.size(' + valString + ')', customHeight, customWidth ); - }, - }; - } - - function initInterval() { - if ( 0 !== interval ) { - log( 'setInterval: ' + interval + 'ms' ); - intervalTimer = setInterval( function() { - sendSize( 'interval', 'setInterval: ' + interval ); - }, Math.abs( interval ) ); - } - } - - /* istanbul ignore next */ //Not testable in PhantomJS - function setupBodyMutationObserver() { - function addImageLoadListners( mutation ) { - function addImageLoadListener( element ) { - if ( false === element.complete ) { - log( 'Attach listeners to ' + element.src ); - element.addEventListener( 'load', imageLoaded, false ); - element.addEventListener( 'error', imageError, false ); - elements.push( element ); - } - } - - if ( mutation.type === 'attributes' && mutation.attributeName === 'src' ) { - addImageLoadListener( mutation.target ); - } else if ( mutation.type === 'childList' ) { - Array.prototype.forEach.call( - mutation.target.querySelectorAll( 'img' ), - addImageLoadListener - ); - } - } - - function removeFromArray( element ) { - elements.splice( elements.indexOf( element ), 1 ); - } - - function removeImageLoadListener( element ) { - log( 'Remove listeners from ' + element.src ); - element.removeEventListener( 'load', imageLoaded, false ); - element.removeEventListener( 'error', imageError, false ); - removeFromArray( element ); - } - - function imageEventTriggered( event, type, typeDesc ) { - removeImageLoadListener( event.target ); - sendSize( type, typeDesc + ': ' + event.target.src, undefined, undefined ); - } - - function imageLoaded( event ) { - imageEventTriggered( event, 'imageLoad', 'Image loaded' ); - } - - function imageError( event ) { - imageEventTriggered( event, 'imageLoadFailed', 'Image load failed' ); - } - - function mutationObserved( mutations ) { - sendSize( 'mutationObserver', 'mutationObserver: ' + mutations[ 0 ].target + ' ' + mutations[ 0 ].type ); - - //Deal with WebKit asyncing image loading when tags are injected into the page - mutations.forEach( addImageLoadListners ); - } - - function createMutationObserver() { - let - target = document.querySelector( 'body' ), - - config = { - attributes: true, - attributeOldValue: false, - characterData: true, - characterDataOldValue: false, - childList: true, - subtree: true, - }; - - observer = new MutationObserver( mutationObserved ); - - log( 'Create body MutationObserver' ); - observer.observe( target, config ); - - return observer; - } - - var - elements = [], - MutationObserver = window.MutationObserver || window.WebKitMutationObserver, - observer = createMutationObserver(); - - return { - disconnect: function() { - if ( 'disconnect' in observer ) { - log( 'Disconnect body MutationObserver' ); - observer.disconnect(); - elements.forEach( removeImageLoadListener ); - } - }, - }; - } - - function setupMutationObserver() { - const forceIntervalTimer = 0 > interval; - - /* istanbul ignore if */ // Not testable in PhantomJS - if ( window.MutationObserver || window.WebKitMutationObserver ) { - if ( forceIntervalTimer ) { - initInterval(); - } else { - bodyObserver = setupBodyMutationObserver(); - } - } else { - log( 'MutationObserver not supported in this browser!' ); - initInterval(); - } - } - - // document.documentElement.offsetHeight is not reliable, so - // we have to jump through hoops to get a better value. - function getComputedStyle( prop, el ) { - /* istanbul ignore next */ //Not testable in PhantomJS - function convertUnitsToPxForIE8( value ) { - const PIXEL = /^\d+(px)?$/i; - - if ( PIXEL.test( value ) ) { - return parseInt( value, base ); - } - - let - style = el.style.left, - runtimeStyle = el.runtimeStyle.left; - - el.runtimeStyle.left = el.currentStyle.left; - el.style.left = value || 0; - value = el.style.pixelLeft; - el.style.left = style; - el.runtimeStyle.left = runtimeStyle; - - return value; - } - - let retVal = 0; - el = el || document.body; - - /* istanbul ignore else */ // Not testable in phantonJS - if ( ( 'defaultView' in document ) && ( 'getComputedStyle' in document.defaultView ) ) { - retVal = document.defaultView.getComputedStyle( el, null ); - retVal = ( null !== retVal ) ? retVal[ prop ] : 0; - } else {//IE8 - retVal = convertUnitsToPxForIE8( el.currentStyle[ prop ] ); - } - - return parseInt( retVal, base ); - } - - function chkEventThottle( timer ) { - if ( timer > throttledTimer / 2 ) { - throttledTimer = 2 * timer; - log( 'Event throttle increased to ' + throttledTimer + 'ms' ); - } - } - - //Idea from https://github.com/guardian/iframe-messenger - function getMaxElement( side, elements ) { - let - elementsLength = elements.length, - elVal = 0, - maxVal = 0, - Side = capitalizeFirstLetter( side ), - timer = getNow(); - - for ( let i = 0; i < elementsLength; i++ ) { - elVal = elements[ i ].getBoundingClientRect()[ side ] + getComputedStyle( 'margin' + Side, elements[ i ] ); - if ( elVal > maxVal ) { - maxVal = elVal; - } - } - - timer = getNow() - timer; - - log( 'Parsed ' + elementsLength + ' HTML elements' ); - log( 'Element position calculated in ' + timer + 'ms' ); - - chkEventThottle( timer ); - - return maxVal; - } - - function getAllMeasurements( dimention ) { - return [ - dimention.bodyOffset(), - dimention.bodyScroll(), - dimention.documentElementOffset(), - dimention.documentElementScroll(), - ]; - } - - function getTaggedElements( side, tag ) { - function noTaggedElementsFound() { - warn( 'No tagged elements (' + tag + ') found on page' ); - return document.querySelectorAll( 'body *' ); - } - - const elements = document.querySelectorAll( '[' + tag + ']' ); - - if ( 0 === elements.length ) { - noTaggedElementsFound(); - } - - return getMaxElement( side, elements ); - } - - function getAllElements() { - return document.querySelectorAll( 'body *' ); - } - - var - getHeight = { - bodyOffset: function getBodyOffsetHeight() { - return document.body.offsetHeight + getComputedStyle( 'marginTop' ) + getComputedStyle( 'marginBottom' ); - }, - - offset: function() { - return getHeight.bodyOffset(); //Backwards compatability - }, - - bodyScroll: function getBodyScrollHeight() { - return document.body.scrollHeight; - }, - - custom: function getCustomWidth() { - return customCalcMethods.height(); - }, - - documentElementOffset: function getDEOffsetHeight() { - return document.documentElement.offsetHeight; - }, - - documentElementScroll: function getDEScrollHeight() { - return document.documentElement.scrollHeight; - }, - - max: function getMaxHeight() { - return Math.max.apply( null, getAllMeasurements( getHeight ) ); - }, - - min: function getMinHeight() { - return Math.min.apply( null, getAllMeasurements( getHeight ) ); - }, - - grow: function growHeight() { - return getHeight.max(); //Run max without the forced downsizing - }, - - lowestElement: function getBestHeight() { - return Math.max( getHeight.bodyOffset(), getMaxElement( 'bottom', getAllElements() ) ); - }, - - taggedElement: function getTaggedElementsHeight() { - return getTaggedElements( 'bottom', 'data-iframe-height' ); - }, - }, - - getWidth = { - bodyScroll: function getBodyScrollWidth() { - return document.body.scrollWidth; - }, - - bodyOffset: function getBodyOffsetWidth() { - return document.body.offsetWidth; - }, - - custom: function getCustomWidth() { - return customCalcMethods.width(); - }, - - documentElementScroll: function getDEScrollWidth() { - return document.documentElement.scrollWidth; - }, - - documentElementOffset: function getDEOffsetWidth() { - return document.documentElement.offsetWidth; - }, - - scroll: function getMaxWidth() { - return Math.max( getWidth.bodyScroll(), getWidth.documentElementScroll() ); - }, - - max: function getMaxWidth() { - return Math.max.apply( null, getAllMeasurements( getWidth ) ); - }, - - min: function getMinWidth() { - return Math.min.apply( null, getAllMeasurements( getWidth ) ); - }, - - rightMostElement: function rightMostElement() { - return getMaxElement( 'right', getAllElements() ); - }, - - taggedElement: function getTaggedElementsWidth() { - return getTaggedElements( 'right', 'data-iframe-width' ); - }, - }; - - function sizeIFrame( triggerEvent, triggerEventDesc, customHeight, customWidth ) { - function resizeIFrame() { - height = currentHeight; - width = currentWidth; - - sendMsg( height, width, triggerEvent ); - } - - function isSizeChangeDetected() { - function checkTolarance( a, b ) { - const retVal = Math.abs( a - b ) <= tolerance; - return ! retVal; - } - - currentHeight = ( undefined !== customHeight ) ? customHeight : getHeight[ heightCalcMode ](); - currentWidth = ( undefined !== customWidth ) ? customWidth : getWidth[ widthCalcMode ](); - - return checkTolarance( height, currentHeight ) || ( calculateWidth && checkTolarance( width, currentWidth ) ); - } - - function isForceResizableEvent() { - return ! ( triggerEvent in { init: 1, interval: 1, size: 1 } ); - } - - function isForceResizableCalcMode() { - return ( heightCalcMode in resetRequiredMethods ) || ( calculateWidth && widthCalcMode in resetRequiredMethods ); - } - - function logIgnored() { - log( 'No change in size detected' ); - } - - function checkDownSizing() { - if ( isForceResizableEvent() && isForceResizableCalcMode() ) { - resetIFrame( triggerEventDesc ); - } else if ( ! ( triggerEvent in { interval: 1 } ) ) { - logIgnored(); - } - } - - let currentHeight, currentWidth; - - if ( isSizeChangeDetected() || 'init' === triggerEvent ) { - lockTrigger(); - resizeIFrame(); - } else { - checkDownSizing(); - } - } - - const sizeIFrameThrottled = throttle( sizeIFrame ); - - function sendSize( triggerEvent, triggerEventDesc, customHeight, customWidth ) { - function recordTrigger() { - if ( ! ( triggerEvent in { reset: 1, resetPage: 1, init: 1 } ) ) { - log( 'Trigger event: ' + triggerEventDesc ); - } - } - - function isDoubleFiredEvent() { - return triggerLocked && ( triggerEvent in doubleEventList ); - } - - if ( ! isDoubleFiredEvent() ) { - recordTrigger(); - sizeIFrameThrottled( triggerEvent, triggerEventDesc, customHeight, customWidth ); - } else { - log( 'Trigger event cancelled: ' + triggerEvent ); - } - } - - function lockTrigger() { - if ( ! triggerLocked ) { - triggerLocked = true; - log( 'Trigger event lock on' ); - } - clearTimeout( triggerLockedTimer ); - triggerLockedTimer = setTimeout( function() { - triggerLocked = false; - log( 'Trigger event lock off' ); - log( '--' ); - }, eventCancelTimer ); - } - - function triggerReset( triggerEvent ) { - height = getHeight[ heightCalcMode ](); - width = getWidth[ widthCalcMode ](); - - sendMsg( height, width, triggerEvent ); - } - - function resetIFrame( triggerEventDesc ) { - const hcm = heightCalcMode; - heightCalcMode = heightCalcModeDefault; - - log( 'Reset trigger event: ' + triggerEventDesc ); - lockTrigger(); - triggerReset( 'reset' ); - - heightCalcMode = hcm; - } - - function sendMsg( height, width, triggerEvent, msg, targetOrigin ) { - function setTargetOrigin() { - if ( undefined === targetOrigin ) { - targetOrigin = targetOriginDefault; - } else { - log( 'Message targetOrigin: ' + targetOrigin ); - } - } - - function sendToParent() { - let - size = height + ':' + width, - message = myID + ':' + size + ':' + triggerEvent + ( undefined !== msg ? ':' + msg : '' ); - - log( 'Sending message to host page (' + message + ')' ); - target.postMessage( msgID + message, targetOrigin ); - } - - if ( true === sendPermit ) { - setTargetOrigin(); - sendToParent(); - } - } - - function receiver( event ) { - var processRequestFromParent = { - init: function initFromParent() { - function fireInit() { - initMsg = event.data; - target = event.source; - - init(); - firstRun = false; - setTimeout( function() { - initLock = false; - }, eventCancelTimer ); - } - - if ( document.body ) { - fireInit(); - } else { - log( 'Waiting for page ready' ); - addEventListener( window, 'readystatechange', processRequestFromParent.initFromParent ); - } - }, - - reset: function resetFromParent() { - if ( ! initLock ) { - log( 'Page size reset by host page' ); - triggerReset( 'resetPage' ); - } else { - log( 'Page reset ignored by init' ); - } - }, - - resize: function resizeFromParent() { - sendSize( 'resizeParent', 'Parent window requested size check' ); - }, - - moveToAnchor: function moveToAnchorF() { - inPageLinks.findTarget( getData() ); - }, - inPageLink: function inPageLinkF() { - this.moveToAnchor(); - }, //Backward compatability - - pageInfo: function pageInfoFromParent() { - const msgBody = getData(); - log( 'PageInfoFromParent called from parent: ' + msgBody ); - pageInfoCallback( JSON.parse( msgBody ) ); - log( ' --' ); - }, - - message: function messageFromParent() { - const msgBody = getData(); - - log( 'MessageCallback called from parent: ' + msgBody ); - messageCallback( JSON.parse( msgBody ) ); - log( ' --' ); - }, - }; - - function isMessageForUs() { - return msgID === ( '' + event.data ).substr( 0, msgIdLen ); //''+ Protects against non-string messages - } - - function getMessageType() { - return event.data.split( ']' )[ 1 ].split( ':' )[ 0 ]; - } - - function getData() { - return event.data.substr( event.data.indexOf( ':' ) + 1 ); - } - - function isMiddleTier() { - return ! ( typeof module !== 'undefined' && module.exports ) && ( 'iFrameResize' in window ); - } - - function isInitMsg() { - //Test if this message is from a child below us. This is an ugly test, however, updating - //the message format would break backwards compatibity. - return event.data.split( ':' )[ 2 ] in { 'true': 1, 'false': 1 }; - } - - function callFromParent() { - const messageType = getMessageType(); - - if ( messageType in processRequestFromParent ) { - processRequestFromParent[ messageType ](); - } else if ( ! isMiddleTier() && ! isInitMsg() ) { - warn( 'Unexpected message (' + event.data + ')' ); - } - } - - function processMessage() { - if ( false === firstRun ) { - callFromParent(); - } else if ( isInitMsg() ) { - processRequestFromParent.init(); - } else { - log( 'Ignored message of type "' + getMessageType() + '". Received before initialization.' ); - } - } - - if ( isMessageForUs() ) { - processMessage(); - } - } - - //Normally the parent kicks things off when it detects the iFrame has loaded. - //If this script is async-loaded, then tell parent page to retry init. - function chkLateLoaded() { - if ( 'loading' !== document.readyState ) { - window.parent.postMessage( '[iFrameResizerChild]Ready', '*' ); - } - } - - addEventListener( window, 'message', receiver ); - chkLateLoaded(); -} )(); diff --git a/assets/js/iframeResizer.contentWindow.min.js b/assets/js/iframeResizer.contentWindow.min.js deleted file mode 100644 index 2b6760ee33a78d..00000000000000 --- a/assets/js/iframeResizer.contentWindow.min.js +++ /dev/null @@ -1,10 +0,0 @@ -/*! iFrame Resizer (iframeSizer.contentWindow.min.js) - v3.5.14 - 2017-03-30 - * Desc: Include this file in any page being loaded into an iframe - * to force the iframe to resize to the content size. - * Requires: iframeResizer.min.js on host page. - * Copyright: (c) 2017 David J. Bradshaw - dave@bradshaw.net - * License: MIT - */ - -!function(a){"use strict";function b(a,b,c){"addEventListener"in window?a.addEventListener(b,c,!1):"attachEvent"in window&&a.attachEvent("on"+b,c)}function c(a,b,c){"removeEventListener"in window?a.removeEventListener(b,c,!1):"detachEvent"in window&&a.detachEvent("on"+b,c)}function d(a){return a.charAt(0).toUpperCase()+a.slice(1)}function e(a){var b,c,d,e=null,f=0,g=function(){f=Ha(),e=null,d=a.apply(b,c),e||(b=c=null)};return function(){var h=Ha();f||(f=h);var i=xa-(h-f);return b=this,c=arguments,0>=i||i>xa?(e&&(clearTimeout(e),e=null),f=h,d=a.apply(b,c),e||(b=c=null)):e||(e=setTimeout(g,i)),d}}function f(a){return ma+"["+oa+"] "+a}function g(a){la&&"object"==typeof window.console&&console.log(f(a))}function h(a){"object"==typeof window.console&&console.warn(f(a))}function i(){j(),g("Initialising iFrame ("+location.href+")"),k(),n(),m("background",W),m("padding",$),A(),s(),t(),o(),C(),u(),ia=B(),N("init","Init message from host page"),Da()}function j(){function b(a){return"true"===a?!0:!1}var c=ha.substr(na).split(":");oa=c[0],X=a!==c[1]?Number(c[1]):X,_=a!==c[2]?b(c[2]):_,la=a!==c[3]?b(c[3]):la,ja=a!==c[4]?Number(c[4]):ja,U=a!==c[6]?b(c[6]):U,Y=c[7],fa=a!==c[8]?c[8]:fa,W=c[9],$=c[10],ua=a!==c[11]?Number(c[11]):ua,ia.enable=a!==c[12]?b(c[12]):!1,qa=a!==c[13]?c[13]:qa,Aa=a!==c[14]?c[14]:Aa}function k(){function a(){var a=window.iFrameResizer;g("Reading data from page: "+JSON.stringify(a)),Ca="messageCallback"in a?a.messageCallback:Ca,Da="readyCallback"in a?a.readyCallback:Da,ta="targetOrigin"in a?a.targetOrigin:ta,fa="heightCalculationMethod"in a?a.heightCalculationMethod:fa,Aa="widthCalculationMethod"in a?a.widthCalculationMethod:Aa}function b(a,b){return"function"==typeof a&&(g("Setup custom "+b+"CalcMethod"),Fa[b]=a,a="custom"),a}"iFrameResizer"in window&&Object===window.iFrameResizer.constructor&&(a(),fa=b(fa,"height"),Aa=b(Aa,"width")),g("TargetOrigin for parent set to: "+ta)}function l(a,b){return-1!==b.indexOf("-")&&(h("Negative CSS value ignored for "+a),b=""),b}function m(b,c){a!==c&&""!==c&&"null"!==c&&(document.body.style[b]=c,g("Body "+b+' set to "'+c+'"'))}function n(){a===Y&&(Y=X+"px"),m("margin",l("margin",Y))}function o(){document.documentElement.style.height="",document.body.style.height="",g('HTML & body height set to "auto"')}function p(a){var e={add:function(c){function d(){N(a.eventName,a.eventType)}Ga[c]=d,b(window,c,d)},remove:function(a){var b=Ga[a];delete Ga[a],c(window,a,b)}};a.eventNames&&Array.prototype.map?(a.eventName=a.eventNames[0],a.eventNames.map(e[a.method])):e[a.method](a.eventName),g(d(a.method)+" event listener: "+a.eventType)}function q(a){p({method:a,eventType:"Animation Start",eventNames:["animationstart","webkitAnimationStart"]}),p({method:a,eventType:"Animation Iteration",eventNames:["animationiteration","webkitAnimationIteration"]}),p({method:a,eventType:"Animation End",eventNames:["animationend","webkitAnimationEnd"]}),p({method:a,eventType:"Input",eventName:"input"}),p({method:a,eventType:"Mouse Up",eventName:"mouseup"}),p({method:a,eventType:"Mouse Down",eventName:"mousedown"}),p({method:a,eventType:"Orientation Change",eventName:"orientationchange"}),p({method:a,eventType:"Print",eventName:["afterprint","beforeprint"]}),p({method:a,eventType:"Ready State Change",eventName:"readystatechange"}),p({method:a,eventType:"Touch Start",eventName:"touchstart"}),p({method:a,eventType:"Touch End",eventName:"touchend"}),p({method:a,eventType:"Touch Cancel",eventName:"touchcancel"}),p({method:a,eventType:"Transition Start",eventNames:["transitionstart","webkitTransitionStart","MSTransitionStart","oTransitionStart","otransitionstart"]}),p({method:a,eventType:"Transition Iteration",eventNames:["transitioniteration","webkitTransitionIteration","MSTransitionIteration","oTransitionIteration","otransitioniteration"]}),p({method:a,eventType:"Transition End",eventNames:["transitionend","webkitTransitionEnd","MSTransitionEnd","oTransitionEnd","otransitionend"]}),"child"===qa&&p({method:a,eventType:"IFrame Resized",eventName:"resize"})}function r(a,b,c,d){return b!==a&&(a in c||(h(a+" is not a valid option for "+d+"CalculationMethod."),a=b),g(d+' calculation method set to "'+a+'"')),a}function s(){fa=r(fa,ea,Ia,"height")}function t(){Aa=r(Aa,za,Ja,"width")}function u(){!0===U?(q("add"),F()):g("Auto Resize disabled")}function v(){g("Disable outgoing messages"),ra=!1}function w(){g("Remove event listener: Message"),c(window,"message",S)}function x(){null!==Z&&Z.disconnect()}function y(){q("remove"),x(),clearInterval(ka)}function z(){v(),w(),!0===U&&y()}function A(){var a=document.createElement("div");a.style.clear="both",a.style.display="block",document.body.appendChild(a)}function B(){function c(){return{x:window.pageXOffset!==a?window.pageXOffset:document.documentElement.scrollLeft,y:window.pageYOffset!==a?window.pageYOffset:document.documentElement.scrollTop}}function d(a){var b=a.getBoundingClientRect(),d=c();return{x:parseInt(b.left,10)+parseInt(d.x,10),y:parseInt(b.top,10)+parseInt(d.y,10)}}function e(b){function c(a){var b=d(a);g("Moving to in page link (#"+e+") at x: "+b.x+" y: "+b.y),R(b.y,b.x,"scrollToOffset")}var e=b.split("#")[1]||b,f=decodeURIComponent(e),h=document.getElementById(f)||document.getElementsByName(f)[0];a!==h?c(h):(g("In page link (#"+e+") not found in iFrame, so sending to parent"),R(0,0,"inPageLink","#"+e))}function f(){""!==location.hash&&"#"!==location.hash&&e(location.href)}function i(){function a(a){function c(a){a.preventDefault(),e(this.getAttribute("href"))}"#"!==a.getAttribute("href")&&b(a,"click",c)}Array.prototype.forEach.call(document.querySelectorAll('a[href^="#"]'),a)}function j(){b(window,"hashchange",f)}function k(){setTimeout(f,ba)}function l(){Array.prototype.forEach&&document.querySelectorAll?(g("Setting up location.hash handlers"),i(),j(),k()):h("In page linking not fully supported in this browser! (See README.md for IE8 workaround)")}return ia.enable?l():g("In page linking not enabled"),{findTarget:e}}function C(){g("Enable public methods"),Ba.parentIFrame={autoResize:function(a){return!0===a&&!1===U?(U=!0,u()):!1===a&&!0===U&&(U=!1,y()),U},close:function(){R(0,0,"close"),z()},getId:function(){return oa},getPageInfo:function(a){"function"==typeof a?(Ea=a,R(0,0,"pageInfo")):(Ea=function(){},R(0,0,"pageInfoStop"))},moveToAnchor:function(a){ia.findTarget(a)},reset:function(){Q("parentIFrame.reset")},scrollTo:function(a,b){R(b,a,"scrollTo")},scrollToOffset:function(a,b){R(b,a,"scrollToOffset")},sendMessage:function(a,b){R(0,0,"message",JSON.stringify(a),b)},setHeightCalculationMethod:function(a){fa=a,s()},setWidthCalculationMethod:function(a){Aa=a,t()},setTargetOrigin:function(a){g("Set targetOrigin: "+a),ta=a},size:function(a,b){var c=""+(a?a:"")+(b?","+b:"");N("size","parentIFrame.size("+c+")",a,b)}}}function D(){0!==ja&&(g("setInterval: "+ja+"ms"),ka=setInterval(function(){N("interval","setInterval: "+ja)},Math.abs(ja)))}function E(){function b(a){function b(a){!1===a.complete&&(g("Attach listeners to "+a.src),a.addEventListener("load",f,!1),a.addEventListener("error",h,!1),k.push(a))}"attributes"===a.type&&"src"===a.attributeName?b(a.target):"childList"===a.type&&Array.prototype.forEach.call(a.target.querySelectorAll("img"),b)}function c(a){k.splice(k.indexOf(a),1)}function d(a){g("Remove listeners from "+a.src),a.removeEventListener("load",f,!1),a.removeEventListener("error",h,!1),c(a)}function e(b,c,e){d(b.target),N(c,e+": "+b.target.src,a,a)}function f(a){e(a,"imageLoad","Image loaded")}function h(a){e(a,"imageLoadFailed","Image load failed")}function i(a){N("mutationObserver","mutationObserver: "+a[0].target+" "+a[0].type),a.forEach(b)}function j(){var a=document.querySelector("body"),b={attributes:!0,attributeOldValue:!1,characterData:!0,characterDataOldValue:!1,childList:!0,subtree:!0};return m=new l(i),g("Create body MutationObserver"),m.observe(a,b),m}var k=[],l=window.MutationObserver||window.WebKitMutationObserver,m=j();return{disconnect:function(){"disconnect"in m&&(g("Disconnect body MutationObserver"),m.disconnect(),k.forEach(d))}}}function F(){var a=0>ja;window.MutationObserver||window.WebKitMutationObserver?a?D():Z=E():(g("MutationObserver not supported in this browser!"),D())}function G(a,b){function c(a){var c=/^\d+(px)?$/i;if(c.test(a))return parseInt(a,V);var d=b.style.left,e=b.runtimeStyle.left;return b.runtimeStyle.left=b.currentStyle.left,b.style.left=a||0,a=b.style.pixelLeft,b.style.left=d,b.runtimeStyle.left=e,a}var d=0;return b=b||document.body,"defaultView"in document&&"getComputedStyle"in document.defaultView?(d=document.defaultView.getComputedStyle(b,null),d=null!==d?d[a]:0):d=c(b.currentStyle[a]),parseInt(d,V)}function H(a){a>xa/2&&(xa=2*a,g("Event throttle increased to "+xa+"ms"))}function I(a,b){for(var c=b.length,e=0,f=0,h=d(a),i=Ha(),j=0;c>j;j++)e=b[j].getBoundingClientRect()[a]+G("margin"+h,b[j]),e>f&&(f=e);return i=Ha()-i,g("Parsed "+c+" HTML elements"),g("Element position calculated in "+i+"ms"),H(i),f}function J(a){return[a.bodyOffset(),a.bodyScroll(),a.documentElementOffset(),a.documentElementScroll()]}function K(a,b){function c(){return h("No tagged elements ("+b+") found on page"),document.querySelectorAll("body *")}var d=document.querySelectorAll("["+b+"]");return 0===d.length&&c(),I(a,d)}function L(){return document.querySelectorAll("body *")}function M(b,c,d,e){function f(){da=m,ya=n,R(da,ya,b)}function h(){function b(a,b){var c=Math.abs(a-b)<=ua;return!c}return m=a!==d?d:Ia[fa](),n=a!==e?e:Ja[Aa](),b(da,m)||_&&b(ya,n)}function i(){return!(b in{init:1,interval:1,size:1})}function j(){return fa in pa||_&&Aa in pa}function k(){g("No change in size detected")}function l(){i()&&j()?Q(c):b in{interval:1}||k()}var m,n;h()||"init"===b?(O(),f()):l()}function N(a,b,c,d){function e(){a in{reset:1,resetPage:1,init:1}||g("Trigger event: "+b)}function f(){return va&&a in aa}f()?g("Trigger event cancelled: "+a):(e(),Ka(a,b,c,d))}function O(){va||(va=!0,g("Trigger event lock on")),clearTimeout(wa),wa=setTimeout(function(){va=!1,g("Trigger event lock off"),g("--")},ba)}function P(a){da=Ia[fa](),ya=Ja[Aa](),R(da,ya,a)}function Q(a){var b=fa;fa=ea,g("Reset trigger event: "+a),O(),P("reset"),fa=b}function R(b,c,d,e,f){function h(){a===f?f=ta:g("Message targetOrigin: "+f)}function i(){var h=b+":"+c,i=oa+":"+h+":"+d+(a!==e?":"+e:"");g("Sending message to host page ("+i+")"),sa.postMessage(ma+i,f)}!0===ra&&(h(),i())}function S(a){function c(){return ma===(""+a.data).substr(0,na)}function d(){return a.data.split("]")[1].split(":")[0]}function e(){return a.data.substr(a.data.indexOf(":")+1)}function f(){return!("undefined"!=typeof module&&module.exports)&&"iFrameResize"in window}function j(){return a.data.split(":")[2]in{"true":1,"false":1}}function k(){var b=d();b in m?m[b]():f()||j()||h("Unexpected message ("+a.data+")")}function l(){!1===ca?k():j()?m.init():g('Ignored message of type "'+d()+'". Received before initialization.')}var m={init:function(){function c(){ha=a.data,sa=a.source,i(),ca=!1,setTimeout(function(){ga=!1},ba)}document.body?c():(g("Waiting for page ready"),b(window,"readystatechange",m.initFromParent))},reset:function(){ga?g("Page reset ignored by init"):(g("Page size reset by host page"),P("resetPage"))},resize:function(){N("resizeParent","Parent window requested size check")},moveToAnchor:function(){ia.findTarget(e())},inPageLink:function(){this.moveToAnchor()},pageInfo:function(){var a=e();g("PageInfoFromParent called from parent: "+a),Ea(JSON.parse(a)),g(" --")},message:function(){var a=e();g("MessageCallback called from parent: "+a),Ca(JSON.parse(a)),g(" --")}};c()&&l()}function T(){"loading"!==document.readyState&&window.parent.postMessage("[iFrameResizerChild]Ready","*")}if("undefined"!=typeof window){var U=!0,V=10,W="",X=0,Y="",Z=null,$="",_=!1,aa={resize:1,click:1},ba=128,ca=!0,da=1,ea="bodyOffset",fa=ea,ga=!0,ha="",ia={},ja=32,ka=null,la=!1,ma="[iFrameSizer]",na=ma.length,oa="",pa={max:1,min:1,bodyScroll:1,documentElementScroll:1},qa="child",ra=!0,sa=window.parent,ta="*",ua=0,va=!1,wa=null,xa=16,ya=1,za="scroll",Aa=za,Ba=window,Ca=function(){h("MessageCallback function not defined")},Da=function(){},Ea=function(){},Fa={height:function(){return h("Custom height calculation function not defined"),document.documentElement.offsetHeight},width:function(){return h("Custom width calculation function not defined"),document.body.scrollWidth}},Ga={},Ha=Date.now||function(){return(new Date).getTime()},Ia={bodyOffset:function(){return document.body.offsetHeight+G("marginTop")+G("marginBottom")},offset:function(){return Ia.bodyOffset()},bodyScroll:function(){return document.body.scrollHeight},custom:function(){return Fa.height()},documentElementOffset:function(){return document.documentElement.offsetHeight},documentElementScroll:function(){return document.documentElement.scrollHeight},max:function(){return Math.max.apply(null,J(Ia))},min:function(){return Math.min.apply(null,J(Ia))},grow:function(){return Ia.max()},lowestElement:function(){return Math.max(Ia.bodyOffset(),I("bottom",L()))},taggedElement:function(){return K("bottom","data-iframe-height")}},Ja={bodyScroll:function(){return document.body.scrollWidth},bodyOffset:function(){return document.body.offsetWidth},custom:function(){return Fa.width()},documentElementScroll:function(){return document.documentElement.scrollWidth},documentElementOffset:function(){return document.documentElement.offsetWidth},scroll:function(){return Math.max(Ja.bodyScroll(),Ja.documentElementScroll())},max:function(){return Math.max.apply(null,J(Ja))},min:function(){return Math.min.apply(null,J(Ja))},rightMostElement:function(){return I("right",L())},taggedElement:function(){return K("right","data-iframe-width")}},Ka=e(M);b(window,"message",S),T()}}(); -//# sourceMappingURL=iframeResizer.contentWindow.map \ No newline at end of file diff --git a/assets/js/iframeResizer.js b/assets/js/iframeResizer.js deleted file mode 100644 index 16e2e72c84612b..00000000000000 --- a/assets/js/iframeResizer.js +++ /dev/null @@ -1,1053 +0,0 @@ -/* - * File: iframeResizer.js - * Desc: Force iframes to size to content. - * Requires: iframeResizer.contentWindow.js to be loaded into the target frame. - * Doc: https://github.com/davidjbradshaw/iframe-resizer - * Author: David J. Bradshaw - dave@bradshaw.net - * Contributor: Jure Mav - jure.mav@gmail.com - * Contributor: Reed Dadoune - reed@dadoune.com - */ - -( function( undefined ) { - 'use strict'; - - if ( typeof window === 'undefined' ) { - return; - } // don't run for server side render - - let - count = 0, - logEnabled = false, - hiddenCheckEnabled = false, - msgHeader = 'message', - msgHeaderLen = msgHeader.length, - msgId = '[iFrameSizer]', //Must match iframe msg ID - msgIdLen = msgId.length, - pagePosition = null, - requestAnimationFrame = window.requestAnimationFrame, - resetRequiredMethods = { max: 1, scroll: 1, bodyScroll: 1, documentElementScroll: 1 }, - settings = {}, - timer = null, - logId = 'Host Page', - - defaults = { - autoResize: true, - bodyBackground: null, - bodyMargin: null, - bodyMarginV1: 8, - bodyPadding: null, - checkOrigin: true, - inPageLinks: false, - enablePublicMethods: true, - heightCalculationMethod: 'bodyOffset', - id: 'iFrameResizer', - interval: 32, - log: false, - maxHeight: Infinity, - maxWidth: Infinity, - minHeight: 0, - minWidth: 0, - resizeFrom: 'parent', - scrolling: false, - sizeHeight: true, - sizeWidth: false, - warningTimeout: 5000, - tolerance: 0, - widthCalculationMethod: 'scroll', - closedCallback: function() {}, - initCallback: function() {}, - messageCallback: function() { - warn( 'MessageCallback function not defined' ); - }, - resizedCallback: function() {}, - scrollCallback: function() { - return true; - }, - }; - - function addEventListener( obj, evt, func ) { - /* istanbul ignore else */ // Not testable in PhantonJS - if ( 'addEventListener' in window ) { - obj.addEventListener( evt, func, false ); - } else if ( 'attachEvent' in window ) {//IE - obj.attachEvent( 'on' + evt, func ); - } - } - - function removeEventListener( el, evt, func ) { - /* istanbul ignore else */ // Not testable in phantonJS - if ( 'removeEventListener' in window ) { - el.removeEventListener( evt, func, false ); - } else if ( 'detachEvent' in window ) { //IE - el.detachEvent( 'on' + evt, func ); - } - } - - function setupRequestAnimationFrame() { - let - vendors = [ 'moz', 'webkit', 'o', 'ms' ], - x; - - // Remove vendor prefixing if prefixed and break early if not - for ( x = 0; x < vendors.length && ! requestAnimationFrame; x += 1 ) { - requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ]; - } - - if ( ! ( requestAnimationFrame ) ) { - log( 'setup', 'RequestAnimationFrame not supported' ); - } - } - - function getMyID( iframeId ) { - let retStr = 'Host page: ' + iframeId; - - if ( window.top !== window.self ) { - if ( window.parentIFrame && window.parentIFrame.getId ) { - retStr = window.parentIFrame.getId() + ': ' + iframeId; - } else { - retStr = 'Nested host page: ' + iframeId; - } - } - - return retStr; - } - - function formatLogHeader( iframeId ) { - return msgId + '[' + getMyID( iframeId ) + ']'; - } - - function isLogEnabled( iframeId ) { - return settings[ iframeId ] ? settings[ iframeId ].log : logEnabled; - } - - function log( iframeId, msg ) { - output( 'log', iframeId, msg, isLogEnabled( iframeId ) ); - } - - function info( iframeId, msg ) { - output( 'info', iframeId, msg, isLogEnabled( iframeId ) ); - } - - function warn( iframeId, msg ) { - output( 'warn', iframeId, msg, true ); - } - - function output( type, iframeId, msg, enabled ) { - if ( true === enabled && 'object' === typeof window.console ) { - console[ type ]( formatLogHeader( iframeId ), msg ); - } - } - - function iFrameListener( event ) { - function resizeIFrame() { - function resize() { - setSize( messageData ); - setPagePosition( iframeId ); - callback( 'resizedCallback', messageData ); - } - - ensureInRange( 'Height' ); - ensureInRange( 'Width' ); - - syncResize( resize, messageData, 'init' ); - } - - function processMsg() { - const data = msg.substr( msgIdLen ).split( ':' ); - - return { - iframe: settings[ data[ 0 ] ].iframe, - id: data[ 0 ], - height: data[ 1 ], - width: data[ 2 ], - type: data[ 3 ], - }; - } - - function ensureInRange( Dimension ) { - let - max = Number( settings[ iframeId ][ 'max' + Dimension ] ), - min = Number( settings[ iframeId ][ 'min' + Dimension ] ), - dimension = Dimension.toLowerCase(), - size = Number( messageData[ dimension ] ); - - log( iframeId, 'Checking ' + dimension + ' is in range ' + min + '-' + max ); - - if ( size < min ) { - size = min; - log( iframeId, 'Set ' + dimension + ' to min value' ); - } - - if ( size > max ) { - size = max; - log( iframeId, 'Set ' + dimension + ' to max value' ); - } - - messageData[ dimension ] = '' + size; - } - - function isMessageFromIFrame() { - function checkAllowedOrigin() { - function checkList() { - let - i = 0, - retCode = false; - - log( iframeId, 'Checking connection is from allowed list of origins: ' + checkOrigin ); - - for ( ; i < checkOrigin.length; i++ ) { - if ( checkOrigin[ i ] === origin ) { - retCode = true; - break; - } - } - return retCode; - } - - function checkSingle() { - const remoteHost = settings[ iframeId ].remoteHost; - log( iframeId, 'Checking connection is from: ' + remoteHost ); - return origin === remoteHost; - } - - return checkOrigin.constructor === Array ? checkList() : checkSingle(); - } - - var - origin = event.origin, - checkOrigin = settings[ iframeId ].checkOrigin; - - if ( checkOrigin && ( '' + origin !== 'null' ) && ! checkAllowedOrigin() ) { - throw new Error( - 'Unexpected message received from: ' + origin + - ' for ' + messageData.iframe.id + - '. Message was: ' + event.data + - '. This error can be disabled by setting the checkOrigin: false option or by providing of array of trusted domains.' - ); - } - - return true; - } - - function isMessageForUs() { - return msgId === ( ( '' + msg ).substr( 0, msgIdLen ) ) && ( msg.substr( msgIdLen ).split( ':' )[ 0 ] in settings ); //''+Protects against non-string msg - } - - function isMessageFromMetaParent() { - //Test if this message is from a parent above us. This is an ugly test, however, updating - //the message format would break backwards compatibity. - const retCode = messageData.type in { 'true': 1, 'false': 1, undefined: 1 }; - - if ( retCode ) { - log( iframeId, 'Ignoring init message from meta parent page' ); - } - - return retCode; - } - - function getMsgBody( offset ) { - return msg.substr( msg.indexOf( ':' ) + msgHeaderLen + offset ); - } - - function forwardMsgFromIFrame( msgBody ) { - log( iframeId, 'MessageCallback passed: {iframe: ' + messageData.iframe.id + ', message: ' + msgBody + '}' ); - callback( 'messageCallback', { - iframe: messageData.iframe, - message: JSON.parse( msgBody ), - } ); - log( iframeId, '--' ); - } - - function getPageInfo() { - let - bodyPosition = document.body.getBoundingClientRect(), - iFramePosition = messageData.iframe.getBoundingClientRect(); - - return JSON.stringify( { - iframeHeight: iFramePosition.height, - iframeWidth: iFramePosition.width, - clientHeight: Math.max( document.documentElement.clientHeight, window.innerHeight || 0 ), - clientWidth: Math.max( document.documentElement.clientWidth, window.innerWidth || 0 ), - offsetTop: parseInt( iFramePosition.top - bodyPosition.top, 10 ), - offsetLeft: parseInt( iFramePosition.left - bodyPosition.left, 10 ), - scrollTop: window.pageYOffset, - scrollLeft: window.pageXOffset, - } ); - } - - function sendPageInfoToIframe( iframe, iframeId ) { - function debouncedTrigger() { - trigger( - 'Send Page Info', - 'pageInfo:' + getPageInfo(), - iframe, - iframeId - ); - } - - debouce( debouncedTrigger, 32 ); - } - - function startPageInfoMonitor() { - function setListener( type, func ) { - function sendPageInfo() { - if ( settings[ id ] ) { - sendPageInfoToIframe( settings[ id ].iframe, id ); - } else { - stop(); - } - } - - [ 'scroll', 'resize' ].forEach( function( evt ) { - log( id, type + evt + ' listener for sendPageInfo' ); - func( window, evt, sendPageInfo ); - } ); - } - - function stop() { - setListener( 'Remove ', removeEventListener ); - } - - function start() { - setListener( 'Add ', addEventListener ); - } - - var id = iframeId; //Create locally scoped copy of iFrame ID - - start(); - - settings[ id ].stopPageInfo = stop; - } - - function stopPageInfoMonitor() { - if ( settings[ iframeId ] && settings[ iframeId ].stopPageInfo ) { - settings[ iframeId ].stopPageInfo(); - delete settings[ iframeId ].stopPageInfo; - } - } - - function checkIFrameExists() { - let retBool = true; - - if ( null === messageData.iframe ) { - warn( iframeId, 'IFrame (' + messageData.id + ') not found' ); - retBool = false; - } - return retBool; - } - - function getElementPosition( target ) { - const iFramePosition = target.getBoundingClientRect(); - - getPagePosition( iframeId ); - - return { - x: Math.floor( Number( iFramePosition.left ) + Number( pagePosition.x ) ), - y: Math.floor( Number( iFramePosition.top ) + Number( pagePosition.y ) ), - }; - } - - function scrollRequestFromChild( addOffset ) { - /* istanbul ignore next */ //Not testable in Karma - function reposition() { - pagePosition = newPosition; - scrollTo(); - log( iframeId, '--' ); - } - - function calcOffset() { - return { - x: Number( messageData.width ) + offset.x, - y: Number( messageData.height ) + offset.y, - }; - } - - function scrollParent() { - if ( window.parentIFrame ) { - window.parentIFrame[ 'scrollTo' + ( addOffset ? 'Offset' : '' ) ]( newPosition.x, newPosition.y ); - } else { - warn( iframeId, 'Unable to scroll to requested position, window.parentIFrame not found' ); - } - } - - var - offset = addOffset ? getElementPosition( messageData.iframe ) : { x: 0, y: 0 }, - newPosition = calcOffset(); - - log( iframeId, 'Reposition requested from iFrame (offset x:' + offset.x + ' y:' + offset.y + ')' ); - - if ( window.top !== window.self ) { - scrollParent(); - } else { - reposition(); - } - } - - function scrollTo() { - if ( false !== callback( 'scrollCallback', pagePosition ) ) { - setPagePosition( iframeId ); - } else { - unsetPagePosition(); - } - } - - function findTarget( location ) { - function jumpToTarget() { - const jumpPosition = getElementPosition( target ); - - log( iframeId, 'Moving to in page link (#' + hash + ') at x: ' + jumpPosition.x + ' y: ' + jumpPosition.y ); - pagePosition = { - x: jumpPosition.x, - y: jumpPosition.y, - }; - - scrollTo(); - log( iframeId, '--' ); - } - - function jumpToParent() { - if ( window.parentIFrame ) { - window.parentIFrame.moveToAnchor( hash ); - } else { - log( iframeId, 'In page link #' + hash + ' not found and window.parentIFrame not found' ); - } - } - - var - hash = location.split( '#' )[ 1 ] || '', - hashData = decodeURIComponent( hash ), - target = document.getElementById( hashData ) || document.getElementsByName( hashData )[ 0 ]; - - if ( target ) { - jumpToTarget(); - } else if ( window.top !== window.self ) { - jumpToParent(); - } else { - log( iframeId, 'In page link #' + hash + ' not found' ); - } - } - - function callback( funcName, val ) { - return chkCallback( iframeId, funcName, val ); - } - - function actionMsg() { - if ( settings[ iframeId ].firstRun ) { - firstRun(); - } - - switch ( messageData.type ) { - case 'close': - closeIFrame( messageData.iframe ); - break; - case 'message': - forwardMsgFromIFrame( getMsgBody( 6 ) ); - break; - case 'scrollTo': - scrollRequestFromChild( false ); - break; - case 'scrollToOffset': - scrollRequestFromChild( true ); - break; - case 'pageInfo': - sendPageInfoToIframe( settings[ iframeId ].iframe, iframeId ); - startPageInfoMonitor(); - break; - case 'pageInfoStop': - stopPageInfoMonitor(); - break; - case 'inPageLink': - findTarget( getMsgBody( 9 ) ); - break; - case 'reset': - resetIFrame( messageData ); - break; - case 'init': - resizeIFrame(); - callback( 'initCallback', messageData.iframe ); - break; - default: - resizeIFrame(); - } - } - - function hasSettings( iframeId ) { - let retBool = true; - - if ( ! settings[ iframeId ] ) { - retBool = false; - warn( messageData.type + ' No settings for ' + iframeId + '. Message was: ' + msg ); - } - - return retBool; - } - - function iFrameReadyMsgReceived() { - for ( const iframeId in settings ) { - trigger( 'iFrame requested init', createOutgoingMsg( iframeId ), document.getElementById( iframeId ), iframeId ); - } - } - - function firstRun() { - settings[ iframeId ].firstRun = false; - } - - function clearWarningTimeout() { - clearTimeout( settings[ iframeId ].msgTimeout ); - settings[ iframeId ].warningTimeout = 0; - } - - var - msg = event.data, - messageData = {}, - iframeId = null; - - if ( '[iFrameResizerChild]Ready' === msg ) { - iFrameReadyMsgReceived(); - } else if ( isMessageForUs() ) { - messageData = processMsg(); - iframeId = logId = messageData.id; - settings[ iframeId ].loaded = true; - - if ( ! isMessageFromMetaParent() && hasSettings( iframeId ) ) { - log( iframeId, 'Received: ' + msg ); - - if ( checkIFrameExists() && isMessageFromIFrame() ) { - actionMsg(); - } - } - } else { - info( iframeId, 'Ignored: ' + msg ); - } - } - - function chkCallback( iframeId, funcName, val ) { - let - func = null, - retVal = null; - - if ( settings[ iframeId ] ) { - func = settings[ iframeId ][ funcName ]; - - if ( 'function' === typeof func ) { - retVal = func( val ); - } else { - throw new TypeError( funcName + ' on iFrame[' + iframeId + '] is not a function' ); - } - } - - return retVal; - } - - function closeIFrame( iframe ) { - const iframeId = iframe.id; - - log( iframeId, 'Removing iFrame: ' + iframeId ); - if ( iframe.parentNode ) { - iframe.parentNode.removeChild( iframe ); - } - chkCallback( iframeId, 'closedCallback', iframeId ); - log( iframeId, '--' ); - delete settings[ iframeId ]; - } - - function getPagePosition( iframeId ) { - if ( null === pagePosition ) { - pagePosition = { - x: ( window.pageXOffset !== undefined ) ? window.pageXOffset : document.documentElement.scrollLeft, - y: ( window.pageYOffset !== undefined ) ? window.pageYOffset : document.documentElement.scrollTop, - }; - log( iframeId, 'Get page position: ' + pagePosition.x + ',' + pagePosition.y ); - } - } - - function setPagePosition( iframeId ) { - if ( null !== pagePosition ) { - window.scrollTo( pagePosition.x, pagePosition.y ); - log( iframeId, 'Set page position: ' + pagePosition.x + ',' + pagePosition.y ); - unsetPagePosition(); - } - } - - function unsetPagePosition() { - pagePosition = null; - } - - function resetIFrame( messageData ) { - function reset() { - setSize( messageData ); - trigger( 'reset', 'reset', messageData.iframe, messageData.id ); - } - - log( messageData.id, 'Size reset requested by ' + ( 'init' === messageData.type ? 'host page' : 'iFrame' ) ); - getPagePosition( messageData.id ); - syncResize( reset, messageData, 'reset' ); - } - - function setSize( messageData ) { - function setDimension( dimension ) { - messageData.iframe.style[ dimension ] = messageData[ dimension ] + 'px'; - log( - messageData.id, - 'IFrame (' + iframeId + - ') ' + dimension + - ' set to ' + messageData[ dimension ] + 'px' - ); - } - - function chkZero( dimension ) { - //FireFox sets dimension of hidden iFrames to zero. - //So if we detect that set up an event to check for - //when iFrame becomes visible. - - /* istanbul ignore next */ //Not testable in PhantomJS - if ( ! hiddenCheckEnabled && '0' === messageData[ dimension ] ) { - hiddenCheckEnabled = true; - log( iframeId, 'Hidden iFrame detected, creating visibility listener' ); - fixHiddenIFrames(); - } - } - - function processDimension( dimension ) { - setDimension( dimension ); - chkZero( dimension ); - } - - var iframeId = messageData.iframe.id; - - if ( settings[ iframeId ] ) { - if ( settings[ iframeId ].sizeHeight ) { - processDimension( 'height' ); - } - if ( settings[ iframeId ].sizeWidth ) { - processDimension( 'width' ); - } - } - } - - function syncResize( func, messageData, doNotSync ) { - /* istanbul ignore if */ //Not testable in PhantomJS - if ( doNotSync !== messageData.type && requestAnimationFrame ) { - log( messageData.id, 'Requesting animation frame' ); - requestAnimationFrame( func ); - } else { - func(); - } - } - - function trigger( calleeMsg, msg, iframe, id, noResponseWarning ) { - function postMessageToIFrame() { - const target = settings[ id ].targetOrigin; - log( id, '[' + calleeMsg + '] Sending msg to iframe[' + id + '] (' + msg + ') targetOrigin: ' + target ); - iframe.contentWindow.postMessage( msgId + msg, target ); - } - - function iFrameNotFound() { - warn( id, '[' + calleeMsg + '] IFrame(' + id + ') not found' ); - } - - function chkAndSend() { - if ( iframe && 'contentWindow' in iframe && ( null !== iframe.contentWindow ) ) { //Null test for PhantomJS - postMessageToIFrame(); - } else { - iFrameNotFound(); - } - } - - function warnOnNoResponse() { - function warning() { - if ( settings[ id ] && ! settings[ id ].loaded && ! errorShown ) { - errorShown = true; - warn( id, 'IFrame has not responded within ' + settings[ id ].warningTimeout / 1000 + ' seconds. Check iFrameResizer.contentWindow.js has been loaded in iFrame. This message can be ingored if everything is working, or you can set the warningTimeout option to a higher value or zero to suppress this warning.' ); - } - } - - if ( !! noResponseWarning && !! settings[ id ].warningTimeout ) { - settings[ id ].msgTimeout = setTimeout( warning, settings[ id ].warningTimeout ); - } - } - - var errorShown = false; - - id = id || iframe.id; - - if ( settings[ id ] ) { - chkAndSend(); - warnOnNoResponse(); - } - } - - function createOutgoingMsg( iframeId ) { - return iframeId + - ':' + settings[ iframeId ].bodyMarginV1 + - ':' + settings[ iframeId ].sizeWidth + - ':' + settings[ iframeId ].log + - ':' + settings[ iframeId ].interval + - ':' + settings[ iframeId ].enablePublicMethods + - ':' + settings[ iframeId ].autoResize + - ':' + settings[ iframeId ].bodyMargin + - ':' + settings[ iframeId ].heightCalculationMethod + - ':' + settings[ iframeId ].bodyBackground + - ':' + settings[ iframeId ].bodyPadding + - ':' + settings[ iframeId ].tolerance + - ':' + settings[ iframeId ].inPageLinks + - ':' + settings[ iframeId ].resizeFrom + - ':' + settings[ iframeId ].widthCalculationMethod; - } - - function setupIFrame( iframe, options ) { - function setLimits() { - function addStyle( style ) { - if ( ( Infinity !== settings[ iframeId ][ style ] ) && ( 0 !== settings[ iframeId ][ style ] ) ) { - iframe.style[ style ] = settings[ iframeId ][ style ] + 'px'; - log( iframeId, 'Set ' + style + ' = ' + settings[ iframeId ][ style ] + 'px' ); - } - } - - function chkMinMax( dimension ) { - if ( settings[ iframeId ][ 'min' + dimension ] > settings[ iframeId ][ 'max' + dimension ] ) { - throw new Error( 'Value for min' + dimension + ' can not be greater than max' + dimension ); - } - } - - chkMinMax( 'Height' ); - chkMinMax( 'Width' ); - - addStyle( 'maxHeight' ); - addStyle( 'minHeight' ); - addStyle( 'maxWidth' ); - addStyle( 'minWidth' ); - } - - function newId() { - let id = ( ( options && options.id ) || defaults.id + count++ ); - if ( null !== document.getElementById( id ) ) { - id = id + count++; - } - return id; - } - - function ensureHasId( iframeId ) { - logId = iframeId; - if ( '' === iframeId ) { - iframe.id = iframeId = newId(); - logEnabled = ( options || {} ).log; - logId = iframeId; - log( iframeId, 'Added missing iframe ID: ' + iframeId + ' (' + iframe.src + ')' ); - } - - return iframeId; - } - - function setScrolling() { - log( iframeId, 'IFrame scrolling ' + ( settings[ iframeId ].scrolling ? 'enabled' : 'disabled' ) + ' for ' + iframeId ); - iframe.style.overflow = false === settings[ iframeId ].scrolling ? 'hidden' : 'auto'; - switch ( settings[ iframeId ].scrolling ) { - case true: - iframe.scrolling = 'yes'; - break; - case false: - iframe.scrolling = 'no'; - break; - default: - iframe.scrolling = settings[ iframeId ].scrolling; - } - } - - //The V1 iFrame script expects an int, where as in V2 expects a CSS - //string value such as '1px 3em', so if we have an int for V2, set V1=V2 - //and then convert V2 to a string PX value. - function setupBodyMarginValues() { - if ( ( 'number' === typeof( settings[ iframeId ].bodyMargin ) ) || ( '0' === settings[ iframeId ].bodyMargin ) ) { - settings[ iframeId ].bodyMarginV1 = settings[ iframeId ].bodyMargin; - settings[ iframeId ].bodyMargin = '' + settings[ iframeId ].bodyMargin + 'px'; - } - } - - function checkReset() { - // Reduce scope of firstRun to function, because IE8's JS execution - // context stack is borked and this value gets externally - // changed midway through running this function!!! - let - firstRun = settings[ iframeId ].firstRun, - resetRequertMethod = settings[ iframeId ].heightCalculationMethod in resetRequiredMethods; - - if ( ! firstRun && resetRequertMethod ) { - resetIFrame( { iframe: iframe, height: 0, width: 0, type: 'init' } ); - } - } - - function setupIFrameObject() { - if ( Function.prototype.bind ) { //Ignore unpolyfilled IE8. - settings[ iframeId ].iframe.iFrameResizer = { - - close: closeIFrame.bind( null, settings[ iframeId ].iframe ), - - resize: trigger.bind( null, 'Window resize', 'resize', settings[ iframeId ].iframe ), - - moveToAnchor: function( anchor ) { - trigger( 'Move to anchor', 'moveToAnchor:' + anchor, settings[ iframeId ].iframe, iframeId ); - }, - - sendMessage: function( message ) { - message = JSON.stringify( message ); - trigger( 'Send Message', 'message:' + message, settings[ iframeId ].iframe, iframeId ); - }, - }; - } - } - - //We have to call trigger twice, as we can not be sure if all - //iframes have completed loading when this code runs. The - //event listener also catches the page changing in the iFrame. - function init( msg ) { - function iFrameLoaded() { - trigger( 'iFrame.onload', msg, iframe, undefined, true ); - checkReset(); - } - - addEventListener( iframe, 'load', iFrameLoaded ); - trigger( 'init', msg, iframe, undefined, true ); - } - - function checkOptions( options ) { - if ( 'object' !== typeof options ) { - throw new TypeError( 'Options is not an object' ); - } - } - - function copyOptions( options ) { - for ( const option in defaults ) { - if ( defaults.hasOwnProperty( option ) ) { - settings[ iframeId ][ option ] = options.hasOwnProperty( option ) ? options[ option ] : defaults[ option ]; - } - } - } - - function getTargetOrigin( remoteHost ) { - return ( '' === remoteHost || 'file://' === remoteHost ) ? '*' : remoteHost; - } - - function processOptions( options ) { - options = options || {}; - settings[ iframeId ] = { - firstRun: true, - iframe: iframe, - remoteHost: iframe.src.split( '/' ).slice( 0, 3 ).join( '/' ), - }; - - checkOptions( options ); - copyOptions( options ); - - settings[ iframeId ].targetOrigin = true === settings[ iframeId ].checkOrigin ? getTargetOrigin( settings[ iframeId ].remoteHost ) : '*'; - } - - function beenHere() { - return ( iframeId in settings && 'iFrameResizer' in iframe ); - } - - var iframeId = ensureHasId( iframe.id ); - - if ( ! beenHere() ) { - processOptions( options ); - setScrolling(); - setLimits(); - setupBodyMarginValues(); - init( createOutgoingMsg( iframeId ) ); - setupIFrameObject(); - } else { - warn( iframeId, 'Ignored iFrame, already setup.' ); - } - } - - function debouce( fn, time ) { - if ( null === timer ) { - timer = setTimeout( function() { - timer = null; - fn(); - }, time ); - } - } - - /* istanbul ignore next */ //Not testable in PhantomJS - function fixHiddenIFrames() { - function checkIFrames() { - function checkIFrame( settingId ) { - function chkDimension( dimension ) { - return '0px' === settings[ settingId ].iframe.style[ dimension ]; - } - - function isVisible( el ) { - return ( null !== el.offsetParent ); - } - - if ( isVisible( settings[ settingId ].iframe ) && ( chkDimension( 'height' ) || chkDimension( 'width' ) ) ) { - trigger( 'Visibility change', 'resize', settings[ settingId ].iframe, settingId ); - } - } - - for ( const settingId in settings ) { - checkIFrame( settingId ); - } - } - - function mutationObserved( mutations ) { - log( 'window', 'Mutation observed: ' + mutations[ 0 ].target + ' ' + mutations[ 0 ].type ); - debouce( checkIFrames, 16 ); - } - - function createMutationObserver() { - let - target = document.querySelector( 'body' ), - - config = { - attributes: true, - attributeOldValue: false, - characterData: true, - characterDataOldValue: false, - childList: true, - subtree: true, - }, - - observer = new MutationObserver( mutationObserved ); - - observer.observe( target, config ); - } - - var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; - - if ( MutationObserver ) { - createMutationObserver(); - } - } - - function resizeIFrames( event ) { - function resize() { - sendTriggerMsg( 'Window ' + event, 'resize' ); - } - - log( 'window', 'Trigger event: ' + event ); - debouce( resize, 16 ); - } - - /* istanbul ignore next */ //Not testable in PhantomJS - function tabVisible() { - function resize() { - sendTriggerMsg( 'Tab Visable', 'resize' ); - } - - if ( 'hidden' !== document.visibilityState ) { - log( 'document', 'Trigger event: Visiblity change' ); - debouce( resize, 16 ); - } - } - - function sendTriggerMsg( eventName, event ) { - function isIFrameResizeEnabled( iframeId ) { - return 'parent' === settings[ iframeId ].resizeFrom && - settings[ iframeId ].autoResize && - ! settings[ iframeId ].firstRun; - } - - for ( const iframeId in settings ) { - if ( isIFrameResizeEnabled( iframeId ) ) { - trigger( eventName, event, document.getElementById( iframeId ), iframeId ); - } - } - } - - function setupEventListeners() { - addEventListener( window, 'message', iFrameListener ); - - addEventListener( window, 'resize', function() { - resizeIFrames( 'resize' ); - } ); - - addEventListener( document, 'visibilitychange', tabVisible ); - addEventListener( document, '-webkit-visibilitychange', tabVisible ); //Andriod 4.4 - addEventListener( window, 'focusin', function() { - resizeIFrames( 'focus' ); - } ); //IE8-9 - addEventListener( window, 'focus', function() { - resizeIFrames( 'focus' ); - } ); - } - - function factory() { - function init( options, element ) { - function chkType() { - if ( ! element.tagName ) { - throw new TypeError( 'Object is not a valid DOM element' ); - } else if ( 'IFRAME' !== element.tagName.toUpperCase() ) { - throw new TypeError( 'Expected