<!DOCTYPE html>
<html>

  <head>
    <base href="." />
    <script data-require="d3@3.5.17" data-semver="3.5.17" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
    <script type="text/javascript" charset="utf-8">
      window.AngularVersionForThisPlunker = 'latest'
    </script>
    <title>angular playground</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js/dist/zone.js"></script>
    <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
    <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
    <script src="config.js"></script>
    <script>
    System.import('app')
      .catch(console.error.bind(console));
  </script>
  </head>

  <body>
    <my-app>
    loading...
  </my-app>
  </body>

</html>
/* Styles go here */

.vr-container {
  position: relative;
  width: 300px;
  height: 60vh;
  border: 1px solid #808080;
  overflow: auto;
}

.vr-container.horizontal {
   width: 80vw;
   height: 300px;
}

.item {
  position: absolute;
  width: 100%;
  height: 50px;
  top: 0;
  left: 0;
  border: 1px dotted lightblue;
  font-size: 12px;
}

.item.horizontal {
  width: 80px;
  height: 100%;
}
### Angular Starter Plunker - Typescript
var angularVersion;
if(window.AngularVersionForThisPlunker === 'latest'){
  angularVersion = ''; //picks up latest
}
else {
  angularVersion = '@' + window.AngularVersionForThisPlunker;
}

System.config({
  //use typescript for compilation
  transpiler: 'typescript',
  //typescript compiler options
  typescriptOptions: {
    emitDecoratorMetadata: true
  },
  paths: {
    'npm:': 'https://unpkg.com/'
  },
  //map tells the System loader where to look for things
  map: {
    
    'app': './src',
    '@angular/core': 'npm:@angular/core'+ angularVersion + '/bundles/core.umd.js',
    '@angular/common': 'npm:@angular/common' + angularVersion + '/bundles/common.umd.js',
    '@angular/compiler': 'npm:@angular/compiler' + angularVersion  + '/bundles/compiler.umd.js',
    '@angular/platform-browser': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser.umd.js',
    '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + angularVersion + '/bundles/platform-browser-dynamic.umd.js',
    '@angular/http': 'npm:@angular/http' + angularVersion + '/bundles/http.umd.js',
    '@angular/router': 'npm:@angular/router' + angularVersion +'/bundles/router.umd.js',
    '@angular/forms': 'npm:@angular/forms' + angularVersion + '/bundles/forms.umd.js',
    '@angular/animations': 'npm:@angular/animations' + angularVersion + '/bundles/animations.umd.js',
    '@angular/platform-browser/animations': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser-animations.umd.js',
    '@angular/animations/browser': 'npm:@angular/animations' + angularVersion + '/bundles/animations-browser.umd.js',
    
    '@angular/core/testing': 'npm:@angular/core' + angularVersion + '/bundles/core-testing.umd.js',
    '@angular/common/testing': 'npm:@angular/common' + angularVersion + '/bundles/common-testing.umd.js',
    '@angular/compiler/testing': 'npm:@angular/compiler' + angularVersion + '/bundles/compiler-testing.umd.js',
    '@angular/platform-browser/testing': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser-testing.umd.js',
    '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic' + angularVersion + '/bundles/platform-browser-dynamic-testing.umd.js',
    '@angular/http/testing': 'npm:@angular/http' + angularVersion + '/bundles/http-testing.umd.js',
    '@angular/router/testing': 'npm:@angular/router' + angularVersion + '/bundles/router-testing.umd.js',
    'tslib': 'npm:tslib@1.6.1',
    'rxjs': 'npm:rxjs',
    'typescript': 'npm:typescript@2.2.1/lib/typescript.js'
  },
  //packages defines our app package
  packages: {
    app: {
      main: './main.ts',
      defaultExtension: 'ts'
    },
    rxjs: {
      defaultExtension: 'js'
    }
  }
});
//main entry point
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app';

platformBrowserDynamic().bootstrapModule(AppModule)
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

