Skip to content
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

✨[amp-story-player] Adds navigation logic #26751

Merged
merged 8 commits into from
Feb 19, 2020
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/OWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
owners: [{name: 'ampproject/wg-analytics'}],
},
{
pattern: '{amp-story-player,amp-story-player-manager}.js',
pattern: '{amp-story-*}.js',
owners: [{name: 'newmuis'}, {name: 'gmajoulet'}, {name: 'enriqe'}],
},
{
Expand Down
80 changes: 80 additions & 0 deletions src/amp-story-player-iframe-pool.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* Copyright 2020 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.
*/

/**
* Manages the iframes used to host the stories inside the player. It keeps
* track of the iframes hosting stories, and what stories have an iframe.
*/
export class IframePool {
/** @public */
constructor() {
/** @private @const {!Array<number>} */
this.iframePool_ = [];

/** @private @const {!Array<number>} */
this.storyIdsWithIframe_ = [];
}

/**
* @param {number} idx
* @public
*/
addIframeIdx(idx) {
this.iframePool_.push(idx);
}

/**
* @param {number} idx
* @public
*/
addStoryIdx(idx) {
this.storyIdsWithIframe_.push(idx);
}

/**
* Takes the leftmost iframe and allocates it to the next story to the right
* without an iframe. It also updates the storyIdsWithIframe by removing the
* reference to the detached story and adds the new one.
* @param {number} nextStoryIdx
* @return {number} Index of the detached story.
* @public
*/
rotateLeft(nextStoryIdx) {
Enriqe marked this conversation as resolved.
Show resolved Hide resolved
const detachedStoryIdx = this.storyIdsWithIframe_.shift();
this.storyIdsWithIframe_.push(nextStoryIdx);

this.iframePool_.push(this.iframePool_.shift());

return detachedStoryIdx;
}

/**
* Takes the rightmost iframe and allocates it to the next story to the left
* without an iframe. It also updates the storyIdsWithIframe by removing the
* reference to the detached story and adds the new one.
* @param {number} nextStoryIdx
* @return {number} Index of the detached story.
* @public
*/
rotateRight(nextStoryIdx) {
const detachedStoryIdx = this.storyIdsWithIframe_.pop();
this.storyIdsWithIframe_.unshift(nextStoryIdx);

this.iframePool_.unshift(this.iframePool_.pop());

return detachedStoryIdx;
}
}
211 changes: 173 additions & 38 deletions src/amp-story-player.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ import {
parseUrlWithA,
removeFragment,
} from './url';
import {dict} from './utils/object';
import {dict, map} from './utils/object';
// Source for this constant is css/amp-story-player-iframe.css
import {IframePool} from './amp-story-player-iframe-pool';
import {VisibilityState} from './visibility-state';
import {cssText} from '../build/amp-story-player-iframe.css';
import {findIndex} from './utils/array';
import {setStyle} from './style';
import {toArray} from './types';

Expand All @@ -36,6 +37,12 @@ const LoadStateClass = {
ERROR: 'i-amphtml-story-player-error',
};

/** @const {number} */
const MAX_IFRAMES = 3;

/** @const {string} */
export const IFRAME_IDX = '__AMP_IFRAME_IDX__';

/**
* Note that this is a vanilla JavaScript class and should not depend on AMP
* services, as v0.js is not expected to be loaded in this context.
Expand Down Expand Up @@ -78,6 +85,15 @@ export class AmpStoryPlayer {

/** @private {boolean} */
this.isLaidOut_ = false;

/** @private {!IframePool} */
this.iframePool_ = new IframePool();

/** @private {!Object<string, !Promise>} */
this.handshakePromises_ = map();

/** @private {number} */
this.currentIdx_ = 0;
}

/**
Expand All @@ -93,9 +109,21 @@ export class AmpStoryPlayer {
this.stories_ = toArray(this.element_.querySelectorAll('a'));

this.initializeShadowRoot_();
this.initializeIframes_();
}

/** @private */
initializeIframes_() {
for (let idx = 0; idx < MAX_IFRAMES && idx < this.stories_.length; idx++) {
const story = this.stories_[idx];
this.buildIframe_(story);

// TODO(#26308): Build all child iframes.
this.buildIframe_(this.stories_[0]);
story[IFRAME_IDX] = idx;
this.setUpMessagingForIframe_(story, this.iframes_[idx]);

this.iframePool_.addIframeIdx(idx);
this.iframePool_.addStoryIdx(idx);
}
}

/** @private */
Expand Down Expand Up @@ -128,26 +156,30 @@ export class AmpStoryPlayer {

this.initializeLoadingListeners_(iframeEl);
this.rootEl_.appendChild(iframeEl);
}

this.initializeHandshake_(story, iframeEl).then(
messaging => {
const iframeIdx = findIndex(
this.iframes_,
iframe => iframe === iframeEl
);

messaging.setDefaultHandler(() => {});

this.messagingFor_[iframeIdx] = messaging;

// TODO(#26308): Appropiately set visibility to stories.
this.displayStory_(iframeIdx);
},
err => {
console /*OK*/
.log({err});
}
);
/**
* Sets up messaging for a story inside an iframe.
* @param {!Element} story
* @param {!Element} iframeEl
* @private
*/
setUpMessagingForIframe_(story, iframeEl) {
const iframeIdx = story[IFRAME_IDX];

this.handshakePromises_[iframeIdx] = new Promise(resolve => {
this.initializeHandshake_(story, iframeEl).then(
messaging => {
messaging.setDefaultHandler(() => Promise.resolve());
this.messagingFor_[iframeIdx] = messaging;
resolve();
},
err => {
console /*OK*/
.log({err});
}
);
});
}

