cap-image-cache
Version:
Easy way to cache images with angular + capacitor
198 lines (192 loc) • 8.44 kB
JavaScript
import * as i0 from '@angular/core';
import { InjectionToken, Injectable, Inject, Directive, Input, NgModule } from '@angular/core';
import { __awaiter } from 'tslib';
import { Filesystem, Directory } from '@capacitor/filesystem';
const CACHE_PATH = new InjectionToken('CACHE_PATH');
class CapImageCacheService {
constructor(cachePath = 'CACHE_IMAGES') {
this.cachePath = cachePath;
}
getImageSrc(_url) {
return __awaiter(this, void 0, void 0, function* () {
let newUrl = new URL(_url);
const imageName = newUrl.pathname.split('/').pop();
const imageType = (imageName || _url).split('.').pop();
try {
const readFile = yield Filesystem.readFile({
directory: Directory.Cache,
path: this.cachePath + '/' + imageName,
});
return {
data: `data:image/${imageType};base64,${readFile.data}`,
from: 'cache',
};
}
catch (e) {
try {
yield this.storeImage(_url, imageName || _url);
const readFile = yield Filesystem.readFile({
directory: Directory.Cache,
path: this.cachePath + '/' + imageName,
});
return {
data: `data:image/${imageType};base64,${readFile.data}`,
from: 'network',
};
}
catch (error) {
throw new Error("there's a network error 2");
}
}
});
}
storeImage(url, path) {
return __awaiter(this, void 0, void 0, function* () {
try {
const response = yield fetch(url);
const blob = yield response.blob();
if (blob.type === 'text/html') {
console.error('response wan not an image');
throw new Error('There was an error while loading an image');
}
const base64Data = yield this.convertBlobToBase64(blob);
const savedFile = yield Filesystem.writeFile({
directory: Directory.Cache,
data: base64Data,
path: this.cachePath + '/' + path,
recursive: true,
});
return savedFile;
}
catch (error) {
throw new Error("there's a network error");
}
});
}
convertBlobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = () => {
if (reader !== null) {
const res = reader.result || '';
resolve(res.toString());
}
else {
reject('Error #F00');
}
};
reader.readAsDataURL(blob);
});
}
}
CapImageCacheService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: CapImageCacheService, deps: [{ token: CACHE_PATH }], target: i0.ɵɵFactoryTarget.Injectable });
CapImageCacheService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: CapImageCacheService, providedIn: 'any' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: CapImageCacheService, decorators: [{
type: Injectable,
args: [{ providedIn: 'any' }]
}], ctorParameters: function () {
return [{ type: undefined, decorators: [{
type: Inject,
args: [CACHE_PATH]
}] }];
} });
class CapImageCacheDirective {
constructor(element, capImageCacheService) {
this.element = element;
this.capImageCacheService = capImageCacheService;
this._lazy = false;
this._alreadyRendered = false;
}
ngAfterViewInit() {
return __awaiter(this, void 0, void 0, function* () {
if (this._lazy) {
this.startObserving();
}
else {
this.loadImage();
}
});
}
loadImage() {
return __awaiter(this, void 0, void 0, function* () {
if (this._src) {
try {
const result = yield this.capImageCacheService.getImageSrc(this._src);
if (this.element.nativeElement.nodeName !== 'IMG') {
this.element.nativeElement.style.backgroundImage = `url('${result.data}')`;
}
else {
this.element.nativeElement.src = result.data;
}
console.info(this._src, 'Loaded successfully from', result.from);
}
catch (error) {
throw new Error('cannot load image check your url');
}
}
else {
throw new Error('image src url is not set');
}
});
}
startObserving() {
var _a;
this._observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
this.renderContents(entry.isIntersecting);
});
}, { threshold: [0, 0.1, 0.9, 1] });
(_a = this._observer) === null || _a === void 0 ? void 0 : _a.observe(this.element.nativeElement);
}
renderContents(isInView) {
var _a;
if (isInView) {
if (!this._alreadyRendered) {
this._alreadyRendered = true;
(_a = this._observer) === null || _a === void 0 ? void 0 : _a.disconnect();
this.loadImage();
}
}
}
}
CapImageCacheDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: CapImageCacheDirective, deps: [{ token: i0.ElementRef }, { token: CapImageCacheService }], target: i0.ɵɵFactoryTarget.Directive });
CapImageCacheDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "13.0.3", type: CapImageCacheDirective, selector: "[cache-img]", inputs: { _src: ["cache-img", "_src"], _lazy: ["lazy", "_lazy"] }, ngImport: i0 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: CapImageCacheDirective, decorators: [{
type: Directive,
args: [{ selector: '[cache-img]' }]
}], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: CapImageCacheService }]; }, propDecorators: { _src: [{
type: Input,
args: ['cache-img']
}], _lazy: [{
type: Input,
args: ['lazy']
}] } });
class CapImageCacheConfig {
}
class CapImageCacheModule {
static forRoot(config = {}) {
return {
ngModule: CapImageCacheModule,
providers: [
{ provide: CACHE_PATH, useValue: config.cachePath },
{ provide: CapImageCacheService, useValue: config },
],
};
}
}
CapImageCacheModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: CapImageCacheModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
CapImageCacheModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: CapImageCacheModule, declarations: [CapImageCacheDirective], exports: [CapImageCacheDirective] });
CapImageCacheModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: CapImageCacheModule });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: CapImageCacheModule, decorators: [{
type: NgModule,
args: [{
declarations: [CapImageCacheDirective],
exports: [CapImageCacheDirective],
}]
}] });
/**
* Generated bundle index. Do not edit.
*/
export { CACHE_PATH, CapImageCacheConfig, CapImageCacheDirective, CapImageCacheModule, CapImageCacheService };
//# sourceMappingURL=cap-image-cache.mjs.map