├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── dist ├── lifecycle.es5.js ├── lifecycle.es5.js.map ├── lifecycle.mjs ├── lifecycle.mjs.map ├── lifecycle.native.mjs └── lifecycle.native.mjs.map ├── package-lock.json ├── package.json ├── rollup.config.js ├── src ├── Lifecycle.mjs ├── StateChangeEvent.mjs ├── export.mjs ├── natives │ ├── Event.mjs │ └── EventTarget.mjs └── shims │ ├── Event.mjs │ ├── EventTarget.mjs │ └── support.mjs └── test ├── Lifecycle-test.mjs ├── export-test.mjs └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log 3 | .DS_Store 4 | 5 | test/test-bundle.js 6 | test/test-bundle.js.map 7 | 8 | demo 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ### 0.1.2 (2019-08-27) 4 | 5 | - Fix security issues in dependencies via npm audit 6 | 7 | ### 0.1.1 (2018-08-03) 8 | 9 | - Fix a bug due to Safari not dispatching the pagehide or visibilitychange events (#3) 10 | - Simplify the logic for `getCurrentState()` (#1) 11 | 12 | ### 0.1.0 (2018-06-27) 13 | 14 | - Initial public release 15 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution, 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows [Google's Open Source Community 28 | Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2018 Google, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PageLifecycle.js 2 | 3 | - [Overview](#overview) 4 | - [Installation](#installation) 5 | - [Usage](#usage) 6 | - [API](#api) 7 | - [Properties](#properties) 8 | - [Methods](#methods) 9 | - [Events](#events) 10 | - [Browser Support](#browser-support) 11 | 12 | 13 | ## Overview 14 | 15 | PageLifecycle.js is a tiny JavaScript library (<1K gzipped) that allows developers to easily observe [Page Lifecycle API](https://developers.google.com/web/updates/2018/07/page-lifecycle-api) state changes and implement [Page Lifecycle best practices](https://developers.google.com/web/updates/2018/07/page-lifecycle-api#developer-recommendations-for-each-state) consistently across all browsers. 16 | 17 | **▶️ View demo: [page-lifecycle.glitch.me](https://page-lifecycle.glitch.me/) 👀** 18 | 19 | ## Installation 20 | 21 | You can install this library from npm by running: 22 | 23 | ```sh 24 | npm install --save-dev page-lifecycle 25 | ``` 26 | 27 | ## Usage 28 | 29 | Releases of this library include three minified, production-ready versions: 30 | 31 | **1. ES5: [`dist/lifecycle.es5.js`](/dist/lifecycle.es5.js)** (UMD) ⭐ 32 | 33 | Use this version for maximum compatibility with legacy browsers (that can't run ES2015+ code). 34 | 35 | As a UMD bundle, it can be required in CommonJS or AMD environments, or it can be loaded with a script tag as the browser global `lifecycle`. 36 | 37 | ```html 38 | 39 | 44 | ``` 45 | 46 | **2. ES2015: [`dist/lifecycle.mjs`](/dist/lifecycle.mjs)** (ESM) 🔥 47 | 48 | Use this version if you only support ES module-capable browsers or if you're using ` 58 | ``` 59 | 60 | 61 | **3. ES2015 (native): [`dist/lifecycle.native.mjs`](/dist/lifecycle.native.mjs)** (ESM w/o `EventTarget` and `Event` shims) ⚠️ 62 | 63 | Use this version if you're only targeting browsers that [support extending `EventTarget` and `Event` constructors](https://www.chromestatus.com/features/5721972856061952). 64 | 65 | *Note: this version is the smallest but will only work in some browsers. The implementation instructions are the same as the ES2015 version above.* 66 | 67 | ## API 68 | 69 | The PageLifecycle.js library exports a `lifecycle` object, which is a singleton instance of the [`Lifecycle`](/src/Lifecycle.mjs) class. The `Lifecycle` class has the following properties, methods, and events: 70 | 71 | ### Properties 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 85 | 86 | 87 | 88 | 89 | 92 | 93 |
NameTypeDescription
statestring 83 | Returns the current Page Lifecycle state. 84 |
pageWasDiscardedboolean 90 | Returns the value of document.wasDiscarded (or false if not present). 91 |
94 | 95 | ### Methods 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 112 | 113 | 114 | 115 | 123 | 124 | 125 | 126 | 135 | 136 | 137 | 138 | 145 | 146 |
NameDescription
addEventListener 105 |

Parameters:

106 |
    107 |
  • type: string
  • 108 |
  • listener: function(Event)
  • 109 |
110 |

Adds a callback function to be invoked whenever the passed event type is detected. (Note: at the moment only the "statechange" event type is supported.)

111 |
removeEventListener 116 |

