Skip to content

feat(youtube-player): Add width and height as inputs #16734

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

Merged
merged 1 commit into from
Aug 16, 2019
Merged
Show file tree
Hide file tree
Changes from all 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/youtube-player/public-api.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './youtube-module';
export * from './youtube-player';
export {YouTubePlayer} from './youtube-player';
57 changes: 53 additions & 4 deletions src/youtube-player/youtube-player.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {Component, ViewChild} from '@angular/core';
import {YouTubePlayerModule} from './index';
import {YouTubePlayer} from './youtube-player';
import {YouTubePlayerModule} from './youtube-module';
import {YouTubePlayer, DEFAULT_PLAYER_WIDTH, DEFAULT_PLAYER_HEIGHT} from './youtube-player';
import {createFakeYtNamespace} from './fake-youtube-player';

const VIDEO_ID = 'a12345';
Expand Down Expand Up @@ -48,6 +48,8 @@ describe('YoutubePlayer', () => {
expect(playerCtorSpy).toHaveBeenCalledWith(
containerElement, jasmine.objectContaining({
videoId: VIDEO_ID,
width: DEFAULT_PLAYER_WIDTH,
height: DEFAULT_PLAYER_HEIGHT,
}));
});

Expand Down Expand Up @@ -85,6 +87,51 @@ describe('YoutubePlayer', () => {
containerElement, jasmine.objectContaining({videoId: 'otherId2'}));
});

it('responds to changes in size', () => {
testComponent.width = 5;
fixture.detectChanges();

expect(playerSpy.setSize).not.toHaveBeenCalled();

events.onReady({target: playerSpy});

expect(playerSpy.setSize).toHaveBeenCalledWith(5, DEFAULT_PLAYER_HEIGHT);
expect(testComponent.youtubePlayer.width).toBe(5);
expect(testComponent.youtubePlayer.height).toBe(DEFAULT_PLAYER_HEIGHT);

testComponent.height = 6;
fixture.detectChanges();

expect(playerSpy.setSize).toHaveBeenCalledWith(5, 6);
expect(testComponent.youtubePlayer.width).toBe(5);
expect(testComponent.youtubePlayer.height).toBe(6);

testComponent.videoId = undefined;
fixture.detectChanges();
testComponent.videoId = VIDEO_ID;
fixture.detectChanges();

expect(playerCtorSpy).toHaveBeenCalledWith(
jasmine.any(Element), jasmine.objectContaining({width: 5, height: 6}));
expect(testComponent.youtubePlayer.width).toBe(5);
expect(testComponent.youtubePlayer.height).toBe(6);

events.onReady({target: playerSpy});
testComponent.width = undefined;
fixture.detectChanges();

expect(playerSpy.setSize).toHaveBeenCalledWith(DEFAULT_PLAYER_WIDTH, 6);
expect(testComponent.youtubePlayer.width).toBe(DEFAULT_PLAYER_WIDTH);
expect(testComponent.youtubePlayer.height).toBe(6);

testComponent.height = undefined;
fixture.detectChanges();

expect(playerSpy.setSize).toHaveBeenCalledWith(DEFAULT_PLAYER_WIDTH, DEFAULT_PLAYER_HEIGHT);
expect(testComponent.youtubePlayer.width).toBe(DEFAULT_PLAYER_WIDTH);
expect(testComponent.youtubePlayer.height).toBe(DEFAULT_PLAYER_HEIGHT);
});

