1
0
mirror of https://github.com/bpatrik/pigallery2.git synced 2024-12-16 11:37:13 +02:00
pigallery2/frontend/app/gallery/grid/thumnailLoader.service.ts

94 lines
2.3 KiB
TypeScript
Raw Normal View History

2016-06-17 00:05:31 +02:00
///<reference path="../../../browser.d.ts"/>
import {Injectable} from "@angular/core";
import {GridPhoto} from "./GridPhoto";
2016-06-17 11:25:15 +02:00
import {Config} from "../../config/Config";
2016-06-17 00:05:31 +02:00
@Injectable()
export class ThumbnailLoaderService {
que:Array<ThumbnailTask> = [];
2016-06-17 11:25:15 +02:00
runningRequests:number = 0;
2016-06-17 00:05:31 +02:00
constructor() {
}
2016-06-23 22:25:16 +02:00
removeTasks() {
this.que = [];
}
loadImage(gridPhoto:GridPhoto, onStartedLoading:()=>void, onLoad:()=>void, onError:(error)=>void):void {
2016-06-17 11:25:15 +02:00
let tmp:ThumbnailTask = null;
2016-06-23 22:25:16 +02:00
//is image already qued?
2016-06-17 11:25:15 +02:00
for (let i = 0; i < this.que.length; i++) {
if (this.que[i].gridPhoto.getThumbnailPath() == gridPhoto.getThumbnailPath()) {
tmp = this.que[i];
break;
2016-06-17 00:05:31 +02:00
}
2016-06-17 11:25:15 +02:00
}
2016-06-23 22:25:16 +02:00
//add to previous
2016-06-17 11:25:15 +02:00
if (tmp != null) {
tmp.onStartedLoading.push(onStartedLoading);
tmp.onLoad.push(onLoad);
tmp.onError.push(onError);
2016-06-23 22:25:16 +02:00
if (tmp.inProgress == true) {
onStartedLoading();
}
} else {//create new task
2016-06-17 11:25:15 +02:00
this.que.push({
gridPhoto: gridPhoto,
2016-06-23 22:25:16 +02:00
inProgress: false,
2016-06-17 11:25:15 +02:00
onStartedLoading: [onStartedLoading],
onLoad: [onLoad],
onError: [onError]
});
}
this.run();
2016-06-17 00:05:31 +02:00
}
run() {
2016-06-17 11:25:15 +02:00
if (this.que.length === 0 || this.runningRequests >= Config.Client.concurrentThumbnailGenerations) {
2016-06-17 00:05:31 +02:00
return;
}
2016-06-17 11:25:15 +02:00
this.runningRequests++;
2016-06-23 22:25:16 +02:00
let task = this.que[0];
task.onStartedLoading.forEach(cb=>cb());
task.inProgress = true;
2016-06-17 00:05:31 +02:00
let curImg = new Image();
2016-06-17 11:25:15 +02:00
curImg.src = task.gridPhoto.getThumbnailPath();
2016-06-23 22:25:16 +02:00
curImg.onload = () => {
2016-06-17 11:25:15 +02:00
task.gridPhoto.thumbnailLoaded();
task.onLoad.forEach(cb=>cb());
2016-06-23 22:25:16 +02:00
this.que.shift();
2016-06-17 11:25:15 +02:00
this.runningRequests--;
2016-06-17 00:05:31 +02:00
this.run();
};
2016-06-23 22:25:16 +02:00
curImg.onerror = (error) => {
2016-06-17 11:25:15 +02:00
task.onLoad.forEach(cb=>cb(error));
2016-06-23 22:25:16 +02:00
this.que.shift();
2016-06-17 11:25:15 +02:00
this.runningRequests--;
2016-06-17 00:05:31 +02:00
this.run();
};
}
}
interface ThumbnailTask {
2016-06-17 11:25:15 +02:00
gridPhoto:GridPhoto;
2016-06-23 22:25:16 +02:00
inProgress:boolean;
2016-06-17 11:25:15 +02:00
onStartedLoading:Array<Function>;
onLoad:Array<Function>;
onError:Array<Function>;
2016-06-17 00:05:31 +02:00
}