feat(aio): detect mobile device and tell user live-example is not available

Adds DeviceService to detect mobile device and listen for window resize events.
This commit is contained in:
Ward Bell 2017-04-10 18:10:38 -07:00 committed by Pete Bacon Darwin
parent 3f307ff061
commit 24670667f1
7 changed files with 125 additions and 28 deletions

View File

@ -3,10 +3,12 @@ import { APP_BASE_HREF } from '@angular/common';
import { Http } from '@angular/http';
import { By } from '@angular/platform-browser';
import { BehaviorSubject} from 'rxjs/BehaviorSubject';
import { of } from 'rxjs/observable/of';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { DeviceService } from 'app/shared/device.service';
import { GaService } from 'app/shared/ga.service';
import { SearchResultsComponent } from 'app/search/search-results/search-results.component';
import { SearchBoxComponent } from 'app/search/search-box/search-box.component';
@ -36,6 +38,7 @@ describe('AppComponent', () => {
imports: [ AppModule ],
providers: [
{ provide: APP_BASE_HREF, useValue: '/' },
{ provide: DeviceService, useClass: TestDeviceService },
{ provide: GaService, useClass: TestGaService },
{ provide: Http, useClass: TestHttp },
{ provide: LocationService, useFactory: () => new MockLocationService(initialUrl) },
@ -330,6 +333,14 @@ describe('AppComponent', () => {
//// test helpers ////
class TestDeviceService {
// Show sidenav next to the main doc when display width on current device is greater than this.
readonly sideBySideWidth = 1032;
// Default to "wide", desktop browser.
displayWidth = new BehaviorSubject(this.sideBySideWidth + 1);
isMobile = false;
}
class TestGaService {
locationChanged = jasmine.createSpy('locationChanged');
}

View File

@ -4,6 +4,7 @@ import { MdSidenav } from '@angular/material';
import { AutoScrollService } from 'app/shared/auto-scroll.service';
import { CurrentNode, NavigationService, NavigationViews, NavigationNode, VersionInfo } from 'app/navigation/navigation.service';
import { DeviceService } from 'app/shared/device.service';
import { DocumentService, DocumentContents } from 'app/documents/document.service';
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
import { LocationService } from 'app/shared/location.service';
@ -11,7 +12,6 @@ import { NavMenuComponent } from 'app/layout/nav-menu/nav-menu.component';
import { SearchResultsComponent } from 'app/search/search-results/search-results.component';
import { SwUpdateNotificationsService } from 'app/sw-updates/sw-update-notifications.service';
const sideNavView = 'SideNav';
@Component({
@ -28,8 +28,6 @@ export class AppComponent implements OnInit {
isSideBySide = false;
private isSideNavDoc = false;
private previousNavView: string;
// Set to 1032 to account for computed html window size
private readonly sideBySideWidth = 1032;
sideNavNodes: NavigationNode[];
topMenuNodes: NavigationNode[];
@ -58,6 +56,7 @@ export class AppComponent implements OnInit {
constructor(
private autoScrollService: AutoScrollService,
private deviceService: DeviceService,
private documentService: DocumentService,
private locationService: LocationService,
private navigationService: NavigationService,
@ -93,7 +92,7 @@ export class AppComponent implements OnInit {
this.swUpdateNotifications.enable();
this.onResize(window.innerWidth);
this.deviceService.displayWidth.subscribe(width => this.onResize(width));
}
// Scroll to the anchor in the hash fragment.
@ -107,9 +106,8 @@ export class AppComponent implements OnInit {
this.autoScroll();
}
@HostListener('window:resize', ['$event.target.innerWidth'])
onResize(width) {
this.isSideBySide = width > this.sideBySideWidth;
this.isSideBySide = width > this.deviceService.sideBySideWidth;
}
@HostListener('click', ['$event.target', '$event.button', '$event.ctrlKey', '$event.metaKey', '$event.altKey'])

View File

@ -15,6 +15,7 @@ import { SwUpdatesModule } from 'app/sw-updates/sw-updates.module';
import { AppComponent } from 'app/app.component';
import { ApiService } from 'app/embedded/api/api.service';
import { DeviceService } from 'app/shared/device.service';
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
import { DtComponent } from 'app/layout/doc-viewer/dt.component';
import { EmbeddedModule } from 'app/embedded/embedded.module';
@ -59,6 +60,7 @@ import { AutoScrollService } from 'app/shared/auto-scroll.service';
],
providers: [
ApiService,
DeviceService,
GaService,
Logger,
Location,

View File

@ -1,15 +1,18 @@
<span *ngIf="!isEmbedded">
<a [href]="plnkr" target="_blank" title="{{title}}">{{title}}</a>
<span *ngIf="enableDownload">
/ <a [href]="zip" download title="Download example">download example</a>
<span [ngSwitch]="mode">
<span *ngSwitchCase="'mobile'">{{title}} <em>(not available on mobile devices)</em></span>
<span *ngSwitchCase="'embedded'">
<div *ngIf="showEmbedded" title="{{title}}">
<aio-embedded-plunker [src]="plnkr"></aio-embedded-plunker>
</div>
<img *ngIf="!showEmbedded" (click)="toggleEmbedded()" [src]="plnkrImg" width="100%" height="100%" alt="{{title}}">
<p *ngIf="enableDownload">
You can also <a [href]="zip" download title="Download example">download this example</a>.
</p>
</span>
<span *ngSwitchDefault>
<a [href]="plnkr" target="_blank" title="{{title}}">{{title}}</a>
<span *ngIf="enableDownload">
/ <a [href]="zip" download title="Download example">download example</a>
</span>
</span>
</span>
<div *ngIf="isEmbedded">
<div *ngIf="showEmbedded" title="{{title}}">
<aio-embedded-plunker [src]="plnkr"></aio-embedded-plunker>
</div>
<img *ngIf="!showEmbedded" (click)="toggleEmbedded()" [src]="plnkrImg" width="100%" height="100%" alt="{{title}}">
<p *ngIf="enableDownload">
You can also <a [href]="zip" download title="Download example">download this example</a>.
</p>
</div>

View File

@ -1,9 +1,9 @@
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Component, DebugElement, ElementRef } from '@angular/core';
import { Location } from '@angular/common';
import { DeviceService } from 'app/shared/device.service';
import { LiveExampleComponent, EmbeddedPlunkerComponent } from './live-example.component';
const defaultTestPath = '/test';
@ -17,6 +17,13 @@ describe('LiveExampleComponent', () => {
let liveExampleContent: string;
//////// test helpers ////////
class TestDeviceService {
isMobile = false;
}
class TestMobileDeviceService {
isMobile = true;
}
@Component({
selector: 'aio-host-comp',
@ -54,7 +61,10 @@ describe('LiveExampleComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ HostComponent, LiveExampleComponent, EmbeddedPlunkerComponent ],
providers: [ {provide: Location, useClass: TestLocation }]
providers: [
{ provide: DeviceService, useClass: TestDeviceService },
{ provide: Location, useClass: TestLocation }
]
})
// Disable the <iframe> within the EmbeddedPlunkerComponent
.overrideComponent(EmbeddedPlunkerComponent, {set: {template: 'NO IFRAME'}});
@ -204,7 +214,7 @@ describe('LiveExampleComponent', () => {
it('should have hidden, embedded plunker', async(() => {
setHostTemplate('<live-example embedded></live-example>');
testComponent(() => {
expect(liveExampleComponent.isEmbedded).toBe(true, 'component.isEmbedded');
expect(liveExampleComponent.mode).toBe('embedded', 'component is embedded');
expect(liveExampleComponent.showEmbedded).toBe(false, 'component.showEmbedded');
expect(getEmbeddedPlunkerComponent()).toBeNull('no EmbeddedPlunkerComponent');
});
@ -254,7 +264,7 @@ describe('LiveExampleComponent', () => {
setHostTemplate('<live-example embedded></live-example>');
testComponent(() => {
clickImg();
expect(liveExampleComponent.isEmbedded).toBe(true, 'component.isEmbedded');
expect(liveExampleComponent.mode).toBe('embedded', 'component is embedded');
expect(liveExampleComponent.showEmbedded).toBe(true, 'component.showEmbedded');
expect(getEmbeddedPlunkerComponent()).toBeDefined('has EmbeddedPlunkerComponent');
});
@ -262,4 +272,28 @@ describe('LiveExampleComponent', () => {
});
});
describe('when mobile', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{ provide: DeviceService, useClass: TestMobileDeviceService }]
});
});
it('should say that live example is not available on mobile', async(() => {
testPath = '/tutorial/toh-pt1';
testComponent(() => {
expect(liveExampleDe.nativeElement.innerText).toContain('not available on mobile');
});
}));
it('should say that the embedded live example is not available on mobile', async(() => {
setHostTemplate('<live-example embedded></live-example>');
testComponent(() => {
expect(liveExampleDe.nativeElement.innerText).toContain('not available on mobile');
});
}));
});
});

View File

@ -2,6 +2,8 @@
import { Component, ElementRef, Input, OnInit, AfterViewInit, ViewChild } from '@angular/core';
import { Location } from '@angular/common';
import { DeviceService } from 'app/shared/device.service';
const defaultPlnkrImg = 'plunker/placeholder.png';
const imageBase = 'assets/images/';
const liveExampleBase = 'content/live-examples/';
@ -10,7 +12,7 @@ const zipBase = 'content/zips/';
/**
* Angular.io Live Example Embedded Component
*
* Renders a link to a live/host example of the doc page.
* Renders a link to a live/host example of the doc page (except on mobile).
*
* All attributes and the text content are optional
*
@ -66,14 +68,18 @@ const zipBase = 'content/zips/';
export class LiveExampleComponent implements OnInit {
enableDownload = true;
isEmbedded = false;
mode: string;
plnkr: string;
plnkrImg: string;
showEmbedded = false;
title: string;
zip: string;
constructor(private elementRef: ElementRef, location: Location ) {
constructor(
deviceService: DeviceService,
private elementRef: ElementRef,
location: Location ) {
const attrs = this.getAttrs();
let exampleDir = attrs.name;
@ -85,8 +91,8 @@ export class LiveExampleComponent implements OnInit {
let plnkrStyle = 'eplnkr';
this.isEmbedded = boolFromAtty(attrs.embedded);
if (!this.isEmbedded) {
const isEmbedded = boolFromAtty(attrs.embedded);
if (!isEmbedded) {
// Not embedded in doc page; determine if is embedded- or flat-style in another browser tab.
// External plunker is embedded style by default.
// Make flat style with `flat-style` or `embedded-style="false`
@ -99,6 +105,8 @@ export class LiveExampleComponent implements OnInit {
plnkrStyle = isEmbeddedStyle ? 'eplnkr' : 'plnkr';
}
this.mode = deviceService.isMobile ? 'mobile' : isEmbedded ? 'embedded' : 'default';
const plnkrName = attrs.plnkr ? attrs.plnkr.trim() + '.' : '';
this.plnkr = `${liveExampleBase}${exampleDir}/${plnkrName}${plnkrStyle}.html`;

View File

@ -0,0 +1,41 @@
// Inquire about the state of the user's device
import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs/ReplaySubject';
@Injectable()
export class DeviceService {
// Show sidenav next to the main doc when display width on current device is greater than this.
readonly sideBySideWidth = 1032;
isMobile = false;
displayWidth = new ReplaySubject<number>(1);
constructor() {
this.isMobile = this.isMobileCheck();
if (window) {
window.onresize = () => this.onResize();
this.onResize();
} else {
// when no window, pretend the display is wide.
this.onResize(this.sideBySideWidth + 1);
}
}
isMobileCheck() {
if (!window) { return false; }
let check = false;
// http://stackoverflow.com/questions/11381673/detecting-a-mobile-browser
// tslint:disable-next-line:curly max-line-length whitespace
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window['opera']);
return check;
}
onResize(width?: number) {
this.displayWidth.next(width == null ? window.innerWidth : width);
}
}