{"version":3,"file":"lifecycle.es5.js","sources":["src/shims/support.mjs","src/shims/EventTarget.mjs","src/shims/Event.mjs","src/StateChangeEvent.mjs","src/Lifecycle.mjs","src/export.mjs"],"sourcesContent":["/*\n Copyright 2018 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\nlet supportsConstructableEventTarget;\n\ntry {\n new EventTarget();\n\n // When transpiled with babel and rollup, the `IS_CODE_TRANSPILED` constant\n // is replaced with the boolean `true`, so this statement will always\n // evaluate to `false`. When not transpiled, it will be true.\n supportsConstructableEventTarget = typeof IS_CODE_TRANSPILED === 'undefined';\n} catch (err) {\n supportsConstructableEventTarget = false;\n}\n\nexport {supportsConstructableEventTarget};\n","/*\n Copyright 2018 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\nimport {supportsConstructableEventTarget} from './support.mjs';\n\n\n/**\n * A minimal EventTarget class shim.\n * This is used if the browser doesn't natively support constructable\n * EventTarget objects.\n */\nclass EventTargetShim {\n /**\n * Creates the event registry.\n */\n constructor() {\n this._registry = {};\n }\n\n /**\n * @param {string} type\n * @param {EventListener|function(!Event):(boolean|undefined)} listener\n * @param {(boolean|!AddEventListenerOptions)=} opts\n * @return {undefined}\n * @see https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener\n */\n addEventListener(type, listener, opts = false) {\n this._getRegistry(type).push(listener);\n }\n\n /**\n * @param {string} type\n * @param {EventListener|function(!Event):(boolean|undefined)} listener\n * @param {(boolean|!EventListenerOptions)=} opts\n * @return {undefined}\n * @see https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener\n */\n removeEventListener(type, listener, opts = false) {\n const typeRegistry = this._getRegistry(type);\n const handlerIndex = typeRegistry.indexOf(listener);\n if (handlerIndex > -1) {\n typeRegistry.splice(handlerIndex, 1);\n }\n }\n\n /**\n * @param {!Event|!EventShim} evt\n * @return {boolean}\n * @see https://dom.spec.whatwg.org/#dom-eventtarget-dispatchevent\n */\n dispatchEvent(evt) {\n // Set the target then freeze the event object to prevent modification.\n evt.target = this;\n Object.freeze(evt);\n\n this._getRegistry(evt.type).forEach((listener) => listener(evt));\n return true;\n }\n\n /**\n * Returns an array of handlers associated with the passed event type.\n * If no handlers have been registered, an empty array is returned.\n * @private\n * @param {string} type The event type.\n * @return {!Array} An array of handler functions.\n */\n _getRegistry(type) {\n return this._registry[type] = (this._registry[type] || []);\n }\n}\n\nexport default supportsConstructableEventTarget ? EventTarget : EventTargetShim;\n","/*\n Copyright 2018 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\nimport {supportsConstructableEventTarget} from './support.mjs';\n\n/**\n * A minimal Event class shim.\n * This is used if the browser doesn't natively support constructable\n * EventTarget objects.\n */\nclass EventShim {\n /**\n * @param {string} type\n */\n constructor(type) {\n this.type = type;\n }\n}\n\nexport default supportsConstructableEventTarget ? Event : EventShim;\n","/*\n Copyright 2018 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\nimport Event from './shims/Event.mjs';\n\n/**\n * implements {IStateChangeEvent}\n */\nexport default class StateChangeEvent extends Event {\n /**\n * @param {string} type\n * @param {!Object} initDict\n */\n constructor(type, initDict) {\n super(type);\n this.newState = initDict.newState;\n this.oldState = initDict.oldState;\n this.originalEvent = initDict.originalEvent;\n }\n}\n","/*\n Copyright 2018 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\nimport EventTarget from './shims/EventTarget.mjs';\nimport StateChangeEvent from './StateChangeEvent.mjs';\n\nconst ACTIVE = 'active';\nconst PASSIVE = 'passive';\nconst HIDDEN = 'hidden';\nconst FROZEN = 'frozen';\n// const DISCARDED = 'discarded'; Not used but show to completeness.\nconst TERMINATED = 'terminated';\n\n// Detect Safari to work around Safari-specific bugs.\nconst IS_SAFARI = typeof safari === 'object' && safari.pushNotification;\n\nconst SUPPORTS_PAGE_TRANSITION_EVENTS = 'onpageshow' in self;\n\nconst EVENTS = [\n 'focus',\n 'blur',\n 'visibilitychange',\n 'freeze',\n 'resume',\n 'pageshow',\n // IE9-10 do not support the pagehide event, so we fall back to unload\n // Note: unload *MUST ONLY* be added conditionally, otherwise it will\n // prevent page navigation caching (a.k.a bfcache).\n SUPPORTS_PAGE_TRANSITION_EVENTS ? 'pagehide' : 'unload',\n];\n\n/**\n * @param {!Event} evt\n * @return {string}\n */\nconst onbeforeunload = (evt) => {\n evt.preventDefault();\n return evt.returnValue = 'Are you sure?';\n};\n\n/**\n * Converts an array of states into an object where the state is the key\n * and the value is the index.\n * @param {!Array} arr\n * @return {!Object}\n */\nconst toIndexedObject = (arr) => arr.reduce((acc, val, idx) => {\n acc[val] = idx;\n return acc;\n}, {});\n\n/**\n * @type {!Array}\n */\nconst LEGAL_STATE_TRANSITIONS = [\n // The normal unload process (bfcache process is addressed above).\n [ACTIVE, PASSIVE, HIDDEN, TERMINATED],\n\n // An active page transitioning to frozen,\n // or an unloading page going into the bfcache.\n [ACTIVE, PASSIVE, HIDDEN, FROZEN],\n\n // A hidden page transitioning back to active.\n [HIDDEN, PASSIVE, ACTIVE],\n\n // A frozen page being resumed\n [FROZEN, HIDDEN],\n\n // A frozen (bfcached) page navigated back to\n // Note: [FROZEN, HIDDEN] can happen here, but it's already covered above.\n [FROZEN, ACTIVE],\n [FROZEN, PASSIVE],\n].map(toIndexedObject);\n\n/**\n * Accepts a current state and a future state and returns an array of legal\n * state transition paths. This is needed to normalize behavior across browsers\n * since some browsers do not fire events in certain cases and thus skip\n * states.\n * @param {string} oldState\n * @param {string} newState\n * @return {!Array}\n */\nconst getLegalStateTransitionPath = (oldState, newState) => {\n // We're intentionally not using for...of here so when we transpile to ES5\n // we don't need to include the Symbol polyfills.\n for (let order, i = 0; order = LEGAL_STATE_TRANSITIONS[i]; ++i) {\n const oldIndex = order[oldState];\n const newIndex = order[newState];\n\n if (oldIndex >= 0 &&\n newIndex >= 0 &&\n newIndex > oldIndex) {\n // Differences greater than one should be reported\n // because it means a state was skipped.\n return Object.keys(order).slice(oldIndex, newIndex + 1);\n }\n }\n return [];\n // TODO(philipwalton): it shouldn't be possible to get here, but\n // consider some kind of warning or call to action if it happens.\n // console.warn(`Invalid state change detected: ${oldState} > ${newState}`);\n};\n\n/**\n * Returns the current state based on the document's visibility and\n * in input focus states. Note this method is only used to determine\n * active vs passive vs hidden states, as other states require listening\n * for events.\n * @return {string}\n */\nconst getCurrentState = () => {\n if (document.visibilityState === HIDDEN) {\n return HIDDEN;\n }\n if (document.hasFocus()) {\n return ACTIVE;\n }\n return PASSIVE;\n};\n\n/**\n * Class definition for the exported, singleton lifecycle instance.\n */\nexport default class Lifecycle extends EventTarget {\n /**\n * Initializes state, state history, and adds event listeners to monitor\n * state changes.\n */\n constructor() {\n super();\n\n const state = getCurrentState();\n\n this._state = state;\n this._unsavedChanges = [];\n\n // Bind the callback and add event listeners.\n this._handleEvents = this._handleEvents.bind(this);\n\n // Add capturing events on window so they run immediately.\n EVENTS.forEach((evt) => addEventListener(evt, this._handleEvents, true));\n\n // Safari does not reliably fire the `pagehide` or `visibilitychange`\n // events when closing a tab, so we have to use `beforeunload` with a\n // timeout to check whether the default action was prevented.\n // NOTE: we only add this to Safari because adding it to Firefox would\n // prevent the page from being eligible for bfcache.\n if (IS_SAFARI) {\n addEventListener('beforeunload', (evt) => {\n this._safariBeforeUnloadTimeout = setTimeout(() => {\n if (!(evt.defaultPrevented || evt.returnValue.length > 0)) {\n this._dispatchChangesIfNeeded(evt, HIDDEN);\n }\n }, 0);\n });\n }\n }\n\n /**\n * @return {string}\n */\n get state() {\n return this._state;\n }\n\n /**\n * Returns the value of document.wasDiscarded. This is arguably unnecessary\n * but I think there's value in having the entire API in one place and\n * consistent across browsers.\n * @return {boolean}\n */\n get pageWasDiscarded() {\n return document.wasDiscarded || false;\n }\n\n /**\n * @param {Symbol|Object} id A unique symbol or object identifying the\n *. pending state. This ID is required when removing the state later.\n */\n addUnsavedChanges(id) {\n // Don't add duplicate state. Note: ideall this would be a set, but for\n // better browser compatibility we're using an array.\n if (!this._unsavedChanges.indexOf(id) > -1) {\n // If this is the first state being added,\n // also add a beforeunload listener.\n if (this._unsavedChanges.length === 0) {\n addEventListener('beforeunload', onbeforeunload);\n }\n this._unsavedChanges.push(id);\n }\n }\n\n /**\n * @param {Symbol|Object} id A unique symbol or object identifying the\n *. pending state. This ID is required when removing the state later.\n */\n removeUnsavedChanges(id) {\n const idIndex = this._unsavedChanges.indexOf(id);\n\n if (idIndex > -1) {\n this._unsavedChanges.splice(idIndex, 1);\n\n // If there's no more pending state, remove the event listener.\n if (this._unsavedChanges.length === 0) {\n removeEventListener('beforeunload', onbeforeunload);\n }\n }\n }\n\n /**\n * @private\n * @param {!Event} originalEvent\n * @param {string} newState\n */\n _dispatchChangesIfNeeded(originalEvent, newState) {\n if (newState !== this._state) {\n const oldState = this._state;\n const path = getLegalStateTransitionPath(oldState, newState);\n\n for (let i = 0; i < path.length - 1; ++i) {\n const oldState = path[i];\n const newState = path[i + 1];\n\n this._state = newState;\n this.dispatchEvent(new StateChangeEvent('statechange', {\n oldState,\n newState,\n originalEvent,\n }));\n }\n }\n }\n\n /**\n * @private\n * @param {!Event} evt\n */\n _handleEvents(evt) {\n if (IS_SAFARI) {\n clearTimeout(this._safariBeforeUnloadTimeout);\n }\n\n switch (evt.type) {\n case 'pageshow':\n case 'resume':\n this._dispatchChangesIfNeeded(evt, getCurrentState());\n break;\n case 'focus':\n this._dispatchChangesIfNeeded(evt, ACTIVE);\n break;\n case 'blur':\n // The `blur` event can fire while the page is being unloaded, so we\n // only need to update the state if the current state is \"active\".\n if (this._state === ACTIVE) {\n this._dispatchChangesIfNeeded(evt, getCurrentState());\n }\n break;\n case 'pagehide':\n case 'unload':\n this._dispatchChangesIfNeeded(evt, evt.persisted ? FROZEN : TERMINATED);\n break;\n case 'visibilitychange':\n // The document's `visibilityState` will change to hidden as the page\n // is being unloaded, but in such cases the lifecycle state shouldn't\n // change.\n if (this._state !== FROZEN &&\n this._state !== TERMINATED) {\n this._dispatchChangesIfNeeded(evt, getCurrentState());\n }\n break;\n case 'freeze':\n this._dispatchChangesIfNeeded(evt, FROZEN);\n break;\n }\n }\n}\n","/*\n Copyright 2018 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\nimport Lifecycle from './Lifecycle.mjs';\n\nexport default new Lifecycle();\n"],"names":["supportsConstructableEventTarget","EventTarget","err","EventTargetShim","_registry","type","listener","_getRegistry","push","typeRegistry","this","handlerIndex","indexOf","splice","evt","target","freeze","forEach","Event","StateChangeEvent","initDict","newState","oldState","originalEvent","ACTIVE","PASSIVE","HIDDEN","FROZEN","TERMINATED","IS_SAFARI","safari","pushNotification","EVENTS","self","onbeforeunload","preventDefault","returnValue","LEGAL_STATE_TRANSITIONS","map","arr","reduce","acc","val","idx","getCurrentState","document","visibilityState","hasFocus","state","_state","_unsavedChanges","_handleEvents","_this","bind","addEventListener","_safariBeforeUnloadTimeout","setTimeout","defaultPrevented","length","_dispatchChangesIfNeeded","id","idIndex","path","order","i","oldIndex","newIndex","Object","keys","slice","getLegalStateTransitionPath","dispatchEvent","persisted","wasDiscarded"],"mappings":";;;;;;;;;;;;;;;qLAeA,IAAIA,SAEJ,QACMC,eAK+B,EACnC,MAAOC,MAC4B,sgCCF/BC,yCAKGC,gEAUUC,EAAMC,QAChBC,aAAaF,GAAMG,KAAKF,+CAUXD,EAAMC,OAClBG,EAAeC,KAAKH,aAAaF,GACjCM,EAAeF,EAAaG,QAAQN,GACtCK,GAAgB,KACLE,OAAOF,EAAc,yCASxBG,YAERC,OAASL,YACNM,OAAOF,QAETP,aAAaO,EAAIT,MAAMY,QAAQ,SAACX,UAAaA,EAASQ,MACpD,uCAUIT,UACJK,KAAKN,UAAUC,GAASK,KAAKN,UAAUC,kBAInCL,EAAmCC,YAAcE,ICpDjDH,EAAmCkB,MALhD,WAAYb,kBACLA,KAAOA,GCPKc,yBAKPd,EAA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