Parameters:

117 |
    118 |
  • type: string
  • 119 |
  • listener: function(Event)
  • 120 |
121 |

Removes a function from the current list of listeners for the passed event type. (Note: at the moment only the "statechange" event type is supported.)

122 |
addUnsavedChanges 127 |

Parameters:

128 |
    129 |
  • id: Object|Symbol
  • 130 |
131 |

Adds an item to an internal pending-changes stack. Calling this method adds a generic beforeunload listener to the window (if one isn't already added).

132 |

The argument passed should be unique to this state, as it can only be removed by passing the same argument to removeUnsavedChanges(). 133 |

134 |
removeUnsavedChanges 139 |

Parameters:

140 |
    141 |
  • id: Object|Symbol
  • 142 |
143 |

Removes an item matching the passed argument from an internal pending-changes stack. If the stack is empty, the generic beforeunload listener is removed from the window.

144 |
147 | 148 | ### Events 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 166 | 167 |
NameDescription
statechange 158 |

Properties:

159 |
    160 |
  • newState: string The current lifecycle state the page just transitioned to.
  • 161 |
  • oldState: string The previous lifecycle state the page just transitioned from.
  • 162 |
  • originalEvent: Event the DOM event that triggered the state change.
  • 163 |
164 |

The statechange event is fired whenever the page's lifecycle state changes.

165 |
168 | 169 | 170 | ## Browser Support 171 | 172 | 173 | 174 | 178 | 182 | 186 | 190 | 194 | 198 | 199 |
175 | Chrome
176 | ✔ 177 |
179 | Firefox
180 | ✔ 181 |
183 | Safari
184 | ✔ 185 |
187 | Edge
188 | ✔ 189 |
191 | Internet Explorer
192 | 9+ 193 |
195 | Opera
196 | ✔ 197 |
200 | 201 | PageLifecycle.js has been tested and known to work in the above browsers. 202 | -------------------------------------------------------------------------------- /dist/lifecycle.es5.js: -------------------------------------------------------------------------------- 1 | /*! 2 | Copyright 2018 Google Inc. All Rights Reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | /*! lifecycle.es5.js v0.1.1 */ 16 | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.lifecycle=t()}(this,function(){"use strict";var e=void 0;try{new EventTarget,e=!1}catch(t){e=!1}var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=function(){function e(e,t){for(var n=0;n-1&&n.splice(i,1)}},{key:"dispatchEvent",value:function(e){return e.target=this,Object.freeze(e),this._getRegistry(e.type).forEach(function(t){return t(e)}),!0}},{key:"_getRegistry",value:function(e){return this._registry[e]=this._registry[e]||[]}}]),e}(),o=e?EventTarget:s,u=e?Event:function e(t){n(this,e),this.type=t},f=function(e){function t(e,i){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.newState=i.newState,r.oldState=i.oldState,r.originalEvent=i.originalEvent,r}return r(t,u),t}(),c="active",h="passive",d="hidden",l="frozen",p="terminated",v="object"===("undefined"==typeof safari?"undefined":t(safari))&&safari.pushNotification,y=["focus","blur","visibilitychange","freeze","resume","pageshow","onpageshow"in self?"pagehide":"unload"],g=function(e){return e.preventDefault(),e.returnValue="Are you sure?"},_=[[c,h,d,p],[c,h,d,l],[d,h,c],[l,d],[l,c],[l,h]].map(function(e){return e.reduce(function(e,t,n){return e[t]=n,e},{})}),b=function(){return document.visibilityState===d?d:document.hasFocus()?c:h};return new(function(e){function t(){n(this,t);var e=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this)),i=b();return e._state=i,e._unsavedChanges=[],e._handleEvents=e._handleEvents.bind(e),y.forEach(function(t){return addEventListener(t,e._handleEvents,!0)}),v&&addEventListener("beforeunload",function(t){e._safariBeforeUnloadTimeout=setTimeout(function(){t.defaultPrevented||t.returnValue.length>0||e._dispatchChangesIfNeeded(t,d)},0)}),e}return r(t,o),i(t,[{key:"addUnsavedChanges",value:function(e){!this._unsavedChanges.indexOf(e)>-1&&(0===this._unsavedChanges.length&&addEventListener("beforeunload",g),this._unsavedChanges.push(e))}},{key:"removeUnsavedChanges",value:function(e){var t=this._unsavedChanges.indexOf(e);t>-1&&(this._unsavedChanges.splice(t,1),0===this._unsavedChanges.length&&removeEventListener("beforeunload",g))}},{key:"_dispatchChangesIfNeeded",value:function(e,t){if(t!==this._state)for(var n=function(e,t){for(var n,i=0;n=_[i];++i){var r=n[e],a=n[t];if(r>=0&&a>=0&&a>r)return Object.keys(n).slice(r,a+1)}return[]}(this._state,t),i=0;i -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,EAAMe,4EACVf,aACDgB,SAAWD,EAASC,WACpBC,SAAWF,EAASE,WACpBC,cAAgBH,EAASG,2BATYL,QCFxCM,EAAS,SACTC,EAAU,UACVC,EAAS,SACTC,EAAS,SAETC,EAAa,aAGbC,EAA8B,gCAAXC,qBAAAA,UAAuBA,OAAOC,iBAIjDC,GACJ,QACA,OACA,mBACA,SACA,SACA,WARsC,eAAgBC,KAYpB,WAAa,UAO3CC,EAAiB,SAACpB,YAClBqB,iBACGrB,EAAIsB,YAAc,iBAiBrBC,IAEHb,EAAQC,EAASC,EAAQE,IAIzBJ,EAAQC,EAASC,EAAQC,IAGzBD,EAAQD,EAASD,IAGjBG,EAAQD,IAIRC,EAAQH,IACRG,EAAQF,IACTa,IA1BsB,SAACC,UAAQA,EAAIC,OA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AAK8B,eAEhC,aACEe,yBAAyB7C,EAAKU,aAEhC,OAGCd,KAAKuC,SAAWzB,QACbmC,yBAAyB7C,EAAK8B,eAGlC,eACA,cACEe,yBAAyB7C,EAAKA,EAAI0D,UAAY7C,EAASC,aAEzD,mBAIClB,KAAKuC,SAAWtB,GAChBjB,KAAKuC,SAAWrB,QACb+B,yBAAyB7C,EAAK8B,eAGlC,cACEe,yBAAyB7C,EAAKa,yCA7GhCjB,KAAKuC,uDAULJ,SAAS4B,eAAgB"} -------------------------------------------------------------------------------- /dist/lifecycle.mjs: -------------------------------------------------------------------------------- 1 | /*! 2 | Copyright 2018 Google Inc. All Rights Reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | /*! lifecycle.mjs v0.1.1 */ 16 | let e;try{new EventTarget,e=!0}catch(t){e=!1}class t{constructor(){this.e={}}addEventListener(e,t,s=!1){this.t(e).push(t)}removeEventListener(e,t,s=!1){const i=this.t(e),a=i.indexOf(t);a>-1&&i.splice(a,1)}dispatchEvent(e){return e.target=this,Object.freeze(e),this.t(e.type).forEach(t=>t(e)),!0}t(e){return this.e[e]=this.e[e]||[]}}var s=e?EventTarget:t;class i{constructor(e){this.type=e}}var a=e?Event:i;class n extends a{constructor(e,t){super(e),this.newState=t.newState,this.oldState=t.oldState,this.originalEvent=t.originalEvent}}const r="active",h="passive",c="hidden",o="frozen",d="terminated",u="object"==typeof safari&&safari.pushNotification,v="onpageshow"in self,l=["focus","blur","visibilitychange","freeze","resume","pageshow",v?"pagehide":"unload"],g=e=>(e.preventDefault(),e.returnValue="Are you sure?"),f=e=>e.reduce((e,t,s)=>(e[t]=s,e),{}),b=[[r,h,c,d],[r,h,c,o],[c,h,r],[o,c],[o,r],[o,h]].map(f),p=(e,t)=>{for(let s,i=0;s=b[i];++i){const i=s[e],a=s[t];if(i>=0&&a>=0&&a>i)return Object.keys(s).slice(i,a+1)}return[]},E=()=>document.visibilityState===c?c:document.hasFocus()?r:h;class m extends s{constructor(){super();const e=E();this.s=e,this.i=[],this.a=this.a.bind(this),l.forEach(e=>addEventListener(e,this.a,!0)),u&&addEventListener("beforeunload",e=>{this.n=setTimeout(()=>{e.defaultPrevented||e.returnValue.length>0||this.r(e,c)},0)})}get state(){return this.s}get pageWasDiscarded(){return document.wasDiscarded||!1}addUnsavedChanges(e){!this.i.indexOf(e)>-1&&(0===this.i.length&&addEventListener("beforeunload",g),this.i.push(e))}removeUnsavedChanges(e){const t=this.i.indexOf(e);t>-1&&(this.i.splice(t,1),0===this.i.length&&removeEventListener("beforeunload",g))}r(e,t){if(t!==this.s){const s=this.s,i=p(s,t);for(let t=0;t -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","[object Object]","this","_registry","type","listener","opts","_getRegistry","push","typeRegistry","handlerIndex","indexOf","splice","evt","target","Object","freeze","forEach","EventShim","Event","StateChangeEvent","initDict","super","newState","oldState","originalEvent","ACTIVE","PASSIVE","HIDDEN","FROZEN","TERMINATED","IS_SAFARI","safari","pushNotification","SUPPORTS_PAGE_TRANSITION_EVENTS","self","EVENTS","onbeforeunload","preventDefault","returnValue","toIndexedObject","arr","reduce","acc","val","idx","LEGAL_STATE_TRANSITIONS","map","getLegalStateTransitionPath","order","i","oldIndex","newIndex","keys","slice","getCurrentState","document","visibilityState","hasFocus","Lifecycle","state","_state","_unsavedChanges","_handleEvents","bind","addEventListener","_safariBeforeUnloadTimeout","setTimeout","defaultPrevented","length","_dispatchChangesIfNeeded","pageWasDiscarded","wasDiscarded","id","idIndex","removeEventListener","path","dispatchEvent","clearTimeout","persisted"],"mappings":";;;;;;;;;;;;;;;AAeA,IAAIA,EAEJ,IACE,IAAIC,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AK,IAAI2B,EAAI,EAAGA,EAAI0B,EAAKP,OAAS,IAAKnB,EAAG,CACxC,MAAM1B,EAAWoD,EAAK1B,GAChB3B,EAAWqD,EAAK1B,EAAI,GAE1BhD,KAAK2D,EAAStC,EACdrB,KAAK2E,cAAc,IAAIzD,EAAiB,eACtCI,SAAAA,EACAD,SAAAA,EACAE,cAAAA,OAURxB,EAAcY,GAKZ,OAJIkB,GACF+C,aAAa5E,KAAKgE,GAGZrD,EAAIT,MACV,IAAK,WACL,IAAK,SACHF,KAAKoE,EAAyBzD,EAAK0C,KACnC,MACF,IAAK,QACHrD,KAAKoE,EAAyBzD,EAAKa,GACnC,MACF,IAAK,OAGCxB,KAAK2D,IAAWnC,GAClBxB,KAAKoE,EAAyBzD,EAAK0C,KAErC,MACF,IAAK,WACL,IAAK,SACHrD,KAAKoE,EAAyBzD,EAAKA,EAAIkE,UAAYlD,EAASC,GAC5D,MACF,IAAK,mBAIC5B,KAAK2D,IAAWhC,GAChB3B,KAAK2D,IAAW/B,GAClB5B,KAAKoE,EAAyBzD,EAAK0C,KAErC,MACF,IAAK,SACHrD,KAAKoE,EAAyBzD,EAAKgB,KC3Q3C,MAAe,IAAI8B"} -------------------------------------------------------------------------------- /dist/lifecycle.native.mjs: -------------------------------------------------------------------------------- 1 | /*! 2 | Copyright 2018 Google Inc. All Rights Reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | /*! lifecycle.native.mjs v0.1.1 */ 16 | class e extends Event{constructor(e,t){super(e),this.newState=t.newState,this.oldState=t.oldState,this.originalEvent=t.originalEvent}}const t="active",s="passive",i="hidden",a="frozen",n="terminated",r="object"==typeof safari&&safari.pushNotification,h="onpageshow"in self,o=["focus","blur","visibilitychange","freeze","resume","pageshow",h?"pagehide":"unload"],c=e=>(e.preventDefault(),e.returnValue="Are you sure?"),d=e=>e.reduce((e,t,s)=>(e[t]=s,e),{}),u=[[t,s,i,n],[t,s,i,a],[i,s,t],[a,i],[a,t],[a,s]].map(d),l=(e,t)=>{for(let s,i=0;s=u[i];++i){const i=s[e],a=s[t];if(i>=0&&a>=0&&a>i)return Object.keys(s).slice(i,a+1)}return[]},f=()=>document.visibilityState===i?i:document.hasFocus()?t:s;class v extends EventTarget{constructor(){super();const e=f();this.e=e,this.t=[],this.s=this.s.bind(this),o.forEach(e=>addEventListener(e,this.s,!0)),r&&addEventListener("beforeunload",e=>{this.i=setTimeout(()=>{e.defaultPrevented||e.returnValue.length>0||this.a(e,i)},0)})}get state(){return this.e}get pageWasDiscarded(){return document.wasDiscarded||!1}addUnsavedChanges(e){!this.t.indexOf(e)>-1&&(0===this.t.length&&addEventListener("beforeunload",c),this.t.push(e))}removeUnsavedChanges(e){const t=this.t.indexOf(e);t>-1&&(this.t.splice(t,1),0===this.t.length&&removeEventListener("beforeunload",c))}a(t,s){if(s!==this.e){const i=this.e,a=l(i,s);for(let s=0;s