import {
    Input, ElementRef,
    ViewChild,
    DoCheck,
    Renderer2, ViewRef,
    Directive,
    TemplateRef,
    ViewContainerRef,
    IterableDiffer,
    IterableDiffers,
    SimpleChanges,
    AfterViewInit,
    OnChanges, NgIterable,
    EmbeddedViewRef,
    IterableChangeRecord,
    IterableChanges,
    EventEmitter,
    Output
} from '@angular/core';
import { NgFor, NgForOfContext, CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@Directive({
    selector: '[vsFor][vsForOf]'
})
export class VirtualRepeatDirective implements AfterViewInit, DoCheck, OnChanges {
    private itemSize: number = 0;
    private realScrollSize: number = 0;
    private currPage: number = 0;
    private currPageOffset: number = 0;
    private prevScrollPos: number = 0;
    private numPages: number = 0;
    private pageHeight: number = 0;
    private jumpCoefficient: number = 0;
    private virtualSize: number = 0;
    private viewportSize: number = 0;
    private cache = new Map<number, ViewRef>();
    private $scroller: HTMLDivElement = document.createElement('div');
    private $viewport: HTMLElement;
    private scrollListener: () => void;
    private _differ: IterableDiffer<any[]> | null = null;
    private _trackByFn: TrackByFunction<any[]>;
    private expectedTime = 0;

    @Input() vsForOf: any[];
    @Input() vsForHorizontal: boolean = false;
    @Output() afterRender = new EventEmitter<any>();

    constructor(
        private _element: ElementRef,
        private _viewContainer: ViewContainerRef,
        private rdr: Renderer2,
        private _template: TemplateRef<any>,
        private _differs: IterableDiffers) {
    }

    @Input()
    set vsForTemplate(value: TemplateRef<NgForOfContext<any[]>>) {
        if (value) {
            this._template = value;
        }
    }

    @Input()
    set vsForTrackBy(fn: TrackByFunction<any[]>) {
        this._trackByFn = fn;
    }

    get vsForTrackBy(): TrackByFunction<any[]> {
        return this._trackByFn;
    }

    onScroll($event: any) {
        const scrollPos = this.$viewport[this.isHorzontal() ? 'scrollLeft' : 'scrollTop'];
        if (Math.abs(scrollPos - this.prevScrollPos) > this.viewportSize) {
            this._onJump();
        } else {
            this._onNearScroll();
        }

        this._renderViewportItems();
    }

    ngAfterViewInit() {
        this.realScrollSize = this.calcMaxBrowserScrollSize();
        this.$viewport = this._element.nativeElement.parentElement;
        this.$viewport.style.position = 'relative';
        this.$scroller.style.position = 'absolute';
        this.$scroller.style.left = '0px';
        this.$scroller.style.top = '0px';
        this.$scroller.style[this.isHorzontal() ? 'height' : 'width'] = '1px';
        this.rdr.appendChild(this.$viewport, this.$scroller);
        this.viewportSize = this.$viewport.getBoundingClientRect()[this.isHorzontal() ? 'width' : 'height'];
        this.scrollListener = this.rdr.listen(this.$viewport, 'scroll', this.onScroll.bind(this));
    }

    ngOnChanges(changes: SimpleChanges): void {
        if ('vsForOf' in changes) {
            // React on vsForOf changes only once all inputs have been initialized
            const value = changes['vsForOf'].currentValue;
            if (!this._differ && value) {
                try {
                    this._differ = this._differs.find(value).create(this.vsForTrackBy);
                } catch (e) {
                    throw new Error(
                        `Cannot find a differ supporting object '${value}' of type '${JSON.stringify(value)}'. NgFor only supports binding to Iterables such as Arrays.`);
                }
            }
        }
    }

    scrollToItem(index: number) {
        console.log(index);
        const virtualPos = index * this.itemSize;
        const currPage = /*this.currPage*/  Math.floor(virtualPos / this.pageHeight);
        const currPageOffset = /*this.currPageOffset*/  Math.round(currPage * this.jumpCoefficient);        
        //this.$viewport[this.isHorzontal() ? 'scrollLeft' : 'scrollTop'] = this.prevScrollPos = (virtualPos - this.currPageOffset);
        this.tween(this.$viewport, this.$viewport[this.isHorzontal() ? 'scrollLeft' : 'scrollTop'], virtualPos - currPageOffset, 750, () => {console.log('Done')});
    }

    ngDoCheck(): void {
        if (this._differ) {
            const changes = this._differ.diff(this.vsForOf);
            if (changes) {
                this._refresh(changes);
            }
        }
    }

      private tween(w, start, end, duration, fn) {

        d3.select(w).transition().duration(duration)
          .tween("ms1234", () => {
            return (t) => { w[this.isHorzontal() ? 'scrollLeft' : 'scrollTop'] = d3.interpolateNumber(start, end)(t); };
         });
        
    }
    
    private _onNearScroll() {
        const scrollPos = this.$viewport[this.isHorzontal() ? 'scrollLeft' : 'scrollTop'];

        if (scrollPos + this.currPageOffset > (this.currPage + 1) * this.pageHeight) {
            this.currPage++;
            this.currPageOffset = Math.round(this.currPage * this.jumpCoefficient);
            this.$viewport[this.isHorzontal() ? 'scrollLeft' : 'scrollTop'] = this.prevScrollPos = (scrollPos - this.jumpCoefficient);
            this.clear();
        } else if (scrollPos + this.currPageOffset < this.currPage * this.pageHeight) {
            this.currPage--;
            this.currPageOffset = Math.round(this.currPage * this.jumpCoefficient);
            this.$viewport[this.isHorzontal() ? 'scrollLeft' : 'scrollTop'] = this.prevScrollPos = (scrollPos + this.jumpCoefficient);
            this.clear();
        } else {
            this.prevScrollPos = scrollPos;
        }
    }

    private _onJump() {
        const scrollPos = this.$viewport[this.isHorzontal() ? 'scrollLeft' : 'scrollTop'];
        this.currPage = Math.floor(scrollPos * ((this.virtualSize - this.viewportSize) / (this.realScrollSize - this.viewportSize)) * (1 / this.pageHeight));
        this.currPageOffset = Math.round(this.currPage * this.jumpCoefficient);
        this.prevScrollPos = scrollPos;
        this.clear();
    }

    private isHorzontal(): boolean {
        return this.vsForHorizontal;
    }

    private _refresh(changes: IterableChanges<any[]>) {
        this.clear();

        const view = this._viewContainer.createEmbeddedView(this._template);
        view.context.__position__ = 0;
        view.context.$implicit = this.vsForOf[0];
        view.context.start = 0;
        view.context.end = 0;
        view.context.index = 0;
        view.detectChanges();
        const rect = getComputedStyle(this.$viewport.firstElementChild);
        this.itemSize = parseFloat(this.isHorzontal() ? rect.width : rect.height)
            + (this.isHorzontal() ? (parseFloat(rect.marginLeft) + parseFloat(rect.marginRight))
                : (parseFloat(rect.marginTop) + parseFloat(rect.marginBottom)));

        this.virtualSize = this.vsForOf.length * this.itemSize;
        this.pageHeight = this.realScrollSize / 100;
        this.numPages = Math.ceil(this.virtualSize / this.pageHeight);
        const coff = (this.virtualSize - this.realScrollSize) / (this.numPages - 1);
        this.jumpCoefficient = coff > 0 ? coff : 1;
        this.realScrollSize = this.realScrollSize > this.virtualSize ? this.virtualSize : this.realScrollSize;
        this.currPage = 1;
        this.currPageOffset = 0;
        this.prevScrollPos = this.prevScrollPos >= 0 ? this.prevScrollPos : 0;

        this.$scroller.style[this.isHorzontal() ? 'width' : 'height'] = `${this.realScrollSize}px`;
        view.destroy();
        this.$viewport.dispatchEvent(new Event('scroll'));
    }

    private clear() {
        this.cache.clear();
        this._viewContainer.clear();
    }

    private _renderViewportItems() {
        const y = this.$viewport[this.isHorzontal() ? 'scrollLeft' : 'scrollTop'] + this.currPageOffset;

        let start = Math.floor((y - this.viewportSize) / this.itemSize);
        let end = Math.ceil((y + (this.viewportSize * 2)) / this.itemSize);

        start = Math.max(0, start);
        end = Math.min(this.virtualSize / this.itemSize, end);

        this.cache.forEach((v, i) => {
            if (i < start || i > end) {
                v.destroy();
                this.cache.delete(i);
            }
        });

        this.vsForOf.slice(start, end).forEach((item, i) => {
            if (!this.cache.get(i + start)) {
                const view = this._viewContainer.createEmbeddedView(this._template);
                view.context.__position__ = (i + start) * this.itemSize - this.currPageOffset;
                view.context.$implicit = item;
                view.context.start = start;
                view.context.end = end;
                view.context.index = i + start;
                this.cache.set(i + start, view);
                view.markForCheck();
            }
        });

        this.afterRender.emit({ items: this.vsForOf.slice(start, end) });
    }

    private calcMaxBrowserScrollSize(): number {
        if (!this.realScrollSize) {
            const div = document.createElement('div');
            const style = div.style;
            style.position = 'absolute';
            style.left = '99999999999999px';
            style.top = '9999999999999999px';
            document.body.appendChild(div);

            const size = div.getBoundingClientRect()[this.isHorzontal() ? 'left' : 'top'];
            document.body.removeChild(div);
            return Math.abs(size);
        } else {
            return this.realScrollSize;
        }
    }

    ngOnDestroy() {
        if (this.scrollListener) {
            this.scrollListener();
        }
    }
}


export interface TrackByFunction<T> {
    (index: number, item: T): any;
}

@Component({
  selector: 'my-app',
  template: `
    Go to: <input type="text" [(ngModel)]="goTo">
    <button type="button" (click)="go()">GO</button>
    <div class="vr-container">
      <ng-template vsFor let-event [vsForOf]="items" let-position="__position__">
        <span class="item" [style.top.px]="position">Entry-{{event.id}}</span>
      </ng-template>
    </div>
    <br>
    <!--
     <div  class="vr-container horizontal">
      <ng-template vsFor let-event [vsForOf]="items" let-position="__position__" [vsForHorizontal]="true">
        <span class="item horizontal" [style.left.px]="position">Entry-{{event.id}}</span>
      </ng-template>
    </div> -->
  `,
})
export class App {
  items = [];
  goTo = 0;
  
  @ViewChild(VirtualRepeatDirective) vrForDir: VirtualRepeatDirective;
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`;
     
  }
  
  go() {
    this.vrForDir.scrollToItem(this.goTo * 1);
  }
  
  ngAfterViewInit() {
    for(let i = 0; i < 1000001; i++) {
      this.items[i] = {id: i, name: 'ID-' + i}
    }
  }
  
  getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
  }
}

@NgModule({
  imports: [ BrowserModule, CommonModule, FormsModule ],
  declarations: [ App, VirtualRepeatDirective ],
  bootstrap: [ App ]
})
export class AppModule {}