Perfromance fix (tests still failing)

This commit is contained in:
Roman Hotsiy 2016-11-23 01:23:32 +02:00
parent 5bd0ac2d11
commit 4208660a6f
No known key found for this signature in database
GPG Key ID: 5CB7B3ACABA57CB0
38 changed files with 508 additions and 145 deletions

View File

@ -27,6 +27,10 @@ $sub-schema-offset: ($bullet-size / 2) + $bullet-margin;
width: 75%;
box-sizing: border-box;
> div {
line-height: 1;
}
}
.param-range {
@ -41,7 +45,7 @@ $sub-schema-offset: ($bullet-size / 2) + $bullet-margin;
}
.param-description {
font-size: 13px;
//font-size: 14px;
}
.param-required {

View File

@ -12,7 +12,8 @@ var cache = {};
@Component({
selector: 'json-schema-lazy',
entryComponents: [ JsonSchema ],
template: ''
template: '',
styles: [':host { display:none }']
})
export class JsonSchemaLazy implements OnDestroy, AfterViewInit {
@Input() pointer: string;
@ -66,7 +67,7 @@ export class JsonSchemaLazy implements OnDestroy, AfterViewInit {
this._loadAfterSelf();
return;
}
insertAfter($element.cloneNode(true), this.elementRef.nativeElement);
//insertAfter($element.cloneNode(true), this.elementRef.nativeElement);
this.loaded = true;
} else {
cache[this.pointer] = this._loadAfterSelf();

View File

@ -0,0 +1,49 @@
'use strict';
import { Input, HostBinding, Component, OnInit, ChangeDetectionStrategy, ElementRef, ChangeDetectorRef } from '@angular/core';
import JsonPointer from '../../utils/JsonPointer';
import { BaseComponent, SpecManager } from '../base';
import { SchemaHelper } from '../../services/schema-helper.service';
import { OptionsService, AppStateService } from '../../services/';
@Component({
selector: 'loading-bar',
template: `
<span [style.width]='progress + "%"'> </span>
`,
styles: [`
:host {
position: fixed;
top: 0;
left: 0;
right: 0;
display: block;
height: 5px;
z-index: 100;
}
span {
display: block;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: attr(progress percentage);
background-color: #5f7fc3;
transition: right 0.2s linear;
}
`],
//changeDetection: ChangeDetectionStrategy.OnPush
})
export class LoadingBar {
@Input() progress:number = 0;
@HostBinding('style.display') display = 'block';
ngOnChanges(ch) {
if (ch.progress.currentValue === 100) {
setTimeout(() => {
this.display = 'none';
}, 500);
}
}
}

View File

@ -1,18 +1,18 @@
<div class="method">
<div class="method-content">
<h2 class="method-header sharable-header">
<a class="share-link" href="#{{method.anchor}}"></a>{{method.summary}}
</h2>
<div class="method-tags" *ngIf="method.info.tags.length">
<a *ngFor="let tag of method.info.tags" attr.href="#tag/{{tag}}"> {{tag}} </a>
</div>
<p *ngIf="method.info.description" class="method-description"
[innerHtml]="method.info.description | marked">
<div class="method" *ngIf="method">
<div class="method-content">
<h2 class="method-header sharable-header">
<a class="share-link" href="#{{method.anchor}}"></a>{{method.summary}}
</h2>
<div class="method-tags" *ngIf="method.info.tags.length">
<a *ngFor="let tag of method.info.tags" attr.href="#tag/{{tag}}"> {{tag}} </a>
</div>
<p *ngIf="method.info.description" class="method-description"
[innerHtml]="method.info.description | marked">
</p>
<params-list pointer="{{pointer}}/parameters"> </params-list>
<responses-list pointer="{{pointer}}/responses"> </responses-list>
</div>
<div class="method-samples">
</div>
<div class="method-samples">
<h4 class="method-params-subheader">Definition</h4>
<div class="method-endpoint">
@ -30,5 +30,5 @@
<br>
<responses-samples pointer="{{pointer}}/responses"> </responses-samples>
</div>
</div>
</div>
<div>

View File

@ -6,18 +6,20 @@
display: block;
border-bottom: 1px solid rgba(127, 127, 127, 0.25);
margin-top: 1em;
transform: translateZ(0);
z-index: 2;
}
:host:last-of-type {
border-bottom: 0;
}
// :host:last-of-type {
// border-bottom: 0;
// }
.method-header {
margin-bottom: .9em;
margin-bottom: calc(1em - 6px);
}
.method-endpoint {
margin: 0 0 2em 0;
//margin: 0 0 2px 0;
padding: 10px 20px;
border-radius: $border-radius*2;
background-color: darken($black, 2%);
@ -31,8 +33,8 @@
padding-top: 1px;
padding-bottom: 0;
margin: 0;
font-size: .8em;
color: $black;
font-size: 12/14em;
color: $black;
vertical-align: middle;
display: inline-block;
border-radius: $border-radius;

View File

@ -1,9 +1,9 @@
'use strict';
import { Input, Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { Input, Component, OnInit, ChangeDetectionStrategy, ElementRef, ChangeDetectorRef } from '@angular/core';
import JsonPointer from '../../utils/JsonPointer';
import { BaseComponent, SpecManager } from '../base';
import { SchemaHelper } from '../../services/schema-helper.service';
import { OptionsService } from '../../services/options.service';
import { OptionsService, AppStateService } from '../../services/';
@Component({
selector: 'method',
@ -14,10 +14,14 @@ import { OptionsService } from '../../services/options.service';
export class Method extends BaseComponent implements OnInit {
@Input() pointer:string;
@Input() tag:string;
@Input() posInfo: any;
hidden = true;
method:any;
constructor(specMgr:SpecManager, private optionsService: OptionsService) {
constructor(specMgr:SpecManager, private optionsService: OptionsService, private chDetector: ChangeDetectorRef,
private appState: AppStateService, private el: ElementRef) {
super(specMgr);
}
@ -53,6 +57,14 @@ export class Method extends BaseComponent implements OnInit {
return bodyParam;
}
show(res) {
if (res) {
this.el.nativeElement.firstElementChild.removeAttribute('hidden');
} else {
this.el.nativeElement.firstElementChild.setAttribute('hidden', 'hidden');
}
}
ngOnInit() {
this.preinit();
}

View File

@ -1,10 +1,10 @@
<div class="methods">
<div class="tag" *ngFor="let tag of tags;trackBy:trackByTagName">
<div class="tag" *ngFor="let tag of tags;let catIdx = index; trackBy:trackByTagName">
<div class="tag-info" [attr.section]="tag.id" *ngIf="!tag.headless">
<h1 class="sharable-header"> <a class="share-link" href="#tag/{{tag.name | encodeURIComponent}}"></a>{{tag.name}} </h1>
<p *ngIf="tag.description" [innerHtml]="tag.description | marked"> </p>
</div>
<method *ngFor="let method of tag.methods;trackBy:trackByPointer" [pointer]="method.pointer" [attr.pointer]="method.pointer"
<method *lazyFor="let method of tag.methods;let show = show;" [hidden]="!show" [pointer]="method.pointer" [attr.pointer]="method.pointer"
[attr.section]="method.tag" [tag]="method.tag" [attr.operation-id]="method.operationId"></method>
</div>
</div>

View File

@ -4,6 +4,11 @@
display: block;
overflow: hidden;
}
:host [hidden] {
display: none;
}
.tag-info {
padding: $section-spacing;
box-sizing: border-box;

View File

@ -23,7 +23,6 @@ describe('Redoc components', () => {
let fixture;
beforeEach(async(inject([SpecManager], ( specMgr) => {
return specMgr.load('/tests/schemas/methods-list-component.json');
})));
beforeEach(() => {

View File

@ -2,10 +2,14 @@
$hint-color: #999999;
:host {
display: block;
}
.param-list-header {
border-bottom: 1px solid rgba($text-color, .3);
padding: 0.2em 0;
margin: 3.5em 0 .8em 0;
// padding: 0.2em 0;
margin: 3em 0 1em 0;
color: rgba($text-color, .5);
font-weight: normal;
text-transform: uppercase;

View File

@ -3,6 +3,10 @@
<div class='redoc-error-details'>{{error.message}}</div>
</div>
<div class="redoc-wrap" *ngIf="specLoaded && !error">
<loading-bar [progress]="loadingProgress"> </loading-bar>
<div class="background">
<div class="background-actual"> </div>
</div>
<div class="menu-content" sticky-sidebar [scrollParent]="options.$scrollParent" [scrollYOffset]="options.scrollYOffset">
<api-logo> </api-logo>
<side-menu> </side-menu>

View File

@ -36,11 +36,17 @@
color: $text-color;
}
.menu-content {
overflow: hidden;
}
[sticky-sidebar] {
width: $side-bar-width;
background-color: $side-bar-bg-color;
overflow-y: auto;
overflow-x: hidden;
transform: translateZ(0);
z-index: 75;
@media (max-width: $side-menu-mobile-breakpoint) {
z-index: 1;
@ -51,22 +57,33 @@
.api-content {
margin-left: $side-bar-width;
z-index: 50;
position: relative;
// height: 100vh;
// overflow: scroll;
top: 0;
@media (max-width: $side-menu-mobile-breakpoint) {
padding-top: 3em;
margin-left: 0;
}
}
.api-content:before {
content: "";
background: $samples-panel-bg-color;
height: 100%;
width: $samples-panel-width;
.background {
position: fixed;
top: 0;
bottom: 0;
right: 0;
position: absolute;
z-index: -1;
left: $side-bar-width;
z-index: 1;
&-actual {
background: $samples-panel-bg-color;
left: 100% - $samples-panel-width;
right: 0;
top: 0;
bottom: 0;
position: absolute;
}
@media (max-width: $right-panel-squash-breakpoint) {
display: none;
@ -98,7 +115,8 @@
font-family: $headers-font, $headers-font-family;
color: $secondary-color;
font-weight: $headers-font-weight;
line-height: 1.4em;
line-height: 1.5;
margin-bottom: 0.5em;
}
}
@ -107,7 +125,7 @@
h2 { font-size: $h2; }
h3 { font-size: $h3; }
h4 { font-size: $h4; }
h5 { font-size: $h5; }
h5 { font-size: $h5; line-height: 20px; }
p {
font-family: $base-font, $base-font-family;

View File

@ -17,13 +17,14 @@ import * as detectScollParent from 'scrollparent';
import { SpecManager } from '../../utils/spec-manager';
import { OptionsService, Hash, MenuService, AppStateService } from '../../services/index';
import { LazyTasksService } from '../../shared/components/LazyFor/lazy-for';
import { CustomErrorHandler } from '../../utils/';
@Component({
selector: 'redoc',
templateUrl: './redoc.html',
styleUrls: ['./redoc.css'],
changeDetection: ChangeDetectionStrategy.OnPush
//changeDetection: ChangeDetectionStrategy.OnPush
})
export class Redoc extends BaseComponent implements OnInit {
static _preOptions: any;
@ -34,6 +35,8 @@ export class Redoc extends BaseComponent implements OnInit {
specLoaded: boolean;
options: any;
loadingProgress: number;
@Input() specUrl: string;
@HostBinding('class.loading') specLoading: boolean = false;
@HostBinding('class.loading-remove') specLoadingRemove: boolean = false;
@ -43,7 +46,9 @@ export class Redoc extends BaseComponent implements OnInit {
optionsMgr: OptionsService,
elementRef: ElementRef,
private changeDetector: ChangeDetectorRef,
private appState: AppStateService
private appState: AppStateService,
private lazyTasksService: LazyTasksService,
private hash: Hash
) {
super(specMgr);
// merge options passed before init
@ -66,24 +71,37 @@ export class Redoc extends BaseComponent implements OnInit {
}, 400);
}
showLoadingAnimation() {
this.specLoading = true;
this.specLoadingRemove = false;
}
load() {
this.specMgr.load(this.options.specUrl).catch(err => {
throw err;
});
this.appState.loading.subscribe(loading => {
if (loading) {
this.showLoadingAnimation();
} else {
this.hideLoadingAnimation();
}
});
this.specMgr.spec.subscribe((spec) => {
if (!spec) {
this.specLoading = true;
this.specLoaded = false;
this.appState.startLoading();
} else {
this.specLoaded = true;
this.hideLoadingAnimation();
this.changeDetector.markForCheck();
this.changeDetector.detectChanges();
}
});
}
ngOnInit() {
this.lazyTasksService.loadProgress.subscribe(progress => this.loadingProgress = progress)
this.appState.error.subscribe(_err => {
if (!_err) return;

View File

@ -53,7 +53,7 @@ header {
border-radius: $border-radius;
margin: 2px 0;
padding: 3px 10px 2px 10px;
line-height: 1.25;
line-height: 16px;
color: $sample-panel-headers-color;
&:hover {

View File

@ -22,7 +22,7 @@ header {
margin: 2px 0;
padding: 2px 8px 3px 8px;
color: $sample-panel-headers-color;
line-height: 1.25;
line-height: 16px;
&:hover {
color: #ffffff;

View File

@ -2,9 +2,9 @@
<!-- in case sample is not available for some reason -->
<pre *ngIf="sample == undefined"> Sample unavailable </pre>
<div class="action-buttons">
<span> <a *ngIf="enableButtons" (click)="collapseAll()">Collapse all</a> </span>
<span copy-button [copyText]="sample" class="hint--top-left hint--inversed"> <a>Copy</a> </span>
<span> <a *ngIf="enableButtons" (click)="expandAll()">Expand all</a> </span>
<span copy-button [copyText]="sample | json" class="hint--top hint--inversed"> <a>Copy</a> </span>
<span> <a *ngIf="enableButtons" (click)="collapseAll()">Collapse all</a> </span>
</div>
<pre [innerHtml]="sample | jsonFormatter"></pre>
</div>

View File

@ -13,46 +13,25 @@ pre {
}
.action-buttons {
display: block;
opacity: 0;
transition: opacity 0.3s ease;
transform: translateY(100%);
z-index: 1;
z-index: 3;
position: relative;
> span {
float: right;
&:last-child > a:before {
display: none;
}
}
height: 2em;
line-height: 2em;
padding-right: 10px;
text-align: right;
> span > a {
padding: 2px 10px;
color: #ffffff;
cursor: pointer;
&:before {
content: '|';
display: inline-block;
transform: translateX(-10px);
}
&:first-child {
margin-right: 0;
}
&:hover {
background-color: $black;
background-color: lighten($black, 15%);
}
}
&:after {
display: block;
content: '';
clear: both;
}
}
.snippet:hover .action-buttons {
@ -135,6 +114,7 @@ pre {
li {
position: relative;
display: block;
}
.hoverable {

View File

@ -10,10 +10,10 @@
<div *ngFor="let cat of categories; let idx = index" class="menu-cat">
<label class="menu-cat-header" (click)="activateAndScroll(idx, -1)" [hidden]="cat.headless"
[ngClass]="{active: cat.active}"> {{cat.name}}</label>
[ngClass]="{active: cat.active, disabled: !cat.ready}"> {{cat.name}}</label>
<ul class="menu-subitems" [@itemAnimation]="cat.active ? 'expanded' : 'collapsed'">
<li *ngFor="let method of cat.methods; trackBy:summary; let methIdx = index"
[ngClass]="{active: method.active}"
[ngClass]="{active: method.active, disabled: !method.ready}"
(click)="activateAndScroll(idx, methIdx)">
{{method.summary}}
</li>

View File

@ -14,13 +14,16 @@ import { MethodsList } from './MethodsList/methods-list';
import { Method } from './Method/method';
import { Warnings } from './Warnings/warnings';
import { SecurityDefinitions } from './SecurityDefinitions/security-definitions';
import { LoadingBar } from './LoadingBar/loading-bar';
import { Redoc } from './Redoc/redoc';
export const REDOC_DIRECTIVES = [
ApiInfo, ApiLogo, JsonSchema, JsonSchemaLazy, ParamsList, RequestSamples, ResponsesList,
ResponsesSamples, SchemaSample, SideMenu, MethodsList, Method, Warnings, Redoc, SecurityDefinitions
ResponsesSamples, SchemaSample, SideMenu, MethodsList, Method, Warnings, Redoc, SecurityDefinitions,
LoadingBar
];
export { ApiInfo, ApiLogo, JsonSchema, JsonSchemaLazy, ParamsList, RequestSamples, ResponsesList,
ResponsesSamples, SchemaSample, SideMenu, MethodsList, Method, Warnings, Redoc, SecurityDefinitions }
ResponsesSamples, SchemaSample, SideMenu, MethodsList, Method, Warnings, Redoc, SecurityDefinitions,
LoadingBar }

View File

@ -14,10 +14,10 @@ if (AOT) {
bootstrapRedoc = require('./bootstrap.dev').bootstrapRedoc;
}
if (IS_PRODUCTION) {
//if (IS_PRODUCTION) {
disableDebugTools();
enableProdMode();
}
//}
export const version = LIB_VERSION;

View File

@ -1,10 +1,11 @@
import { NgModule, ErrorHandler } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Redoc, SecurityDefinitions, REDOC_DIRECTIVES } from './components/index';
import { Redoc, SecurityDefinitions, Method, REDOC_DIRECTIVES } from './components/index';
import { REDOC_COMMON_DIRECTIVES, DynamicNg2Wrapper } from './shared/components/index';
import { REDOC_PIPES, KeysPipe } from './utils/pipes';
import { CustomErrorHandler } from './utils/'
import { LazyTasksService } from './shared/components/LazyFor/lazy-for';
import {
OptionsService,
@ -22,7 +23,7 @@ import { SpecManager } from './utils/spec-manager';
imports: [ CommonModule ],
declarations: [ REDOC_DIRECTIVES, REDOC_COMMON_DIRECTIVES, REDOC_PIPES ],
bootstrap: [ Redoc ],
entryComponents: [ SecurityDefinitions, DynamicNg2Wrapper ],
entryComponents: [ SecurityDefinitions, DynamicNg2Wrapper, Method ],
providers: [
SpecManager,
ScrollService,
@ -33,6 +34,7 @@ import { SpecManager } from './utils/spec-manager';
AppStateService,
ComponentParser,
ContentProjector,
LazyTasksService,
{ provide: ErrorHandler, useClass: CustomErrorHandler },
{ provide: COMPONENT_PARSER_ALLOWED, useValue: { 'security-definitions': SecurityDefinitions} }
],

View File

@ -1,11 +1,24 @@
'use strict';
import { Injectable } from '@angular/core';
import { Injectable, NgZone } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Injector } from '@angular/core';
@Injectable()
export class AppStateService {
samplesLanguage = new Subject<string>();
error = new BehaviorSubject<any>(null);
loading = new Subject<boolean>();
startLoading() {
this.loading.next(true);
}
stopLoading() {
this.loading.next(false);
}
constructor(private injector: Injector, private zone: NgZone) {
}
}

View File

@ -13,10 +13,11 @@ describe('Hash Service', () => {
beforeEach(inject([Hash], (_hash) => hashService = _hash));
it('should trigger changed event after ReDoc bootstrapped', (done) => {
spyOn(hashService.value, 'next').and.callThrough();
spyOn(hashService.value, 'next').and.stub();
specMgr.spec.next({});
setTimeout(() => {
expect(hashService.value.next).toHaveBeenCalled();
hashService.value.next.and.callThrough();
done();
});
});

View File

@ -7,7 +7,7 @@ import { SpecManager } from '../utils/spec-manager';
@Injectable()
export class Hash {
public value = new BehaviorSubject<string>('');
public value = new BehaviorSubject<string | null>(null);
constructor(private specMgr: SpecManager, private location: PlatformLocation) {
this.bind();

View File

@ -8,7 +8,8 @@ import {
import { MenuService } from './menu.service';
import { Hash } from './hash.service';
import { ScrollService } from './scroll.service';
import { LazyTasksService } from '../shared/components/LazyFor/lazy-for';
import { ScrollService, } from './scroll.service';
import { SpecManager } from '../utils/spec-manager';;
describe('Menu service', () => {
@ -16,42 +17,38 @@ describe('Menu service', () => {
TestBed.configureTestingModule({ declarations: [ TestAppComponent ] });
});
let menu, hashService, scroll;
let specMgr;
let menu, hashService, scroll, tasks;
let specMgr, appStateMock;
beforeEach(async(inject([SpecManager, Hash, ScrollService],
( _specMgr, _hash, _scroll, _menu) => {
beforeEach(async(inject([SpecManager, Hash, ScrollService, LazyTasksService],
( _specMgr, _hash, _scroll, _tasks) => {
hashService = _hash;
scroll = _scroll;
tasks = _tasks;
appStateMock = {
stopLoading: () => { /* */ },
startLoading: () => { /* */ }
};
specMgr = _specMgr;
tasks.allSync = true;
return specMgr.load('/tests/schemas/extended-petstore.yml');
})));
beforeEach(() => {
menu = new MenuService(hashService, scroll, specMgr);
menu = new MenuService(hashService, tasks, scroll, appStateMock, specMgr);
let fixture = TestBed.createComponent(TestAppComponent);
fixture.detectChanges();
});
it('should run hashScroll when hash changed', (done) => {
spyOn(menu, 'hashScroll').and.callThrough();
hashService.value.subscribe((hash) => {
if (!hash) return;
expect(menu.hashScroll).toHaveBeenCalled();
menu.hashScroll.and.callThrough();
done();
});
hashService.value.next('nonFalsy');
});
it('should scroll to method when location hash is present [jp]', (done) => {
let hash = '#tag/pet/paths/~1pet~1findByStatus/get';
spyOn(menu, 'hashScroll').and.callThrough();
spyOn(menu, 'scrollToActive').and.callThrough();
spyOn(window, 'scrollTo').and.stub();
hashService.value.subscribe((hash) => {
if (!hash) return;
expect(menu.hashScroll).toHaveBeenCalled();
expect(menu.scrollToActive).toHaveBeenCalled();
let scrollY = (<jasmine.Spy>window.scrollTo).calls.argsFor(0)[1];
expect(scrollY).toBeGreaterThan(0);
(<jasmine.Spy>window.scrollTo).and.callThrough();
@ -62,11 +59,11 @@ describe('Menu service', () => {
it('should scroll to method when location hash is present [operation]', (done) => {
let hash = '#operation/getPetById';
spyOn(menu, 'hashScroll').and.callThrough();
spyOn(menu, 'scrollToActive').and.callThrough();
spyOn(window, 'scrollTo').and.stub();
hashService.value.subscribe((hash) => {
if (!hash) return;
expect(menu.hashScroll).toHaveBeenCalled();
expect(menu.scrollToActive).toHaveBeenCalled();
let scrollY = (<jasmine.Spy>window.scrollTo).calls.argsFor(0)[1];
expect(scrollY).toBeGreaterThan(0);
done();

View File

@ -1,9 +1,12 @@
'use strict';
import { Injectable, EventEmitter } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ScrollService, INVIEW_POSITION } from './scroll.service';
import { Hash } from './hash.service';
import { SpecManager } from '../utils/spec-manager';
import { SchemaHelper, MenuCategory } from './schema-helper.service';
import { AppStateService } from './app-state.service';
import { LazyTasksService } from '../shared/components/LazyFor/lazy-for';
const CHANGE = {
NEXT : 1,
@ -14,13 +17,19 @@ const CHANGE = {
@Injectable()
export class MenuService {
changed: EventEmitter<any> = new EventEmitter();
ready: BehaviorSubject<boolean> = new BehaviorSubject(false);
categories: Array<MenuCategory>;
activeCatIdx: number = 0;
activeMethodIdx: number = -1;
activeMethodPtr: string;
constructor(private hash:Hash, private scrollService:ScrollService, specMgr:SpecManager) {
constructor(
private hash:Hash,
private tasks: LazyTasksService,
private scrollService: ScrollService,
private appState: AppStateService,
specMgr:SpecManager
) {
this.hash = hash;
this.categories = SchemaHelper.buildMenuTree(specMgr.schema);
@ -30,11 +39,35 @@ export class MenuService {
this.changeActive(CHANGE.INITIAL);
let initialScroll = true;
this.hash.value.subscribe((hash) => {
this.hashScroll(hash);
if (hash == undefined) return;
this.setActiveByHash(hash);
if (!this.tasks.empty) {
this.tasks.start(this.activeCatIdx, this.activeMethodIdx);
this.scrollService.setStickElement(this.getCurrentMethodEl());
this.scrollToActive();
if (initialScroll) {
this.appState.stopLoading();
initialScroll = false;
}
} else {
this.scrollToActive();
}
});
}
get activeMethodPtr() {
let cat = this.categories[this.activeCatIdx];
let ptr = null;
if (cat && cat.methods.length) {
let mtd = cat.methods[this.activeMethodIdx];
ptr = mtd && mtd.pointer || null;
}
return ptr;
}
scrollUpdate(isScrolledDown) {
let stable = false;
while(!stable) {
@ -44,6 +77,7 @@ export class MenuService {
if(isScrolledDown) {
//&& elementInViewPos === INVIEW_POSITION.BELLOW
let $nextEl = this.getRelativeCatOrItem(1);
if (!$nextEl) return;
let nextInViewPos = this.scrollService.getElementPos($nextEl, true);
if (elementInViewPos === INVIEW_POSITION.BELLOW && nextInViewPos === INVIEW_POSITION.ABOVE) {
stable = this.changeActive(CHANGE.NEXT);
@ -105,12 +139,10 @@ export class MenuService {
this.activeCatIdx = catIdx;
this.activeMethodIdx = methodIdx;
menu[catIdx].active = true;
this.activeMethodPtr = null;
let currentItem;
if (menu[catIdx].methods.length && (methodIdx > -1)) {
currentItem = menu[catIdx].methods[methodIdx];
currentItem.active = true;
this.activeMethodPtr = currentItem.pointer;
}
this.changed.next({cat: menu[catIdx], item: currentItem});
@ -156,24 +188,31 @@ export class MenuService {
this.scrollService.scrollTo(this.getCurrentMethodEl());
}
hashScroll(hash) {
if (!hash) return;
let $el;
setActiveByHash(hash) {
if (!hash) {
return;
}
let catIdx, methodIdx;
hash = hash.substr(1);
let namespace = hash.split('/')[0];
let ptr = decodeURIComponent(hash.substr(namespace.length + 1));
if (namespace === 'operation') {
$el = this.getMethodElByOperId(ptr);
} else if (namespace === 'tag') {
if (namespace === 'section' || namespace === 'tag') {
let sectionId = ptr.split('/')[0];
catIdx = this.categories.findIndex(cat => cat.id === namespace + '/' + sectionId);
let cat = this.categories[catIdx];
ptr = ptr.substr(sectionId.length) || null;
sectionId = namespace + (sectionId ? '/' + sectionId : '');
$el = this.getMethodElByPtr(ptr, sectionId);
methodIdx = cat.methods.findIndex(method => method.pointer === ptr);
} else {
$el = this.getMethodElByPtr(null, namespace + '/' + ptr);
catIdx = this.categories.findIndex(cat => {
if (!cat.methods.length) return false;
methodIdx = cat.methods.findIndex(method => method.operationId === ptr || method.pointer === ptr);
if (methodIdx >= 0) {
return true;
} else {
return false;
}
});
}
if ($el) this.scrollService.scrollTo($el);
this.activate(catIdx, methodIdx);
}
}

View File

@ -15,6 +15,7 @@ export interface MenuMethod {
summary: string;
tag: string;
pointer: string;
operationId: string;
}
export interface MenuCategory {
@ -291,13 +292,15 @@ export class SchemaHelper {
}
static buildMenuTree(schema):Array<MenuCategory> {
var catIdx = 0;
let tag2MethodMapping = {};
for (let header of (<Array<string>>(schema.info && schema.info['x-redoc-markdown-headers'] || []))) {
let id = 'section/' + slugify(header);
tag2MethodMapping[id] = {
name: header, id: id, virtual: true, methods: []
name: header, id: id, virtual: true, methods: [], idx: catIdx
};
catIdx++;
}
for (let tag of schema.tags || []) {
@ -309,7 +312,9 @@ export class SchemaHelper {
headless: tag.name === '',
empty: !!tag['x-traitTag'],
methods: [],
idx: catIdx
};
catIdx++;
}
let paths = schema.paths;
@ -331,9 +336,11 @@ export class SchemaHelper {
tagDetails = {
name: tag,
id: id,
headless: tag === ''
headless: tag === '',
idx: catIdx
};
tag2MethodMapping[id] = tagDetails;
catIdx++;
}
if (tagDetails.empty) continue;
if (!tagDetails.methods) tagDetails.methods = [];
@ -341,7 +348,9 @@ export class SchemaHelper {
pointer: methodPointer,
summary: methodSummary,
operationId: methodInfo.operationId,
tag: tag
tag: tag,
idx: tagDetails.methods.length,
catIdx: tagDetails.idx
});
}
}

View File

@ -1,5 +1,5 @@
'use strict';
import { Injectable, EventEmitter, Output } from '@angular/core';
import { Injectable, EventEmitter } from '@angular/core';
import { BrowserDomAdapter as DOM } from '../utils/browser-adapter';
import { OptionsService } from './options.service';
import { throttle } from '../utils/helpers';
@ -14,14 +14,19 @@ export const INVIEW_POSITION = {
export class ScrollService {
scrollYOffset: any;
$scrollParent: any;
@Output() scroll = new EventEmitter();
scroll = new EventEmitter();
private prevOffsetY: number;
private _cancel:any;
constructor(optionsService:OptionsService) {
private _savedPosition:number;
private _stickElement: HTMLElement;
constructor(private optionsService:OptionsService) {
this.scrollYOffset = () => optionsService.options.scrollYOffset();
this.$scrollParent = optionsService.options.$scrollParent;
this.scroll = new EventEmitter();
this.bind();
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
}
scrollY() {
@ -42,20 +47,45 @@ export class ScrollService {
return INVIEW_POSITION.INVIEW;
}
scrollTo($el, offset:number = 0) {
// TODO: rewrite this to use offsetTop as more reliable solution
let subjRect = $el.getBoundingClientRect();
let posY = this.scrollY() + subjRect.top - this.scrollYOffset() + offset + 1;
scrollToPos(posY: number) {
if (this.$scrollParent.scrollTo) {
this.$scrollParent.scrollTo(0, posY);
this.$scrollParent.scrollTo(0, Math.floor(posY));
} else {
this.$scrollParent.scrollTop = posY;
}
}
scrollTo($el, offset:number = 0) {
if (!$el) return;
// TODO: rewrite this to use offsetTop as more reliable solution
let subjRect = $el.getBoundingClientRect();
let posY = this.scrollY() + subjRect.top - this.scrollYOffset() + offset + 1;
this.scrollToPos(posY);
return posY;
}
saveScroll() {
let $el = this._stickElement;
if (!$el) return;
let offsetParent = $el.offsetParent;
this._savedPosition = $el.offsetTop + (<any>offsetParent).offsetTop;
}
setStickElement($el) {
this._stickElement = $el;
}
restoreScroll() {
let $el = this._stickElement;
if (!$el) return;
let offsetParent = $el.offsetParent;
let currentPosition = $el.offsetTop + (<any>offsetParent).offsetTop;
let newY = this.scrollY() + (currentPosition - this._savedPosition);
this.scrollToPos(newY);
}
relativeScrollPos($el) {
let subjRect = $el.getBoundingClientRect();
return - subjRect.top + this.scrollYOffset() - 1;
return -subjRect.top + this.scrollYOffset() - 1;
}
scrollHandler(evt) {

View File

@ -27,7 +27,7 @@ export class CopyButton implements OnInit {
onClick() {
let copied;
if (this.copyText) {
copied = Clipboard.copyCustom(this.copyText);
copied = Clipboard.copyCustom(JSON.stringify(this.copyText));
} else {
copied = Clipboard.copyElement(this.copyElement);
}

View File

@ -0,0 +1,157 @@
'use strict';
import {
Directive,
Input,
TemplateRef,
ChangeDetectorRef,
ViewContainerRef,
Injectable,
NgZone
} from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ScrollService } from '../../../services/scroll.service';
import { OptionsService } from '../../../services/options.service';
import { isSafari } from '../../../utils/helpers';
export class LazyForRow {
constructor(public $implicit: any, public index: number, public show: boolean) {}
get first(): boolean { return this.index === 0; }
get even(): boolean { return this.index % 2 === 0; }
get odd(): boolean { return !this.even; }
}
@Injectable()
export class LazyTasksService {
private _tasks = [];
private _current: number = 0;
private _syncCount: number = 0;
public loadProgress = new BehaviorSubject<number>(0);
public allSync = false;
constructor(public optionsService: OptionsService, private zone: NgZone) {
}
get empty() {
return this._current === this._tasks.length - 1;
}
set syncCount(n: number) {
this._syncCount = n;
}
addTasks(tasks:any[], callback:Function) {
tasks.forEach((task) => {
let taskCopy = Object.assign({_callback: callback}, task);
this._tasks.push(taskCopy);
});
}
nextTaskSync() {
this.zone.runOutsideAngular(() => {
let task = this._tasks[this._current];
if (!task) return;
task._callback(task.idx, true);
this._current++;
this.loadProgress.next(this._current / this._tasks.length * 100);
});
}
nextTask() {
requestAnimationFrame(() => {
let task = this._tasks[this._current];
if (!task) return;
task._callback(task.idx, false).then(() => {
this._current++;
setTimeout(()=> this.nextTask());
this.loadProgress.next(this._current / this._tasks.length * 100);
});
});
}
sortTasks(catIdx, metIdx) {
let idxMap = {};
this._tasks.forEach((task, idx) => {
idxMap[task.catIdx + '_' + task.idx] = idx;
});
metIdx = metIdx < 0 ? 0 : metIdx;
let destIdx = idxMap[catIdx + '_' + metIdx] || 0;
this._tasks.sort((a, b) => {
let aIdx = idxMap[a.catIdx + '_' + a.idx];
let bIdx = idxMap[b.catIdx + '_' + b.idx];
return Math.abs(aIdx - destIdx) - Math.abs(bIdx - destIdx);
})
}
start(catIdx, metIdx) {
let syncCount = 5;
// I know this is bad practice to detect browsers but there is an issue on Safari only
// http://stackoverflow.com/questions/40692365/maintaining-scroll-position-while-inserting-elements-above-glitching-only-in-sa
if (isSafari && this.optionsService.options.$scrollParent === window) {
syncCount = (metIdx >= 0) ?
this._tasks.findIndex(task => (task.catIdx === catIdx) && (task.idx === metIdx))
: this._tasks.findIndex(task => task.catIdx === catIdx);
syncCount += 1;
} else {
this.sortTasks(catIdx, metIdx);
}
if (this.allSync) syncCount = this._tasks.length;
for (var i=0; i < syncCount; i++) {
this.nextTaskSync();
}
this.nextTask();
}
}
@Directive({
selector: '[lazyFor][lazyForOf]'
})
export class LazyFor {
@Input() lazyForOf: any;
prevIdx = null;
private _viewRef;
constructor(
public _template: TemplateRef<LazyForRow>,
public cdr: ChangeDetectorRef,
public _viewContainer: ViewContainerRef,
public lazyTasks: LazyTasksService,
public scroll: ScrollService
){
}
nextIteration(idx: number, sync: boolean):Promise<void> {
const view = this._viewContainer.createEmbeddedView(
this._template, new LazyForRow(this.lazyForOf[idx], idx, sync), idx < this.prevIdx ? 0 : undefined);
this.prevIdx = idx;
view.context.index = idx;
(<any>view as ChangeDetectorRef).markForCheck();
(<any>view as ChangeDetectorRef).detectChanges();
if (sync) {
return Promise.resolve();
}
return new Promise<void>((resolve, reject) => {
requestAnimationFrame(() => {
this.scroll.saveScroll();
view.context.show = true;
(<any>view as ChangeDetectorRef).markForCheck();
(<any>view as ChangeDetectorRef).detectChanges();
this.scroll.restoreScroll();
resolve();
});
});
}
ngOnInit() {
this.lazyTasks.addTasks(this.lazyForOf, this.nextIteration.bind(this))
}
}

View File

@ -83,7 +83,7 @@ export class StickySidebar implements OnInit, OnDestroy {
// FIXME use more reliable code
this.$redocEl = this.$element.offsetParent.parentNode || DOM.defaultDoc().body;
this.bind();
setTimeout(() => this.updatePosition());
requestAnimationFrame(() => this.updatePosition());
//this.updatePosition()
}

View File

@ -69,6 +69,9 @@ export class Tabs implements OnInit {
</div>
`,
styles: [`
:host {
display: block;
}
.tab-wrap {
display: none;
}

View File

@ -12,8 +12,8 @@ $zippy-redirect-bg-color: rgba($zippy-redirect-color, .08);
:host {
// performance optimization
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
// transform: translate3d(0, 0, 0);
// backface-visibility: hidden;
overflow: hidden;
display: block;
}

View File

@ -6,9 +6,11 @@ import { Zippy } from './Zippy/zippy';
import { CopyButton } from './CopyButton/copy-button.directive';
import { SelectOnClick } from './SelectOnClick/select-on-click.directive';
import { DynamicNg2Viewer, DynamicNg2Wrapper } from './DynamicNg2Viewer/dynamic-ng2-viewer.component';
import { LazyFor, LazyTasksService } from './LazyFor/lazy-for';
export const REDOC_COMMON_DIRECTIVES = [
DropDown, StickySidebar, Tabs, Tab, Zippy, CopyButton, SelectOnClick, DynamicNg2Viewer, DynamicNg2Wrapper
DropDown, StickySidebar, Tabs, Tab, Zippy, CopyButton, SelectOnClick, DynamicNg2Viewer, DynamicNg2Wrapper, LazyFor
];
export { DropDown, StickySidebar, Tabs, Tab, Zippy, CopyButton, SelectOnClick, DynamicNg2Viewer, DynamicNg2Wrapper }
export { DropDown, StickySidebar, Tabs, Tab, Zippy, CopyButton, SelectOnClick, DynamicNg2Viewer, DynamicNg2Wrapper, LazyFor }
export { LazyTasksService }

View File

@ -22,7 +22,7 @@ $base-font: Roboto;
$base-font-family: sans-serif;
$base-font-weight: $light;
$base-font-size: 1em;
$base-line-height: 1.55em;
$base-line-height: 1.5em;
$text-color: $black;
// Heading Font

View File

@ -74,3 +74,7 @@ export function throttle(fn, threshhold, scope) {
}
};
}
export const isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0
|| (function (p) { return p.toString() === '[object SafariRemoteNotification]'; })(!window['safari']
|| safari.pushNotification);

View File

@ -41,8 +41,8 @@ export class SpecManager {
this._schema = schema;
try {
this.init();
resolve(this._schema);
this.spec.next(this._schema);
resolve(this._schema);
} catch(err) {
reject(err);
}

View File

@ -19,4 +19,11 @@ declare var AOT: any;
interface ErrorStackTraceLimit {
stackTraceLimit: number;
}
interface History {
scrollRestoration: "auto"|"manual";
}
interface Window {
HTMLElement: any
}
declare var safari: any;
interface ErrorConstructor extends ErrorStackTraceLimit {}