2018-05-11 23:58:10 -04:00
|
|
|
import { Directive, ElementRef, OnDestroy, OnInit } from "@angular/core";
|
|
|
|
import { Subscription } from "rxjs/Subscription";
|
|
|
|
import { ScalarWidgetApi } from "../services/scalar/scalar-widget.api";
|
|
|
|
import { ScalarToWidgetRequest } from "../models/scalar-widget-actions";
|
|
|
|
import * as domtoimage from "dom-to-image";
|
2020-10-23 07:30:20 -04:00
|
|
|
import { TranslateService } from "@ngx-translate/core";
|
2018-05-11 23:58:10 -04:00
|
|
|
|
|
|
|
@Directive({
|
|
|
|
selector: "[myScreenshotCapable]",
|
|
|
|
})
|
|
|
|
export class ScreenshotCapableDirective implements OnInit, OnDestroy {
|
|
|
|
|
|
|
|
private widgetApiSubscription: Subscription;
|
|
|
|
|
2020-10-23 07:30:20 -04:00
|
|
|
constructor(private el: ElementRef, public translate: TranslateService) {
|
|
|
|
this.translate = translate;
|
2018-05-11 23:58:10 -04:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
public ngOnInit() {
|
|
|
|
this.widgetApiSubscription = ScalarWidgetApi.requestReceived.subscribe(request => {
|
|
|
|
if (request.action === "screenshot") this.takeScreenshot(request);
|
2018-05-12 18:46:08 -04:00
|
|
|
});
|
2018-05-11 23:58:10 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
public ngOnDestroy() {
|
|
|
|
if (this.widgetApiSubscription) this.widgetApiSubscription.unsubscribe();
|
|
|
|
}
|
|
|
|
|
|
|
|
private takeScreenshot(request: ScalarToWidgetRequest) {
|
2018-05-12 18:46:08 -04:00
|
|
|
if (this.el.nativeElement.tagName === "IFRAME") {
|
|
|
|
console.error("Attempted to take a screenshot of an iframe");
|
2021-09-01 19:01:01 -04:00
|
|
|
this.translate.get('Failed to take screenshot: iframe not supported').subscribe((res: string) => {
|
|
|
|
ScalarWidgetApi.replyError(request, new Error("Cannot take screenshot of iframe"), res);
|
|
|
|
});
|
2018-05-12 18:46:08 -04:00
|
|
|
} else {
|
|
|
|
domtoimage.toBlob(this.el.nativeElement).then(b => {
|
|
|
|
if (!b) {
|
|
|
|
console.warn("No screenshot produced - skipping reply");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
ScalarWidgetApi.replyScreenshot(request, b);
|
|
|
|
}).catch(error => {
|
|
|
|
console.error(error);
|
2021-09-01 19:01:01 -04:00
|
|
|
this.translate.get('Failed to take screenshot').subscribe((res: string) => {
|
|
|
|
ScalarWidgetApi.replyError(request, error, res);
|
|
|
|
});
|
2018-05-12 18:46:08 -04:00
|
|
|
});
|
|
|
|
}
|
2018-05-11 23:58:10 -04:00
|
|
|
}
|
|
|
|
}
|