├── .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 |
Name
76 |
Type
77 |
Description
78 |
79 |
80 |
state
81 |
string
82 |
83 | Returns the current Page Lifecycle state.
84 |
85 |
86 |
87 |
pageWasDiscarded
88 |
boolean
89 |
90 | Returns the value of document.wasDiscarded (or false if not present).
91 |
92 |
93 |
94 |
95 | ### Methods
96 |
97 |
98 |
99 |
Name
100 |
Description
101 |
102 |
103 |
addEventListener
104 |
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 |
112 |
113 |
114 |
removeEventListener
115 |
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 |
123 |
124 |
125 |
addUnsavedChanges
126 |
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 |
135 |
136 |
137 |
removeUnsavedChanges
138 |
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 |
145 |
146 |
147 |
148 | ### Events
149 |
150 |
151 |
152 |
Name
153 |
Description
154 |
155 |
156 |
statechange
157 |
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 |
166 |
167 |
168 |
169 |
170 | ## Browser Support
171 |
172 |
173 |
174 |
175 |
176 | ✔
177 |
178 |
179 |
180 | ✔
181 |
182 |
183 |
184 | ✔
185 |
186 |
187 |
188 | ✔
189 |
190 |
191 |
192 | 9+
193 |
194 |
195 |
196 | ✔
197 |
198 |
199 |
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,OAAO,SAACC,EAAKC,EAAKC,YACjDD,GAAOC,EACJF,SA+DHG,EAAkB,kBAClBC,SAASC,kBAAoBpB,EACxBA,EAELmB,SAASE,WACJvB,EAEFC,UCjHM,wGD+HLuB,EAAQJ,aAETK,OAASD,IACTE,qBAGAC,cAAgBC,EAAKD,cAAcE,UAGjCpC,QAAQ,SAACH,UAAQwC,iBAAiBxC,EAAKsC,EAAKD,eAAe,KAO9DtB,oBACe,eAAgB,SAACf,KAC3ByC,2BAA6BC,WAAW,WACrC1C,EAAI2C,kBAAoB3C,EAAIsB,YAAYsB,OAAS,KAChDC,yBAAyB7C,EAAKY,IAEpC,kBA9B4BzB,gDAwDnB2D,IAGXlD,KAAKwC,gBAAgBtC,QAAQgD,IAAO,IAGH,IAAhClD,KAAKwC,gBAAgBQ,yBACN,eAAgBxB,QAE9BgB,gBAAgB1C,KAAKoD,iDAQTA,OACbC,EAAUnD,KAAKwC,gBAAgBtC,QAAQgD,GAEzCC,GAAW,SACRX,gBAAgBrC,OAAOgD,EAAS,GAGD,IAAhCnD,KAAKwC,gBAAgBQ,4BACH,eAAgBxB,qDAUjBX,EAAeF,MAClCA,IAAaX,KAAKuC,eAEda,EAvIwB,SAACxC,EAAUD,OAGxC,IAAI0C,EAAOC,EAAI,EAAGD,EAAQ1B,EAAwB2B,KAAMA,EAAG,KACxDC,EAAWF,EAAMzC,GACjB4C,EAAWH,EAAM1C,MAEnB4C,GAAY,GACZC,GAAY,GACZA,EAAWD,SAGNE,OAAOC,KAAKL,GAAOM,MAAMJ,EAAUC,EAAW,YA2HxCI,CADI5D,KAAKuC,OAC6B5B,GAE1C2C,EAAI,EAAGA,EAAIF,EAAKJ,OAAS,IAAKM,EAAG,KAClC1C,EAAWwC,EAAKE,GAChB3C,EAAWyC,EAAKE,EAAI,QAErBf,OAAS5B,OACTkD,cAAc,IAAIpD,EAAiB,+FAahCL,UACRe,gBACWnB,KAAK6C,4BAGZzC,EAAIT,UACL,eACA,cACEsD,yBAAyB7C,EAAK8B,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":"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"}
--------------------------------------------------------------------------------
/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 {\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":["StateChangeEvent","Event","[object Object]","type","initDict","super","this","newState","oldState","originalEvent","ACTIVE","PASSIVE","HIDDEN","FROZEN","TERMINATED","IS_SAFARI","safari","pushNotification","SUPPORTS_PAGE_TRANSITION_EVENTS","self","EVENTS","onbeforeunload","evt","preventDefault","returnValue","toIndexedObject","arr","reduce","acc","val","idx","LEGAL_STATE_TRANSITIONS","map","getLegalStateTransitionPath","order","i","oldIndex","newIndex","Object","keys","slice","getCurrentState","document","visibilityState","hasFocus","Lifecycle","EventTarget","state","_state","_unsavedChanges","_handleEvents","bind","forEach","addEventListener","_safariBeforeUnloadTimeout","setTimeout","defaultPrevented","length","_dispatchChangesIfNeeded","pageWasDiscarded","wasDiscarded","id","indexOf","push","idIndex","splice","removeEventListener","path","dispatchEvent","clearTimeout","persisted"],"mappings":"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"}
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "page-lifecycle",
3 | "version": "0.1.2",
4 | "description": "A JavaScript library to observe Page Lifecycle API states: https://github.com/WICG/page-lifecycle",
5 | "license": "Apache-2.0",
6 | "main": "dist/lifecycle.es5.js",
7 | "module": "dist/lifecycle.mjs",
8 | "scripts": {
9 | "test": "eslint *.js src/**/* test/*.mjs",
10 | "build": "rollup -c"
11 | },
12 | "repository": {
13 | "type": "git",
14 | "url": "https://github.com/GoogleChromeLabs/page-lifecycle.git"
15 | },
16 | "bugs": {
17 | "url": "https://github.com/GoogleChromeLabs/page-lifecycle/issues"
18 | },
19 | "homepage": "https://github.com/GoogleChromeLabs/page-lifecycle#readme",
20 | "keywords": [
21 | "page",
22 | "lifecycle",
23 | "unload",
24 | "beforeunload",
25 | "visibilityState",
26 | "visibilitychange",
27 | "active",
28 | "passive",
29 | "hidden",
30 | "frozen",
31 | "discarded",
32 | "terminated"
33 | ],
34 | "author": {
35 | "name": "Philip Walton",
36 | "email": "philip@philipwalton.com",
37 | "url": "http://philipwalton.com"
38 | },
39 | "devDependencies": {
40 | "babel-core": "^6.26.3",
41 | "babel-plugin-external-helpers": "^6.22.0",
42 | "babel-preset-env": "^1.7.0",
43 | "eslint": "^6.2.2",
44 | "eslint-config-google": "^0.13.0",
45 | "rollup": "^1.20.2",
46 | "rollup-plugin-babel": "^4.3.3",
47 | "rollup-plugin-multi-entry": "^2.1.0",
48 | "rollup-plugin-replace": "^2.2.0",
49 | "rollup-plugin-terser": "^5.1.1"
50 | },
51 | "eslintConfig": {
52 | "root": true,
53 | "env": {
54 | "browser": true,
55 | "es6": true,
56 | "node": true,
57 | "mocha": true
58 | },
59 | "globals": {
60 | "assert": false,
61 | "sinon": false,
62 | "safari": false
63 | },
64 | "parserOptions": {
65 | "ecmaVersion": 2018,
66 | "sourceType": "module"
67 | },
68 | "extends": [
69 | "eslint:recommended",
70 | "google"
71 | ]
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/rollup.config.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 |
16 | const path = require('path');
17 | const babel = require('rollup-plugin-babel');
18 | const multiEntry = require('rollup-plugin-multi-entry');
19 | const replace = require('rollup-plugin-replace');
20 | const {terser} = require('rollup-plugin-terser');
21 |
22 |
23 | const pkg = require('./package.json');
24 |
25 | const BANNER = `/*!
26 | Copyright 2018 Google Inc. All Rights Reserved.
27 | Licensed under the Apache License, Version 2.0 (the "License");
28 | you may not use this file except in compliance with the License.
29 | You may obtain a copy of the License at
30 |
31 | http://www.apache.org/licenses/LICENSE-2.0
32 |
33 | Unless required by applicable law or agreed to in writing, software
34 | distributed under the License is distributed on an "AS IS" BASIS,
35 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
36 | See the License for the specific language governing permissions and
37 | limitations under the License.
38 | */`;
39 |
40 | const generateBundleOpts = (file, {transpile, useNatives} = {}) => {
41 | const plugins = [];
42 |
43 | if (useNatives) {
44 | plugins.push({
45 | resolveId: (importee, importer) => {
46 | if (importee.includes('/shims/')) {
47 | return path.resolve(
48 | path.dirname(importer),
49 | importee.replace('/shims/', '/natives/'));
50 | }
51 | },
52 | });
53 | }
54 |
55 | if (transpile) {
56 | plugins.push(replace({
57 | 'IS_CODE_TRANSPILED': JSON.stringify(true),
58 | }));
59 | plugins.push(babel({
60 | presets: [['env', {modules: false}]],
61 | plugins: ['external-helpers'],
62 | }));
63 | } else {
64 | plugins.push(replace({
65 | 'IS_CODE_TRANSPILED': JSON.stringify(undefined),
66 | }));
67 | }
68 |
69 | const terserOpts = {
70 | output: {
71 | comments: /^!/,
72 | },
73 | compress: true,
74 | mangle: {
75 | toplevel: true,
76 | },
77 | };
78 | if (!transpile) {
79 | // Mangling properties doesn't work with the class transformations done
80 | // by Babel, since Babel defines class methods using their string names
81 | // .(passed to `Object.defineProperty()`) and strings are not minifed
82 | // by terser.
83 | terserOpts.mangle.properties = {
84 | regex: /^_/,
85 | };
86 | }
87 | plugins.push(terser(terserOpts));
88 |
89 | return {
90 | input: 'src/export.mjs',
91 | output: {
92 | file,
93 | format: transpile ? 'umd' : 'es',
94 | dir: 'dist',
95 | name: 'lifecycle',
96 | banner: `${BANNER}\n\n/*! ${file} v${pkg.version} */\n`,
97 | sourcemap: true,
98 | },
99 | plugins,
100 | };
101 | };
102 |
103 | module.exports = [
104 | generateBundleOpts('lifecycle.mjs'),
105 | generateBundleOpts('lifecycle.native.mjs', {useNatives: true}),
106 | generateBundleOpts('lifecycle.es5.js', {transpile: true}),
107 |
108 | {
109 | input: 'test/*-test.mjs',
110 | output: {
111 | file: 'test-bundle.js',
112 | format: 'iife',
113 | dir: 'test',
114 | },
115 | plugins: [
116 | multiEntry(),
117 | babel({
118 | presets: [['env', {modules: false}]],
119 | plugins: ['external-helpers'],
120 | }),
121 | ],
122 | watch: {
123 | include: ['src/**/*.mjs', 'test/**/*.mjs'],
124 | },
125 | },
126 | ];
127 |
--------------------------------------------------------------------------------
/src/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 |
16 | import EventTarget from './shims/EventTarget.mjs';
17 | import StateChangeEvent from './StateChangeEvent.mjs';
18 |
19 | const ACTIVE = 'active';
20 | const PASSIVE = 'passive';
21 | const HIDDEN = 'hidden';
22 | const FROZEN = 'frozen';
23 | // const DISCARDED = 'discarded'; Not used but show to completeness.
24 | const TERMINATED = 'terminated';
25 |
26 | // Detect Safari to work around Safari-specific bugs.
27 | const IS_SAFARI = typeof safari === 'object' && safari.pushNotification;
28 |
29 | const SUPPORTS_PAGE_TRANSITION_EVENTS = 'onpageshow' in self;
30 |
31 | const EVENTS = [
32 | 'focus',
33 | 'blur',
34 | 'visibilitychange',
35 | 'freeze',
36 | 'resume',
37 | 'pageshow',
38 | // IE9-10 do not support the pagehide event, so we fall back to unload
39 | // Note: unload *MUST ONLY* be added conditionally, otherwise it will
40 | // prevent page navigation caching (a.k.a bfcache).
41 | SUPPORTS_PAGE_TRANSITION_EVENTS ? 'pagehide' : 'unload',
42 | ];
43 |
44 | /**
45 | * @param {!Event} evt
46 | * @return {string}
47 | */
48 | const onbeforeunload = (evt) => {
49 | evt.preventDefault();
50 | return evt.returnValue = 'Are you sure?';
51 | };
52 |
53 | /**
54 | * Converts an array of states into an object where the state is the key
55 | * and the value is the index.
56 | * @param {!Array} arr
57 | * @return {!Object}
58 | */
59 | const toIndexedObject = (arr) => arr.reduce((acc, val, idx) => {
60 | acc[val] = idx;
61 | return acc;
62 | }, {});
63 |
64 | /**
65 | * @type {!Array}
66 | */
67 | const LEGAL_STATE_TRANSITIONS = [
68 | // The normal unload process (bfcache process is addressed above).
69 | [ACTIVE, PASSIVE, HIDDEN, TERMINATED],
70 |
71 | // An active page transitioning to frozen,
72 | // or an unloading page going into the bfcache.
73 | [ACTIVE, PASSIVE, HIDDEN, FROZEN],
74 |
75 | // A hidden page transitioning back to active.
76 | [HIDDEN, PASSIVE, ACTIVE],
77 |
78 | // A frozen page being resumed
79 | [FROZEN, HIDDEN],
80 |
81 | // A frozen (bfcached) page navigated back to
82 | // Note: [FROZEN, HIDDEN] can happen here, but it's already covered above.
83 | [FROZEN, ACTIVE],
84 | [FROZEN, PASSIVE],
85 | ].map(toIndexedObject);
86 |
87 | /**
88 | * Accepts a current state and a future state and returns an array of legal
89 | * state transition paths. This is needed to normalize behavior across browsers
90 | * since some browsers do not fire events in certain cases and thus skip
91 | * states.
92 | * @param {string} oldState
93 | * @param {string} newState
94 | * @return {!Array}
95 | */
96 | const getLegalStateTransitionPath = (oldState, newState) => {
97 | // We're intentionally not using for...of here so when we transpile to ES5
98 | // we don't need to include the Symbol polyfills.
99 | for (let order, i = 0; order = LEGAL_STATE_TRANSITIONS[i]; ++i) {
100 | const oldIndex = order[oldState];
101 | const newIndex = order[newState];
102 |
103 | if (oldIndex >= 0 &&
104 | newIndex >= 0 &&
105 | newIndex > oldIndex) {
106 | // Differences greater than one should be reported
107 | // because it means a state was skipped.
108 | return Object.keys(order).slice(oldIndex, newIndex + 1);
109 | }
110 | }
111 | return [];
112 | // TODO(philipwalton): it shouldn't be possible to get here, but
113 | // consider some kind of warning or call to action if it happens.
114 | // console.warn(`Invalid state change detected: ${oldState} > ${newState}`);
115 | };
116 |
117 | /**
118 | * Returns the current state based on the document's visibility and
119 | * in input focus states. Note this method is only used to determine
120 | * active vs passive vs hidden states, as other states require listening
121 | * for events.
122 | * @return {string}
123 | */
124 | const getCurrentState = () => {
125 | if (document.visibilityState === HIDDEN) {
126 | return HIDDEN;
127 | }
128 | if (document.hasFocus()) {
129 | return ACTIVE;
130 | }
131 | return PASSIVE;
132 | };
133 |
134 | /**
135 | * Class definition for the exported, singleton lifecycle instance.
136 | */
137 | export default class Lifecycle extends EventTarget {
138 | /**
139 | * Initializes state, state history, and adds event listeners to monitor
140 | * state changes.
141 | */
142 | constructor() {
143 | super();
144 |
145 | const state = getCurrentState();
146 |
147 | this._state = state;
148 | this._unsavedChanges = [];
149 |
150 | // Bind the callback and add event listeners.
151 | this._handleEvents = this._handleEvents.bind(this);
152 |
153 | // Add capturing events on window so they run immediately.
154 | EVENTS.forEach((evt) => addEventListener(evt, this._handleEvents, true));
155 |
156 | // Safari does not reliably fire the `pagehide` or `visibilitychange`
157 | // events when closing a tab, so we have to use `beforeunload` with a
158 | // timeout to check whether the default action was prevented.
159 | // - https://bugs.webkit.org/show_bug.cgi?id=151610
160 | // - https://bugs.webkit.org/show_bug.cgi?id=151234
161 | // NOTE: we only add this to Safari because adding it to Firefox would
162 | // prevent the page from being eligible for bfcache.
163 | if (IS_SAFARI) {
164 | addEventListener('beforeunload', (evt) => {
165 | this._safariBeforeUnloadTimeout = setTimeout(() => {
166 | if (!(evt.defaultPrevented || evt.returnValue.length > 0)) {
167 | this._dispatchChangesIfNeeded(evt, HIDDEN);
168 | }
169 | }, 0);
170 | });
171 | }
172 | }
173 |
174 | /**
175 | * @return {string}
176 | */
177 | get state() {
178 | return this._state;
179 | }
180 |
181 | /**
182 | * Returns the value of document.wasDiscarded. This is arguably unnecessary
183 | * but I think there's value in having the entire API in one place and
184 | * consistent across browsers.
185 | * @return {boolean}
186 | */
187 | get pageWasDiscarded() {
188 | return document.wasDiscarded || false;
189 | }
190 |
191 | /**
192 | * @param {Symbol|Object} id A unique symbol or object identifying the
193 | *. pending state. This ID is required when removing the state later.
194 | */
195 | addUnsavedChanges(id) {
196 | // Don't add duplicate state. Note: ideall this would be a set, but for
197 | // better browser compatibility we're using an array.
198 | if (!this._unsavedChanges.indexOf(id) > -1) {
199 | // If this is the first state being added,
200 | // also add a beforeunload listener.
201 | if (this._unsavedChanges.length === 0) {
202 | addEventListener('beforeunload', onbeforeunload);
203 | }
204 | this._unsavedChanges.push(id);
205 | }
206 | }
207 |
208 | /**
209 | * @param {Symbol|Object} id A unique symbol or object identifying the
210 | *. pending state. This ID is required when removing the state later.
211 | */
212 | removeUnsavedChanges(id) {
213 | const idIndex = this._unsavedChanges.indexOf(id);
214 |
215 | if (idIndex > -1) {
216 | this._unsavedChanges.splice(idIndex, 1);
217 |
218 | // If there's no more pending state, remove the event listener.
219 | if (this._unsavedChanges.length === 0) {
220 | removeEventListener('beforeunload', onbeforeunload);
221 | }
222 | }
223 | }
224 |
225 | /**
226 | * @private
227 | * @param {!Event} originalEvent
228 | * @param {string} newState
229 | */
230 | _dispatchChangesIfNeeded(originalEvent, newState) {
231 | if (newState !== this._state) {
232 | const oldState = this._state;
233 | const path = getLegalStateTransitionPath(oldState, newState);
234 |
235 | for (let i = 0; i < path.length - 1; ++i) {
236 | const oldState = path[i];
237 | const newState = path[i + 1];
238 |
239 | this._state = newState;
240 | this.dispatchEvent(new StateChangeEvent('statechange', {
241 | oldState,
242 | newState,
243 | originalEvent,
244 | }));
245 | }
246 | }
247 | }
248 |
249 | /**
250 | * @private
251 | * @param {!Event} evt
252 | */
253 | _handleEvents(evt) {
254 | if (IS_SAFARI) {
255 | clearTimeout(this._safariBeforeUnloadTimeout);
256 | }
257 |
258 | switch (evt.type) {
259 | case 'pageshow':
260 | case 'resume':
261 | this._dispatchChangesIfNeeded(evt, getCurrentState());
262 | break;
263 | case 'focus':
264 | this._dispatchChangesIfNeeded(evt, ACTIVE);
265 | break;
266 | case 'blur':
267 | // The `blur` event can fire while the page is being unloaded, so we
268 | // only need to update the state if the current state is "active".
269 | if (this._state === ACTIVE) {
270 | this._dispatchChangesIfNeeded(evt, getCurrentState());
271 | }
272 | break;
273 | case 'pagehide':
274 | case 'unload':
275 | this._dispatchChangesIfNeeded(evt, evt.persisted ? FROZEN : TERMINATED);
276 | break;
277 | case 'visibilitychange':
278 | // The document's `visibilityState` will change to hidden as the page
279 | // is being unloaded, but in such cases the lifecycle state shouldn't
280 | // change.
281 | if (this._state !== FROZEN &&
282 | this._state !== TERMINATED) {
283 | this._dispatchChangesIfNeeded(evt, getCurrentState());
284 | }
285 | break;
286 | case 'freeze':
287 | this._dispatchChangesIfNeeded(evt, FROZEN);
288 | break;
289 | }
290 | }
291 | }
292 |
--------------------------------------------------------------------------------
/src/StateChangeEvent.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 |
16 | import Event from './shims/Event.mjs';
17 |
18 | /**
19 | * implements {IStateChangeEvent}
20 | */
21 | export default class StateChangeEvent extends Event {
22 | /**
23 | * @param {string} type
24 | * @param {!Object} initDict
25 | */
26 | constructor(type, initDict) {
27 | super(type);
28 | this.newState = initDict.newState;
29 | this.oldState = initDict.oldState;
30 | this.originalEvent = initDict.originalEvent;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/export.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 |
16 | import Lifecycle from './Lifecycle.mjs';
17 |
18 | export default new Lifecycle();
19 |
--------------------------------------------------------------------------------
/src/natives/Event.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 |
16 | export default Event;
17 |
--------------------------------------------------------------------------------
/src/natives/EventTarget.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 |
16 | export default EventTarget;
17 |
--------------------------------------------------------------------------------
/src/shims/Event.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 |
16 | import {supportsConstructableEventTarget} from './support.mjs';
17 |
18 | /**
19 | * A minimal Event class shim.
20 | * This is used if the browser doesn't natively support constructable
21 | * EventTarget objects.
22 | */
23 | class EventShim {
24 | /**
25 | * @param {string} type
26 | */
27 | constructor(type) {
28 | this.type = type;
29 | }
30 | }
31 |
32 | export default supportsConstructableEventTarget ? Event : EventShim;
33 |
--------------------------------------------------------------------------------
/src/shims/EventTarget.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 |
16 | import {supportsConstructableEventTarget} from './support.mjs';
17 |
18 |
19 | /**
20 | * A minimal EventTarget class shim.
21 | * This is used if the browser doesn't natively support constructable
22 | * EventTarget objects.
23 | */
24 | class EventTargetShim {
25 | /**
26 | * Creates the event registry.
27 | */
28 | constructor() {
29 | this._registry = {};
30 | }
31 |
32 | /**
33 | * @param {string} type
34 | * @param {EventListener|function(!Event):(boolean|undefined)} listener
35 | * @param {(boolean|!AddEventListenerOptions)=} opts
36 | * @return {undefined}
37 | * @see https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener
38 | */
39 | addEventListener(type, listener, opts = false) {
40 | this._getRegistry(type).push(listener);
41 | }
42 |
43 | /**
44 | * @param {string} type
45 | * @param {EventListener|function(!Event):(boolean|undefined)} listener
46 | * @param {(boolean|!EventListenerOptions)=} opts
47 | * @return {undefined}
48 | * @see https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener
49 | */
50 | removeEventListener(type, listener, opts = false) {
51 | const typeRegistry = this._getRegistry(type);
52 | const handlerIndex = typeRegistry.indexOf(listener);
53 | if (handlerIndex > -1) {
54 | typeRegistry.splice(handlerIndex, 1);
55 | }
56 | }
57 |
58 | /**
59 | * @param {!Event|!EventShim} evt
60 | * @return {boolean}
61 | * @see https://dom.spec.whatwg.org/#dom-eventtarget-dispatchevent
62 | */
63 | dispatchEvent(evt) {
64 | // Set the target then freeze the event object to prevent modification.
65 | evt.target = this;
66 | Object.freeze(evt);
67 |
68 | this._getRegistry(evt.type).forEach((listener) => listener(evt));
69 | return true;
70 | }
71 |
72 | /**
73 | * Returns an array of handlers associated with the passed event type.
74 | * If no handlers have been registered, an empty array is returned.
75 | * @private
76 | * @param {string} type The event type.
77 | * @return {!Array} An array of handler functions.
78 | */
79 | _getRegistry(type) {
80 | return this._registry[type] = (this._registry[type] || []);
81 | }
82 | }
83 |
84 | export default supportsConstructableEventTarget ? EventTarget : EventTargetShim;
85 |
--------------------------------------------------------------------------------
/src/shims/support.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 |
16 | let supportsConstructableEventTarget;
17 |
18 | try {
19 | new EventTarget();
20 |
21 | // When transpiled with babel and rollup, the `IS_CODE_TRANSPILED` constant
22 | // is replaced with the boolean `true`, so this statement will always
23 | // evaluate to `false`. When not transpiled, it will be true.
24 | supportsConstructableEventTarget = typeof IS_CODE_TRANSPILED === 'undefined';
25 | } catch (err) {
26 | supportsConstructableEventTarget = false;
27 | }
28 |
29 | export {supportsConstructableEventTarget};
30 |
--------------------------------------------------------------------------------
/test/Lifecycle-test.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 |
16 | import Lifecycle from '../src/Lifecycle.mjs';
17 | import NativeEventTargetOrEventTargetShim from '../src/shims/EventTarget.mjs';
18 | import NativeEventOrEventShim from '../src/shims/Event.mjs';
19 |
20 | // Detect Safari to work around Safari-specific bugs.
21 | const IS_SAFARI = typeof safari === 'object' && safari.pushNotification;
22 | const SUPPORTS_FREEZE_EVENT = 'onfreeze' in document;
23 | const SUPPORTS_PAGE_TRANSITION_EVENTS = 'onpageshow' in self;
24 | const SUPPORTS_PAGE_VISIBILITY = 'visibilityState' in document;
25 |
26 | const sandbox = sinon.createSandbox();
27 |
28 | /**
29 | * Dispatches an event, with optional props that should be added to the
30 | * event object. This method also only fires the event if the browser running
31 | * this could would actually fire it. This helps ensure the tests more
32 | * accurately reflect different scenarios the library could be run in.
33 | * @param {string} type The type of event to dispatch.
34 | * @param {Object=} props Additioal property/values to set on the event.
35 | */
36 | const fireEvent = (type, props = {}) => {
37 | let event;
38 |
39 | // Don't fire events if the browser doesn't support them.
40 | switch (type) {
41 | case 'visibilitychange':
42 | if (!SUPPORTS_PAGE_VISIBILITY) return;
43 | break;
44 | case 'pageshow':
45 | case 'pagehide':
46 | if (!SUPPORTS_PAGE_TRANSITION_EVENTS) return;
47 | break;
48 | case 'freeze':
49 | case 'resume':
50 | if (!SUPPORTS_FREEZE_EVENT) return;
51 | break;
52 | }
53 |
54 | // Tries to create the event using a constructor, if that doesn't work,
55 | // falls back to `document.createEvent()`.
56 | try {
57 | event = new Event(type);
58 | } catch (err) {
59 | event = document.createEvent('Event');
60 | event.initEvent(type, false, false);
61 | }
62 |
63 | Object.keys(props).forEach((prop) => {
64 | Object.defineProperty(event, prop, {value: props[prop]});
65 | });
66 |
67 | self.dispatchEvent(event);
68 | };
69 |
70 | /**
71 | * A wrapper around `sinon.stub()` for properties that supports non-existent
72 | * own properties (sinon doesn't).
73 | * @param {!Object} obj
74 | * @param {string} prop
75 | * @param {*} value
76 | * @return {!Object}
77 | */
78 | const stubProperty = (obj, prop, value) => {
79 | if (!obj.hasOwnProperty(prop)) {
80 | return {
81 | value: (value) => {
82 | Object.defineProperty(obj, prop, {value, configurable: true});
83 | },
84 | };
85 | } else {
86 | return sandbox.stub(obj, prop);
87 | }
88 | };
89 |
90 | /**
91 | * A wrapper around `sinon.stub()` for methods that automatically unstubs
92 | * an restubs a method if it's already been stubbed.
93 | * @param {!Object} obj
94 | * @param {string} method
95 | * @return {!Object}
96 | */
97 | const stubMethod = (obj, method) => {
98 | if (obj[method].isSinonProxy) {
99 | obj[method].restore();
100 | }
101 | return sandbox.stub(obj, method);
102 | };
103 |
104 | /**
105 | * Stubs the properties and methods needed for Lifecycle to detect the
106 | * correct state (either at instantiation time or after an event). Note that
107 | * the frozen, terminated, and discarded states cannot be stubbed since
108 | * they require an event to fire to be observable.
109 | * @param {string} state
110 | */
111 | const stubState = (state) => {
112 | switch (state) {
113 | case 'active':
114 | stubProperty(document, 'visibilityState').value('visible');
115 | stubMethod(document, 'hasFocus').returns(true);
116 | break;
117 | case 'passive':
118 | stubProperty(document, 'visibilityState').value('visible');
119 | stubMethod(document, 'hasFocus').returns(false);
120 | break;
121 | case 'hidden':
122 | stubProperty(document, 'visibilityState').value('hidden');
123 | stubMethod(document, 'hasFocus').returns(false);
124 | break;
125 | }
126 | };
127 |
128 | /**
129 | * Stubs the properties and methods needed for Lifecycle to detect the
130 | * correct state (either at instantiation time or after an event). Note that
131 | * the frozen, terminated, and discarded states cannot be stubbed since
132 | * they require an event to fire to be observable.
133 | * @param {string} oldState
134 | * @param {string} newState
135 | * @param {{bfcache: (string)}=} param3
136 | * - bfcache: true if the state change involves entering or leaving the
137 | *. page navigation cache (bfcache).
138 | */
139 | const simulateStateChange = (oldState, newState, {bfcache} = {}) => {
140 | stubState(newState);
141 |
142 | switch (newState) {
143 | case 'active':
144 | if (oldState === 'frozen') {
145 | fireEvent('resume');
146 | fireEvent('pageshow', {persisted: true});
147 | }
148 | fireEvent('focus');
149 | break;
150 | case 'passive':
151 | if (oldState === 'active') {
152 | fireEvent('blur');
153 | }
154 | if (oldState === 'hidden') {
155 | fireEvent('visibilitychange');
156 | }
157 | if (oldState === 'frozen') {
158 | fireEvent('resume');
159 | fireEvent('pageshow', {persisted: true});
160 | }
161 | break;
162 | case 'hidden':
163 | if (oldState === 'passive') {
164 | fireEvent('visibilitychange');
165 | }
166 | if (oldState === 'frozen') {
167 | fireEvent('resume');
168 | if (bfcache) {
169 | fireEvent('pageshow', {persisted: true});
170 | }
171 | }
172 | break;
173 | case 'frozen':
174 | if (bfcache) {
175 | fireEvent('pagehide', {persisted: true});
176 | }
177 | fireEvent('freeze');
178 | break;
179 | case 'terminated':
180 | fireEvent('pagehide');
181 | fireEvent('unload'); // Needed for IE9-10
182 | break;
183 | }
184 | };
185 |
186 | describe('Lifecycle', () => {
187 | beforeEach(() => {
188 | sandbox.restore();
189 | });
190 |
191 | afterEach(() => {
192 | sandbox.restore();
193 | });
194 |
195 | describe(`constructor`, () => {
196 | it(`extends EventTarget`, () => {
197 | const lifecycle = new Lifecycle();
198 | assert(lifecycle instanceof NativeEventTargetOrEventTargetShim);
199 | });
200 |
201 | it(`adds capturing event listeners for all built-in lifecycle events`,
202 | () => {
203 | const spy = sandbox.spy(self, 'addEventListener');
204 |
205 | new Lifecycle();
206 |
207 | if (!IS_SAFARI) {
208 | assert.equal(spy.callCount, 7);
209 | } else {
210 | // Safari requires a `beforeunload` listener to fix buggy behavior:
211 | // https://github.com/GoogleChromeLabs/page-lifecycle/issues/2
212 | assert.equal(spy.callCount, 8);
213 | assert(spy.calledWith('beforeunload', sinon.match.func));
214 | }
215 |
216 | assert(spy.calledWith('focus', sinon.match.func, true));
217 | assert(spy.calledWith('blur', sinon.match.func, true));
218 | assert(spy.calledWith('visibilitychange', sinon.match.func, true));
219 | assert(spy.calledWith('freeze', sinon.match.func, true));
220 | assert(spy.calledWith('resume', sinon.match.func, true));
221 | if (SUPPORTS_PAGE_TRANSITION_EVENTS) {
222 | assert(spy.calledWith('pageshow', sinon.match.func, true));
223 | assert(spy.calledWith('pagehide', sinon.match.func, true));
224 | } else {
225 | assert(spy.calledWith('unload', sinon.match.func, true));
226 | }
227 | });
228 | });
229 |
230 | describe(`get state`, () => {
231 | it(`returns 'active' when the document is visible and has input focus`,
232 | () => {
233 | stubState('active');
234 | const lifecycle = new Lifecycle();
235 |
236 | assert.equal(lifecycle.state, 'active');
237 | });
238 |
239 | it(`returns 'passive' when the document visible and doesn't have input ` +
240 | `focus`, () => {
241 | stubState('passive');
242 | const lifecycle = new Lifecycle();
243 |
244 | assert.equal(lifecycle.state, 'passive');
245 | });
246 |
247 | it(`returns 'hidden' when the document is hidden and not frozen`, () => {
248 | stubState('hidden');
249 | const lifecycle = new Lifecycle();
250 |
251 | assert.equal(lifecycle.state, 'hidden');
252 | });
253 |
254 | it(`returns 'frozen' if the freeze event has just fired`, () => {
255 | if (SUPPORTS_FREEZE_EVENT) {
256 | stubState('hidden');
257 | const lifecycle = new Lifecycle();
258 |
259 | simulateStateChange('hidden', 'frozen');
260 |
261 | assert.equal(lifecycle.state, 'frozen');
262 | }
263 | });
264 |
265 | it(`returns 'frozen' if the page is entering the page navigation cache`,
266 | () => {
267 | if (SUPPORTS_PAGE_TRANSITION_EVENTS) {
268 | stubState('hidden');
269 | const lifecycle = new Lifecycle();
270 |
271 | simulateStateChange('hidden', 'frozen', {bfcache: true});
272 |
273 | assert.equal(lifecycle.state, 'frozen');
274 | }
275 | });
276 |
277 | it(`returns 'terminated' if the page is being unloaded`, () => {
278 | stubState('hidden');
279 | const lifecycle = new Lifecycle();
280 |
281 | simulateStateChange('hidden', 'terminated');
282 |
283 | assert.equal(lifecycle.state, 'terminated');
284 | });
285 | });
286 |
287 | describe(`get pageWasDiscarded`, () => {
288 | it(`returns the value of document.wasDiscarded`, () => {
289 | const lifecycle = new Lifecycle();
290 | assert.equal(lifecycle.pageWasDiscarded, false);
291 |
292 | stubProperty(document, 'wasDiscarded').value(true);
293 | assert.equal(lifecycle.pageWasDiscarded, true);
294 | });
295 | });
296 |
297 | describe(`addEventListener`, () => {
298 | it(`adds a listener for statechange events`, () => {
299 | stubState('active');
300 |
301 | const lifecycle = new Lifecycle();
302 | const listener = sinon.spy();
303 | lifecycle.addEventListener('statechange', listener);
304 |
305 | simulateStateChange('active', 'passive');
306 |
307 | assert.equal(listener.callCount, 1);
308 | assert(listener.getCall(0).calledWith(sinon.match({
309 | type: 'statechange',
310 | oldState: 'active',
311 | newState: 'passive',
312 | target: lifecycle,
313 | })));
314 | assert(listener.getCall(0).args[0] instanceof NativeEventOrEventShim);
315 |
316 | simulateStateChange('passive', 'active');
317 |
318 | assert.equal(listener.callCount, 2);
319 | assert(listener.getCall(1).calledWith(sinon.match({
320 | type: 'statechange',
321 | oldState: 'passive',
322 | newState: 'active',
323 | target: lifecycle,
324 | })));
325 | assert(listener.getCall(0).args[0] instanceof NativeEventOrEventShim);
326 | });
327 |
328 | it(`tracks valid state change events from active to terminated`, () => {
329 | stubState('active');
330 |
331 | const lifecycle = new Lifecycle();
332 | const listener = sinon.spy();
333 | lifecycle.addEventListener('statechange', listener);
334 |
335 | simulateStateChange('active', 'passive');
336 |
337 | assert(listener.calledOnce);
338 | assert(listener.firstCall.calledWith(sinon.match({
339 | oldState: 'active',
340 | newState: 'passive',
341 | })));
342 | listener.resetHistory();
343 |
344 | simulateStateChange('passive', 'hidden');
345 | simulateStateChange('hidden', 'terminated');
346 |
347 | assert(listener.calledTwice);
348 | assert(listener.firstCall.calledWith(sinon.match({
349 | oldState: 'passive',
350 | newState: 'hidden',
351 | })));
352 | assert(listener.secondCall.calledWith(sinon.match({
353 | oldState: 'hidden',
354 | newState: 'terminated',
355 | })));
356 | });
357 |
358 | it(`tracks valid state change events from active to frozen, and back`,
359 | () => {
360 | stubState('active');
361 |
362 | const lifecycle = new Lifecycle();
363 | const listener = sinon.spy();
364 | lifecycle.addEventListener('statechange', listener);
365 |
366 | simulateStateChange('active', 'passive');
367 |
368 | assert(listener.calledOnce);
369 | assert(listener.firstCall.calledWith(sinon.match({
370 | oldState: 'active',
371 | newState: 'passive',
372 | })));
373 | listener.resetHistory();
374 |
375 | if (SUPPORTS_PAGE_VISIBILITY) {
376 | simulateStateChange('passive', 'hidden');
377 |
378 | assert(listener.calledOnce);
379 | assert(listener.firstCall.calledWith(sinon.match({
380 | oldState: 'passive',
381 | newState: 'hidden',
382 | })));
383 | listener.resetHistory();
384 |
385 | if (SUPPORTS_FREEZE_EVENT) {
386 | simulateStateChange('hidden', 'frozen');
387 | simulateStateChange('frozen', 'hidden');
388 |
389 | assert(listener.calledTwice);
390 | assert(listener.firstCall.calledWith(sinon.match({
391 | oldState: 'hidden',
392 | newState: 'frozen',
393 | })));
394 | assert(listener.secondCall.calledWith(sinon.match({
395 | oldState: 'frozen',
396 | newState: 'hidden',
397 | })));
398 | listener.resetHistory();
399 | }
400 |
401 | simulateStateChange('hidden', 'passive');
402 |
403 | assert(listener.calledOnce);
404 | assert(listener.firstCall.calledWith(sinon.match({
405 | oldState: 'hidden',
406 | newState: 'passive',
407 | })));
408 | listener.resetHistory();
409 | }
410 |
411 | simulateStateChange('passive', 'active');
412 |
413 | assert(listener.calledOnce);
414 | assert(listener.firstCall.calledWith(sinon.match({
415 | oldState: 'passive',
416 | newState: 'active',
417 | })));
418 | });
419 |
420 | it(`tracks valid state change events from active to frozen (in page cache)`,
421 | () => {
422 | stubState('active');
423 |
424 | const lifecycle = new Lifecycle();
425 | const listener = sinon.spy();
426 | lifecycle.addEventListener('statechange', listener);
427 |
428 | simulateStateChange('active', 'passive');
429 |
430 | assert(listener.calledOnce);
431 | assert(listener.firstCall.calledWith(sinon.match({
432 | oldState: 'active',
433 | newState: 'passive',
434 | })));
435 | listener.resetHistory();
436 |
437 | if (SUPPORTS_PAGE_VISIBILITY) {
438 | simulateStateChange('passive', 'hidden');
439 |
440 | assert(listener.calledOnce);
441 | assert(listener.firstCall.calledWith(sinon.match({
442 | oldState: 'passive',
443 | newState: 'hidden',
444 | })));
445 | listener.resetHistory();
446 |
447 | if (SUPPORTS_PAGE_TRANSITION_EVENTS) {
448 | simulateStateChange('hidden', 'frozen', {bfcache: true});
449 |
450 | assert(listener.calledOnce);
451 | assert(listener.firstCall.calledWith(sinon.match({
452 | oldState: 'hidden',
453 | newState: 'frozen',
454 | })));
455 | }
456 | }
457 | });
458 |
459 | ['active', 'passive', 'hidden'].forEach((state) => {
460 | it(`tracks valid state change events from frozen (in page cache) ` +
461 | `to ${state}`, () => {
462 | stubState('hidden');
463 | const lifecycle = new Lifecycle();
464 | simulateStateChange('hidden', 'frozen', {bfcache: true});
465 |
466 | if (SUPPORTS_PAGE_TRANSITION_EVENTS) {
467 | const listener = sinon.spy();
468 | lifecycle.addEventListener('statechange', listener);
469 |
470 | simulateStateChange('frozen', state, {bfcache: true});
471 |
472 | assert(listener.calledOnce);
473 | assert(listener.firstCall.calledWith(sinon.match({
474 | oldState: 'frozen',
475 | newState: state,
476 | })));
477 | }
478 | });
479 | });
480 |
481 | // In Safari 12 (and below) you can switch tabs without getting a
482 | // blur event. We need to ensure the passive state is still observed in
483 | // this case.
484 | it(`handles invalid changes from active to hidden, and back`, () => {
485 | stubState('active');
486 |
487 | const lifecycle = new Lifecycle();
488 | const listener = sinon.spy();
489 | lifecycle.addEventListener('statechange', listener);
490 |
491 | if (SUPPORTS_PAGE_VISIBILITY) {
492 | // Change the page's visibilityState to hidden without first firing a
493 | // blur event.
494 | stubMethod(document, 'hasFocus').returns(false);
495 | stubProperty(document, 'visibilityState').value('hidden');
496 | fireEvent('visibilitychange');
497 |
498 | assert.equal(listener.callCount, 2);
499 | assert(listener.firstCall.calledWith(sinon.match({
500 | oldState: 'active',
501 | newState: 'passive',
502 | })));
503 | assert(listener.secondCall.calledWith(sinon.match({
504 | oldState: 'passive',
505 | newState: 'hidden',
506 | })));
507 |
508 | listener.resetHistory();
509 |
510 | // Change the page's visibilityState back to visible and set document
511 | // focus without first firing a focus event.
512 | stubMethod(document, 'hasFocus').returns(true);
513 | stubProperty(document, 'visibilityState').value('visible');
514 | fireEvent('visibilitychange');
515 |
516 | assert.equal(listener.callCount, 2);
517 | assert(listener.getCall(0).calledWith(sinon.match({
518 | oldState: 'hidden',
519 | newState: 'passive',
520 | })));
521 | assert(listener.getCall(1).calledWith(sinon.match({
522 | oldState: 'passive',
523 | newState: 'active',
524 | })));
525 |
526 | listener.resetHistory();
527 | }
528 | });
529 |
530 | // In most browsers, navigating via an in-page link will not trigger a
531 | // blur event (at least not right away). We need to ensure the passive
532 | // state is still observed in this case.
533 | // Chrome 67: pagehide > visibilitychange
534 | // Firefox 60: pagehide > visibilitychange > blur
535 | it(`handles invalid changes from active to frozen (page cache), and back`,
536 | () => {
537 | stubState('active');
538 |
539 | const lifecycle = new Lifecycle();
540 | const listener = sinon.spy();
541 | lifecycle.addEventListener('statechange', listener);
542 |
543 | if (SUPPORTS_PAGE_VISIBILITY && SUPPORTS_PAGE_TRANSITION_EVENTS) {
544 | // Navigate away but put the page into the bfcache.
545 | stubMethod(document, 'hasFocus').returns(false);
546 | fireEvent('pagehide', {persisted: true});
547 |
548 | assert.equal(listener.callCount, 3);
549 | assert(listener.getCall(0).calledWith(sinon.match({
550 | oldState: 'active',
551 | newState: 'passive',
552 | })));
553 | assert(listener.getCall(1).calledWith(sinon.match({
554 | oldState: 'passive',
555 | newState: 'hidden',
556 | })));
557 | assert(listener.getCall(2).calledWith(sinon.match({
558 | oldState: 'hidden',
559 | newState: 'frozen',
560 | })));
561 |
562 | listener.resetHistory();
563 |
564 | // Navigate back, moving the page from frozen directly to active.
565 | document.hasFocus.restore();
566 | stubMethod(document, 'hasFocus').returns(true);
567 | stubProperty(document, 'visibilityState').value('visible');
568 | fireEvent('pageshow');
569 |
570 | assert.equal(listener.callCount, 1);
571 | assert(listener.getCall(0).calledWith(sinon.match({
572 | oldState: 'frozen',
573 | newState: 'active',
574 | })));
575 |
576 | listener.resetHistory();
577 | }
578 | });
579 |
580 | // All browsers (at this moment) fire the pagehide event before the
581 | // visibilitychange event if the user is unloading an active tab.
582 | // We need to ensure the state change happen in the right order.
583 | // (Note: this behavior is current per-spec, but we're proposing an update
584 | // https://github.com/w3c/page-visibility/issues/39)
585 | it(`handles invalid changes from active to terminated`, () => {
586 | stubState('active');
587 |
588 | const lifecycle = new Lifecycle();
589 | const listener = sinon.spy();
590 | lifecycle.addEventListener('statechange', listener);
591 |
592 | fireEvent('pagehide');
593 | stubProperty(document, 'visibilityState').value('hidden');
594 | fireEvent('visibilitychange');
595 | fireEvent('unload');
596 |
597 | assert.equal(listener.callCount, 3);
598 | assert(listener.getCall(0).calledWith(sinon.match({
599 | oldState: 'active',
600 | newState: 'passive',
601 | })));
602 | assert(listener.getCall(1).calledWith(sinon.match({
603 | oldState: 'passive',
604 | newState: 'hidden',
605 | })));
606 | assert(listener.getCall(2).calledWith(sinon.match({
607 | oldState: 'hidden',
608 | newState: 'terminated',
609 | })));
610 | });
611 |
612 | if (IS_SAFARI) {
613 | it(`adds a beforeunload listener to detect missing pagehide events`,
614 | (done) => {
615 | stubState('active');
616 |
617 | const lifecycle = new Lifecycle();
618 | const listener = sinon.spy();
619 | lifecycle.addEventListener('statechange', listener);
620 |
621 | fireEvent('beforeunload');
622 | setTimeout(() => {
623 | assert.equal(listener.callCount, 2);
624 | assert(listener.getCall(0).calledWith(sinon.match({
625 | oldState: 'active',
626 | newState: 'passive',
627 | })));
628 | assert(listener.getCall(1).calledWith(sinon.match({
629 | oldState: 'passive',
630 | newState: 'hidden',
631 | })));
632 | done();
633 | }, 0);
634 | });
635 |
636 | it(`accounts for the beforeunload listener being cancelled`, (done) => {
637 | stubState('active');
638 |
639 | const lifecycle = new Lifecycle();
640 | const listener = sinon.spy();
641 | lifecycle.addEventListener('statechange', listener);
642 |
643 | fireEvent('beforeunload', {defaultPrevented: true});
644 | fireEvent('beforeunload', {returnValue: '!'});
645 | setTimeout(() => {
646 | assert.equal(listener.callCount, 0);
647 | done();
648 | }, 0);
649 | });
650 |
651 | it(`accounts for other events firing before the beforeunload timeout`,
652 | (done) => {
653 | stubState('active');
654 |
655 | const lifecycle = new Lifecycle();
656 | const listener = sinon.spy();
657 | lifecycle.addEventListener('statechange', listener);
658 |
659 | // Schedule a timeout to fire the pagehide and pageshow events
660 | // to ensure that receiving other events cancels the logic about
661 | // to be performed by the beforeunload listener.
662 | setTimeout(() => {
663 | fireEvent('pagehide', {persisted: true});
664 | fireEvent('pageshow', {persisted: true});
665 | }, 0);
666 |
667 | fireEvent('beforeunload');
668 | setTimeout(() => {
669 | assert.equal(listener.callCount, 4);
670 | assert(listener.getCall(0).calledWith(sinon.match({
671 | oldState: 'active',
672 | newState: 'passive',
673 | originalEvent: sinon.match({type: 'pagehide'}),
674 | })));
675 | assert(listener.getCall(1).calledWith(sinon.match({
676 | oldState: 'passive',
677 | newState: 'hidden',
678 | originalEvent: sinon.match({type: 'pagehide'}),
679 | })));
680 | assert(listener.getCall(2).calledWith(sinon.match({
681 | oldState: 'hidden',
682 | newState: 'frozen',
683 | originalEvent: sinon.match({type: 'pagehide'}),
684 | })));
685 | assert(listener.getCall(3).calledWith(sinon.match({
686 | oldState: 'frozen',
687 | newState: 'active',
688 | originalEvent: sinon.match({type: 'pageshow'}),
689 | })));
690 | done();
691 | }, 0);
692 | });
693 | }
694 | });
695 |
696 | describe(`removeEventListener`, () => {
697 | it(`remove added event listeners`, () => {
698 | stubState('active');
699 |
700 | const lifecycle = new Lifecycle();
701 | const listener = sinon.spy();
702 | lifecycle.addEventListener('statechange', listener);
703 |
704 | simulateStateChange('active', 'passive');
705 |
706 | assert.equal(listener.callCount, 1);
707 | assert(listener.getCall(0).calledWith(sinon.match({
708 | type: 'statechange',
709 | oldState: 'active',
710 | newState: 'passive',
711 | target: lifecycle,
712 | })));
713 |
714 | // Remove the listener, then trigger a change to the 'passive' state.
715 | lifecycle.removeEventListener('statechange', listener);
716 |
717 | simulateStateChange('passive', 'active');
718 |
719 | // Should not have been called again.
720 | assert.equal(listener.callCount, 1);
721 | });
722 | });
723 |
724 | describe(`addUnsavedChanges`, () => {
725 | it(`adds a beforeunload listener to warn about unsaved changes if one ` +
726 | `isn't already added`, () => {
727 | const lifecycle = new Lifecycle();
728 |
729 | const stub = sandbox.stub(self, 'addEventListener');
730 | const id1 = {};
731 | lifecycle.addUnsavedChanges(id1);
732 |
733 | assert(stub.calledOnce);
734 |
735 | const id2 = {};
736 | lifecycle.addUnsavedChanges(id2);
737 |
738 | // It shouldn't have been called again.
739 | assert(stub.calledOnce);
740 |
741 | const id3 = {};
742 | lifecycle.addUnsavedChanges(id3);
743 |
744 | // It still shouldn't have been called again.
745 | assert(stub.calledOnce);
746 | });
747 | });
748 |
749 | describe(`removeUnsavedChanges`, () => {
750 | it(`removes a beforeunload listener to warn about unsaved changes if ` +
751 | `no unsaved changes remain`, () => {
752 | const lifecycle = new Lifecycle();
753 |
754 | const addEventListenerStub = sandbox.stub(self, 'addEventListener');
755 | const removeEventListenerStub = sandbox.stub(self, 'removeEventListener');
756 |
757 | const id1 = {};
758 | const id2 = {};
759 | const id3 = {};
760 | lifecycle.addUnsavedChanges(id1);
761 | lifecycle.addUnsavedChanges(id2);
762 | lifecycle.addUnsavedChanges(id3);
763 |
764 | assert(addEventListenerStub.calledOnce);
765 | assert(removeEventListenerStub.notCalled);
766 |
767 | lifecycle.removeUnsavedChanges(id1);
768 | lifecycle.removeUnsavedChanges(id2);
769 |
770 | assert(addEventListenerStub.calledOnce);
771 | assert(removeEventListenerStub.notCalled);
772 |
773 | lifecycle.removeUnsavedChanges(id3);
774 |
775 | assert(addEventListenerStub.calledOnce);
776 | assert(removeEventListenerStub.calledOnce);
777 | });
778 | });
779 | });
780 |
--------------------------------------------------------------------------------
/test/export-test.mjs:
--------------------------------------------------------------------------------
1 | import lifecycle from '../src/export.mjs';
2 | import Lifecycle from '../src/Lifecycle.mjs';
3 |
4 | describe('export', () => {
5 | it(`is an instance of Lifecycle`, () => {
6 | assert(lifecycle instanceof Lifecycle);
7 | });
8 | });
9 |
--------------------------------------------------------------------------------
/test/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
25 |
26 |
27 |
28 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
77 |
78 |
79 |
--------------------------------------------------------------------------------