it('proxies events as output', () => {
events.onReady({target: playerSpy});
expect(testComponent.onReady).toHaveBeenCalledWith({target: playerSpy});
Expand Down Expand Up @@ -113,7 +160,7 @@ describe('YoutubePlayer', () => {
@Component({
selector: 'test-app',
template: `
<youtube-player #player [videoId]="videoId" *ngIf="visible"
<youtube-player #player [videoId]="videoId" *ngIf="visible" [width]="width" [height]="height"
(ready)="onReady($event)"
(stateChange)="onStateChange($event)"
(playbackQualityChange)="onPlaybackQualityChange($event)"
Expand All @@ -126,11 +173,13 @@ describe('YoutubePlayer', () => {
class TestApp {
videoId: string | undefined = VIDEO_ID;
visible = true;
width: number | undefined;
height: number | undefined;
onReady = jasmine.createSpy('onReady');
onStateChange = jasmine.createSpy('onStateChange');
onPlaybackQualityChange = jasmine.createSpy('onPlaybackQualityChange');
onPlaybackRateChange = jasmine.createSpy('onPlaybackRateChange');
onError = jasmine.createSpy('onError');
onApiChange = jasmine.createSpy('onApiChange');
@ViewChild('player', {static: true}) youtubePlayer: YouTubePlayer;
@ViewChild('player', {static: false}) youtubePlayer: YouTubePlayer;
}
52 changes: 46 additions & 6 deletions src/youtube-player/youtube-player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ declare global {
interface Window { YT: typeof YT | undefined; }
}

export const DEFAULT_PLAYER_WIDTH = 640;
export const DEFAULT_PLAYER_HEIGHT = 390;

// The native YT.Player doesn't expose the set videoId, but we need it for
// convenience.
interface Player extends YT.Player {
Expand All @@ -62,17 +65,33 @@ type UninitializedPlayer = Pick<Player, 'videoId' | 'destroy' | 'addEventListene
})
export class YouTubePlayer implements AfterViewInit, OnDestroy {
/** YouTube Video ID to view */
get videoId(): string | undefined {
return this._player && this._player.videoId;
}

@Input()
get videoId(): string | undefined { return this._player && this._player.videoId; }
set videoId(videoId: string | undefined) {
this._videoId.emit(videoId);
}

private _videoId = new EventEmitter<string | undefined>();

/** Height of video player */
@Input()
get height(): number | undefined { return this._height; }
set height(height: number | undefined) {
this._height = height || DEFAULT_PLAYER_HEIGHT;
this._heightObs.emit(this._height);
}
private _height = DEFAULT_PLAYER_HEIGHT;
private _heightObs = new EventEmitter<number>();

/** Width of video player */
@Input()
get width(): number | undefined { return this._width; }
set width(width: number | undefined) {
this._width = width || DEFAULT_PLAYER_WIDTH;
this._widthObs.emit(this._width);
}
private _width = DEFAULT_PLAYER_WIDTH;
private _widthObs = new EventEmitter<number>();

/** Outputs are direct proxies from the player itself. */
@Output() ready = new EventEmitter<YT.PlayerEvent>();
@Output() stateChange = new EventEmitter<YT.OnStateChangeEvent>();
Expand All @@ -94,17 +113,25 @@ export class YouTubePlayer implements AfterViewInit, OnDestroy {
'Please install the YouTube Player API Reference for iframe Embeds: ' +
'https://developers.google.com/youtube/iframe_api_reference');
}
// Add initial values to all of the inputs.
const widthObs = this._widthObs.pipe(startWith(this._width));
const heightObs = this._heightObs.pipe(startWith(this._height));

/** An observable of the currently loaded player. */
const playerObs =
createPlayerObservable(
this._youtubeContainer,
this._videoId,
widthObs,
heightObs,
this.createEventsBoundInZone(),
).pipe(waitUntilReady(), takeUntil(this._destroyed), publish());

/** Set up side effects to bind inputs to the player. */
playerObs.subscribe(player => this._player = player);

bindSizeToPlayer(playerObs, widthObs, heightObs);

bindCueVideoCall(playerObs, this._videoId, this._destroyed);

// After all of the subscriptions are set up, connect the observable.
Expand Down Expand Up @@ -146,6 +173,16 @@ export class YouTubePlayer implements AfterViewInit, OnDestroy {
}
}

/** Listens to changes to the given width and height and sets it on the player. */
function bindSizeToPlayer(
playerObs: Observable<YT.Player | undefined>,
widthObs: Observable<number>,
heightObs: Observable<number>
) {
return combineLatest(playerObs, widthObs, heightObs)
.subscribe(([player, width, height]) => player && player.setSize(width, height));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason not to just call setSize in ngOnChanges without the streams?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Width and height are needed for the constructor of the player as well, and I think a stream fits better when managing the player initialization. I could use ngOnChanges for the setSize call, but that won't eliminate the streams entirely, so I think it'll just add complexity if we have two different means of monitoring changes on the same value.

}

/**
* Returns an observable that emits the loaded player once it's ready. Certain properties/methods
* won't be available until the iframe finishes loading.
Expand Down Expand Up @@ -190,13 +227,16 @@ function fromPlayerOnReady(player: UninitializedPlayer): Observable<Player> {
function createPlayerObservable(
youtubeContainer: Observable<HTMLElement>,
videoIdObs: Observable<string | undefined>,
widthObs: Observable<number>,
heightObs: Observable<number>,
events: YT.Events,
): Observable<UninitializedPlayer | undefined> {

const playerOptions =
videoIdObs
.pipe(
map((videoId) => videoId ? ({videoId, events}) : undefined),
withLatestFrom(combineLatest(widthObs, heightObs)),
map(([videoId, [width, height]]) => videoId ? ({videoId, width, height, events}) : undefined),
);

return combineLatest(youtubeContainer, playerOptions)
Expand Down