-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Activity service to calculate engaged time for amp-analytics #1818
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
/** | ||
* Copyright 2015 The AMP HTML Authors. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS-IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
import {getElementService} from './custom-element'; | ||
|
||
/** | ||
* @param {!Window} win | ||
* @return {!Promise<!Activity>} | ||
*/ | ||
export function activityFor(win) { | ||
return getElementService(win, 'activity', 'amp-analytics'); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,303 @@ | ||
/** | ||
* Copyright 2015 The AMP HTML Authors. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS-IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
/** | ||
* @fileoverview Provides an ability to collect data about activities the user | ||
* has performed on the page. | ||
*/ | ||
|
||
import {getService} from '../service'; | ||
import {viewerFor} from '../viewer'; | ||
import {listen} from '../event-helper'; | ||
|
||
|
||
/** | ||
* The amount of time after an activity the user is considered engaged. | ||
* @private @const {number} | ||
*/ | ||
const DEFAULT_ENGAGED_SECONDS = 5; | ||
|
||
/** | ||
* @enum {string} | ||
*/ | ||
const ActivityEventType = { | ||
ACTIVE: 'active', | ||
INACTIVE: 'inactive' | ||
}; | ||
|
||
/** | ||
* @typedef {{ | ||
* type: string, | ||
* time: number | ||
* }} | ||
*/ | ||
let ActivityEventDef; | ||
|
||
/** | ||
* Find the engaged time between the event and the time (exclusive of the time) | ||
* @param {ActivityEventDef} e1 | ||
* @param {number} time | ||
* @return {number} | ||
* @private | ||
*/ | ||
function findEngagedTimeBetween(activityEvent, time) { | ||
let engagementBonus = 0; | ||
|
||
if (activityEvent.type === ActivityEventType.ACTIVE) { | ||
engagementBonus = DEFAULT_ENGAGED_SECONDS; | ||
} | ||
|
||
return Math.min(time - activityEvent.time, engagementBonus); | ||
} | ||
|
||
class ActivityHistory { | ||
|
||
constructor() { | ||
/** @private {number} */ | ||
this.totalEngagedTime_ = 0; | ||
|
||
/** | ||
* prevActivityEvent_ remains undefined until the first valid push call. | ||
* @private {ActivityEventDef} | ||
*/ | ||
this.prevActivityEvent_ = undefined; | ||
} | ||
|
||
/** | ||
* Indicate that an activity took place at the given time. | ||
* @param {ActivityEventDef} | ||
*/ | ||
push(activityEvent) { | ||
if (!this.prevActivityEvent_) { | ||
this.prevActivityEvent_ = activityEvent; | ||
} | ||
|
||
if (this.prevActivityEvent_.time < activityEvent.time) { | ||
this.totalEngagedTime_ += | ||
findEngagedTimeBetween(this.prevActivityEvent_, activityEvent.time); | ||
this.prevActivityEvent_ = activityEvent; | ||
} | ||
} | ||
|
||
/** | ||
* Get the total engaged time up to the given time recorded in | ||
* ActivityHistory. | ||
* @param {number} time | ||
* @return {number} | ||
*/ | ||
getTotalEngagedTime(time) { | ||
let totalEngagedTime = 0; | ||
if (this.prevActivityEvent_ !== undefined) { | ||
totalEngagedTime = this.totalEngagedTime_ + | ||
findEngagedTimeBetween(this.prevActivityEvent_, time); | ||
} | ||
return totalEngagedTime; | ||
} | ||
} | ||
|
||
|
||
/** | ||
* Array of event types which will be listened for on the document element to | ||
* indicate activity. | ||
* @private @const {Array<string>} | ||
*/ | ||
const ACTIVE_EVENT_TYPES = [ | ||
'scroll', 'mousedown', 'mouseup', 'mousemove', 'keydown', 'keyup' | ||
]; | ||
|
||
export class Activity { | ||
|
||
/** | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please describe the lifecycle a bit. |
||
* Activity tracks basic user activity on the page. | ||
* - Listeners are not registered on the activity event types until the | ||
* Viewer's `whenFirstVisible` is resolved. | ||
* - When the `whenFirstVisible` of Viewer is resolved, a first activity | ||
* is recorded. | ||
* - The first activity in any second causes all other activities to be | ||
* ignored. This is similar to debounce functionality since some events | ||
* (e.g. scroll) could occur in rapid succession. | ||
* - In any one second period, active events or inactive events can override | ||
* each other. Whichever type occured last has precedence. | ||
* - Active events give a 5 second "bonus" to engaged time. | ||
* - Inactive events cause an immediate stop to the engaged time bonus of | ||
* any previous activity event. | ||
* - At any point after instantiation, `getTotalEngagedTime` can be used | ||
* to get the engage time up to the time the function is called. If | ||
* `whenFirstVisible` has not yet resolved, engaged time is 0. | ||
* @param {!Window} win | ||
*/ | ||
constructor(win) { | ||
/** @private @const */ | ||
this.win_ = win; | ||
|
||
/** @private @const {function} */ | ||
this.boundStopIgnore_ = this.stopIgnore_.bind(this); | ||
|
||
/** @private @const {function} */ | ||
this.boundHandleActivity_ = this.handleActivity_.bind(this); | ||
|
||
/** @private @const {function} */ | ||
this.boundHandleInactive_ = this.handleInactive_.bind(this); | ||
|
||
/** @private @const {function} */ | ||
this.boundHandleVisibilityChange_ = this.handleVisibilityChange_.bind(this); | ||
|
||
/** @private {Array<!UnlistenDef>} */ | ||
this.unlistenFuncs_ = []; | ||
|
||
/** @private {boolean} */ | ||
this.ignoreActivity_ = false; | ||
|
||
/** @private {boolean} */ | ||
this.ignoreInactive_ = false; | ||
|
||
/** @private @const {!ActivityHistory} */ | ||
this.activityHistory_ = new ActivityHistory(); | ||
|
||
/** @private @const {!Viewer} */ | ||
this.viewer_ = viewerFor(this.win_); | ||
|
||
this.viewer_.whenFirstVisible().then(this.start_.bind(this)); | ||
} | ||
|
||
/** @private */ | ||
start_() { | ||
/** @private @const {number} */ | ||
this.startTime_ = (new Date()).getTime(); | ||
// record an activity since this is when the page became visible | ||
this.handleActivity_(); | ||
this.setUpActivityListeners_(); | ||
} | ||
|
||
/** @private */ | ||
getTimeSinceStart_() { | ||
const timeSinceStart = (new Date()).getTime() - this.startTime_; | ||
// Ensure that a negative time is never returned. This may cause loss of | ||
// data if there is a time change during the session but it will decrease | ||
// the likelyhood of errors in that situation. | ||
return (timeSinceStart > 0 ? timeSinceStart : 0); | ||
} | ||
|
||
/** | ||
* Return to a state where neither activities or inactivity events are | ||
* ignored when that event type is fired. | ||
* @private | ||
*/ | ||
stopIgnore_() { | ||
this.ignoreActivity_ = false; | ||
this.ignoreInactive_ = false; | ||
} | ||
|
||
/** @private */ | ||
setUpActivityListeners_() { | ||
for (let i = 0; i < ACTIVE_EVENT_TYPES.length; i++) { | ||
this.unlistenFuncs_.push(listen(this.win_.document.documentElement, | ||
ACTIVE_EVENT_TYPES[i], this.boundHandleActivity_)); | ||
} | ||
|
||
this.viewer_.onVisibilityChanged(this.boundHandleVisibilityChange_); | ||
} | ||
|
||
/** @private */ | ||
handleActivity_() { | ||
if (this.ignoreActivity_) { | ||
return; | ||
} | ||
this.ignoreActivity_ = true; | ||
this.ignoreInactive_ = false; | ||
|
||
this.handleActivityEvent_(ActivityEventType.ACTIVE); | ||
} | ||
|
||
/** @private */ | ||
handleInactive_() { | ||
if (this.ignoreInactive_) { | ||
return; | ||
} | ||
this.ignoreInactive_ = true; | ||
this.ignoreActivity_ = false; | ||
|
||
this.handleActivityEvent_(ActivityEventType.INACTIVE); | ||
} | ||
|
||
/** | ||
* @param {ActivityEventType} | ||
* @private | ||
*/ | ||
handleActivityEvent_(type) { | ||
const timeSinceStart = this.getTimeSinceStart_(); | ||
const secondKey = Math.floor(timeSinceStart / 1000); | ||
const timeToWait = 1000 - (timeSinceStart % 1000); | ||
|
||
// stop ignoring activity at the start of the next activity bucket | ||
setTimeout(this.boundStopIgnore_, timeToWait); | ||
|
||
this.activityHistory_.push(/** @type {ActivityEventDef} */{ | ||
type: type, | ||
time: secondKey | ||
}); | ||
} | ||
|
||
/** @private */ | ||
handleVisibilityChange_() { | ||
if (this.viewer_.isVisible()) { | ||
this.handleActivity_(); | ||
} else { | ||
this.handleInactive_(); | ||
} | ||
} | ||
|
||
/** | ||
* Remove all listeners associated with this Activity instance. | ||
* @private | ||
*/ | ||
unlisten_() { | ||
for (let i = 0; i < this.unlistenFuncs_.length; i++) { | ||
const unlistenFunc = this.unlistenFuncs_[i]; | ||
// TODO(britice): Due to eslint typechecking, this check may not be | ||
// necessary. | ||
if (typeof unlistenFunc === 'function') { | ||
unlistenFunc(); | ||
} | ||
} | ||
this.unlistenFuncs_ = []; | ||
} | ||
|
||
/** @private */ | ||
cleanup_() { | ||
this.unlisten_(); | ||
} | ||
|
||
/** | ||
* Get total engaged time since the page became visible. | ||
* @return {number} | ||
*/ | ||
getTotalEngagedTime() { | ||
const secondsSinceStart = Math.floor(this.getTimeSinceStart_() / 1000); | ||
return this.activityHistory_.getTotalEngagedTime(secondsSinceStart); | ||
} | ||
}; | ||
|
||
|
||
/** | ||
* @param {!Window} win | ||
* @return {!Activity} | ||
*/ | ||
export function installActivityService(win) { | ||
return getService(win, 'activity', () => { | ||
return new Activity(win); | ||
}); | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@cramforce I see the reason why it is better to put this here. How do you make sure that any place that is using activity service calls this first and is not just dependent on amp-analytics calling it for them? For example, how does amp-pixel work with this var? do we need a call to install the service there as well?
Would having this code in url-replacements be bad?