/**
Expand Down Expand Up @@ -193,36 +225,136 @@ export class AmpStoryPlayer {
return;
}

// TODO(#26308): Layout all child iframes.
this.layoutIframe_(this.stories_[0], this.iframes_[0]);
for (let idx = 0; idx < this.stories_.length && idx < MAX_IFRAMES; idx++) {
const story = this.stories_[idx];
const iframeIdx = story[IFRAME_IDX];
const iframe = this.iframes_[iframeIdx];
this.layoutIframe_(
story,
iframe,
idx === 0 ? VisibilityState.VISIBLE : VisibilityState.PRERENDER
);
}

this.isLaidOut_ = true;
}

/**
* Navigates to the next story in the player.
* @private
* @visibleForTesting
*/
next_() {
if (this.currentIdx_ + 1 >= this.stories_.length) {
return;
}

this.currentIdx_++;

const previousStory = this.stories_[this.currentIdx_ - 1];
this.updateVisibilityState_(
previousStory[IFRAME_IDX],
VisibilityState.PAUSED
);

const currentStory = this.stories_[this.currentIdx_];
this.updateVisibilityState_(
currentStory[IFRAME_IDX],
VisibilityState.VISIBLE
);

const nextStoryIdx = this.currentIdx_ + 1;
if (
nextStoryIdx < this.stories_.length &&
this.stories_[nextStoryIdx][IFRAME_IDX] === undefined
) {
this.allocateIframeForStory_(nextStoryIdx);
}
}

/**
* Navigates to the previous story in the player.
* @private
* @visibleForTesting
*/
previous_() {
if (this.currentIdx_ - 1 < 0) {
return;
}

this.currentIdx_--;

const previousStory = this.stories_[this.currentIdx_ + 1];
this.updateVisibilityState_(
previousStory[IFRAME_IDX],
VisibilityState.PAUSED
Enriqe marked this conversation as resolved.
Show resolved Hide resolved
);

const currentStory = this.stories_[this.currentIdx_];
this.updateVisibilityState_(
currentStory[IFRAME_IDX],
VisibilityState.VISIBLE
);

const nextStoryIdx = this.currentIdx_ - 1;
if (
nextStoryIdx >= 0 &&
this.stories_[nextStoryIdx][IFRAME_IDX] === undefined
) {
this.allocateIframeForStory_(nextStoryIdx, true /** reverse */);
}
}

/**
* Detaches iframe from a story and gives it to the next story. It detaches
* the iframe from the story furthest away; depending where the user is
* navigating and allocates it to a story that the user is close to seeing.
* @param {number} nextStoryIdx
* @param {boolean} reverse
* @private
*/
allocateIframeForStory_(nextStoryIdx, reverse = false) {
const detachedStoryIdx = reverse
? this.iframePool_.rotateRight(nextStoryIdx)
: this.iframePool_.rotateLeft(nextStoryIdx);

const detachedStory = this.stories_[detachedStoryIdx];
const nextStory = this.stories_[nextStoryIdx];

nextStory[IFRAME_IDX] = detachedStory[IFRAME_IDX];
detachedStory[IFRAME_IDX] = undefined;

const nextIframe = this.iframes_[nextStory[IFRAME_IDX]];
this.layoutIframe_(nextStory, nextIframe, VisibilityState.PRERENDER);
this.setUpMessagingForIframe_(nextStory, nextIframe);
}

/**
* @param {!Element} story
* @param {!Element} iframe
* @param {string} visibilityState
Enriqe marked this conversation as resolved.
Show resolved Hide resolved
* @private
*/
layoutIframe_(story, iframe) {
const {href} = this.getEncodedLocation_(story.href);
layoutIframe_(story, iframe, visibilityState) {
const {href} = this.getEncodedLocation_(story.href, visibilityState);

iframe.setAttribute('src', href);
}

/**
* Gets encoded url for viewer usage.
* Gets encoded url for player usage.
* @param {string} href
* @param {string} visibilityState
* @return {!Location}
* @private
*/
getEncodedLocation_(href) {
getEncodedLocation_(href, visibilityState = VisibilityState.INACTIVE) {
const {location} = this.win_;
const url = parseUrlWithA(this.cachedA_, location.href);

const params = dict({
'amp_js_v': '0.1',
'visibilityState': 'inactive',
'visibilityState': visibilityState,
'origin': url.origin,
'showStoryUrlInfo': '0',
'storyPlayer': 'v0',
Expand All @@ -243,16 +375,19 @@ export class AmpStoryPlayer {
}

/**
* Sends a message to the story document to make it visible.
* @private
* Updates the visibility state of the story inside the iframe.
* @param {number} iframeIdx
* @param {string} visibilityState
* @private
*/
displayStory_(iframeIdx) {
this.messagingFor_[iframeIdx].sendRequest(
'visibilitychange',
{state: 'visible'},
true
);
updateVisibilityState_(iframeIdx, visibilityState) {
this.handshakePromises_[iframeIdx].then(() => {
this.messagingFor_[iframeIdx].sendRequest(
'visibilitychange',
{state: visibilityState},
true
);
});
Enriqe marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down
Loading