Migrate first batch to typescript

This commit is contained in:
Tamius Han 2021-02-08 22:45:51 +01:00
parent d9053e26b5
commit ee3ccef0e4
5 changed files with 164 additions and 55 deletions

View File

@ -4,8 +4,11 @@ import AspectRatio from '../../../common/enums/aspect-ratio.enum';
import PlayerNotificationUi from '../uwui/PlayerNotificationUI'; import PlayerNotificationUi from '../uwui/PlayerNotificationUI';
import PlayerUi from '../uwui/PlayerUI'; import PlayerUi from '../uwui/PlayerUI';
import BrowserDetect from '../../conf/BrowserDetect'; import BrowserDetect from '../../conf/BrowserDetect';
import _ from 'lodash'; import * as _ from 'lodash';
import { sleep } from '../../../common/js/utils'; import { sleep } from '../../../common/js/utils';
import VideoData from './VideoData';
import Settings from '../Settings';
import Logger from '../Logger';
if (process.env.CHANNEL !== 'stable'){ if (process.env.CHANNEL !== 'stable'){
console.info("Loading: PlayerData.js"); console.info("Loading: PlayerData.js");
@ -40,6 +43,31 @@ if (process.env.CHANNEL !== 'stable'){
class PlayerData { class PlayerData {
//#region helper objects
logger: Logger;
videoData: VideoData;
settings: Settings;
notificationService: PlayerNotificationUi;
//#endregion
//#region HTML objects
video: any;
element: any;
overlayNode: any;
//#endregion
//#region flags
invalid: boolean = false;
private periodicallyRefreshPlayerElement: boolean = false;
halted: boolean = true;
//#region misc stuff
extensionMode: any;
dimensions: any;
private playerIdElement: any;
private observer: MutationObserver;
//#endregion
constructor(videoData) { constructor(videoData) {
try { try {
this.logger = videoData.logger; this.logger = videoData.logger;
@ -84,7 +112,7 @@ class PlayerData {
} }
onPlayerDimensionsChanged(mutationList, observer) { onPlayerDimensionsChanged(mutationList?, observer?) {
if (this?.checkPlayerSizeChange()) { if (this?.checkPlayerSizeChange()) {
this.videoData.resizer.restore(); this.videoData.resizer.restore();
} }

View File

@ -3,11 +3,43 @@ import PlayerData from './PlayerData';
import Resizer from '../video-transform/Resizer'; import Resizer from '../video-transform/Resizer';
import ArDetector from '../ar-detect/ArDetector'; import ArDetector from '../ar-detect/ArDetector';
import AspectRatio from '../../../common/enums/aspect-ratio.enum'; import AspectRatio from '../../../common/enums/aspect-ratio.enum';
import _ from 'lodash'; import * as _ from 'lodash';
import BrowserDetect from '../../conf/BrowserDetect'; import BrowserDetect from '../../conf/BrowserDetect';
import Logger from '../Logger';
import Settings from '../Settings';
import PageInfo from './PageInfo';
import { sleep } from '../../../common/js/utils';
class VideoData { class VideoData {
//#region flags
arSetupComplete: boolean = false;
destroyed: boolean = false;
invalid: boolean = false;
videoStatusOk: boolean = false;
videoLoaded: boolean = false;
videoDimensionsLoaded: boolean = false;
paused: boolean = false;
//#endregion
//#region misc stuff
vdid: string;
video: any;
observer: MutationObserver;
extensionMode: any;
userCssClassName: string;
validationId: number;
dimensions: any;
//#endregion
//#region helper objects
logger: Logger;
settings: Settings;
pageInfo: PageInfo;
player: PlayerData;
resizer: Resizer;
arDetector: ArDetector;
//#endregion
constructor(video, settings, pageInfo){ constructor(video, settings, pageInfo){
this.vdid = (Math.random()*100).toFixed(); this.vdid = (Math.random()*100).toFixed();
@ -267,7 +299,8 @@ class VideoData {
if (this.pageInfo.defaultCrop) { if (this.pageInfo.defaultCrop) {
this.resizer.setAr(this.pageInfo.defaultCrop); this.resizer.setAr(this.pageInfo.defaultCrop);
} else { } else {
this.resizer.reset(); console.log("RESETTING!")
this.resizer.reset();
try { try {
this.stopArDetection(); this.stopArDetection();
@ -286,7 +319,7 @@ class VideoData {
this.validationId = validationId; this.validationId = validationId;
while (!this.destroyed && !this.invalid && this.validationId === validationId) { while (!this.destroyed && !this.invalid && this.validationId === validationId) {
await this.sleep(500); await sleep(500);
this.doPeriodicFallbackChangeDetectionCheck(); this.doPeriodicFallbackChangeDetectionCheck();
} }
} }
@ -295,11 +328,6 @@ class VideoData {
this.validateVideoOffsets(); this.validateVideoOffsets();
} }
async sleep(timeout) {
return new Promise( (resolve) => setTimeout(() => resolve(), timeout));
}
onVideoDimensionsChanged(mutationList, observer) { onVideoDimensionsChanged(mutationList, observer) {
if (!mutationList || this.video === undefined) { // something's wrong if (!mutationList || this.video === undefined) { // something's wrong
if (observer && this.video) { if (observer && this.video) {
@ -391,7 +419,7 @@ class VideoData {
* Gets the contents of the style attribute of the video element * Gets the contents of the style attribute of the video element
* in a form of an object. * in a form of an object.
*/ */
getVideoStyle() { getVideoStyle(): any {
// This will _always_ give us an array. Empty string gives an array // This will _always_ give us an array. Empty string gives an array
// that contains one element. That element is an empty string. // that contains one element. That element is an empty string.
const styleArray = (this.video.getAttribute('style') || '').split(';'); const styleArray = (this.video.getAttribute('style') || '').split(';');
@ -502,7 +530,7 @@ class VideoData {
} }
this.paused = false; this.paused = false;
try { try {
this.resizer.start(); // this.resizer.start();
if (this.player) { if (this.player) {
this.player.start(); this.player.start();
} }

View File

@ -9,34 +9,59 @@ import VideoAlignment from '../../../common/enums/video-alignment.enum';
import AspectRatio from '../../../common/enums/aspect-ratio.enum'; import AspectRatio from '../../../common/enums/aspect-ratio.enum';
import CropModePersistance from '../../../common/enums/crop-mode-persistence.enum'; import CropModePersistance from '../../../common/enums/crop-mode-persistence.enum';
import { sleep } from '../Util'; import { sleep } from '../Util';
import Logger from '../Logger';
import Settings from '../Settings';
import VideoData from '../video-data/VideoData';
if(Debug.debug) { if(Debug.debug) {
console.log("Loading: Resizer.js"); console.log("Loading: Resizer.js");
} }
class Resizer { class Resizer {
//#region flags
canPan: boolean = false;
destroyed: boolean = false;
//#endregion
//#region helper objects
logger: Logger;
settings: Settings;
scaler: Scaler;
stretcher: Stretcher;
zoom: Zoom;
conf: VideoData;
//#endregion
//#region HTML elements
video: any;
//#endregion
//#region data
correctedVideoDimensions: any;
currentCss: any;
currentStyleString: string;
currentPlayerStyleString: any;
currentCssValidFor: any;
currentVideoSettings: any;
lastAr: {type: any, ratio?: number} = {type: AspectRatio.Initial};
resizerId: any;
videoAlignment: any;
userCss: string;
userCssClassName: any;
pan: any = null;
//#endregion
constructor(videoData) { constructor(videoData) {
this.resizerId = (Math.random(99)*100).toFixed(0); this.resizerId = (Math.random()*100).toFixed(0);
this.conf = videoData; this.conf = videoData;
this.logger = videoData.logger; this.logger = videoData.logger;
this.video = videoData.video; this.video = videoData.video;
this.settings = videoData.settings; this.settings = videoData.settings;
this.extensionMode = videoData.extensionMode;
this.scaler = new Scaler(this.conf); this.scaler = new Scaler(this.conf);
this.stretcher = new Stretcher(this.conf); this.stretcher = new Stretcher(this.conf);
this.zoom = new Zoom(this.conf); this.zoom = new Zoom(this.conf);
// load up default values
this.correctedVideoDimensions = {};
this.currentCss = {};
this.currentStyleString = "";
this.currentPlayerStyleString = "";
this.currentCssValidFor = {};
this.lastAr = {type: AspectRatio.Initial};
this.videoAlignment = this.settings.getDefaultVideoAlignment(window.location.hostname); // this is initial video alignment this.videoAlignment = this.settings.getDefaultVideoAlignment(window.location.hostname); // this is initial video alignment
this.destroyed = false; this.destroyed = false;
@ -47,7 +72,6 @@ class Resizer {
this.canPan = false; this.canPan = false;
} }
this.userCss = '';
this.userCssClassName = videoData.userCssClassName; this.userCssClassName = videoData.userCssClassName;
} }
@ -140,7 +164,7 @@ class Resizer {
} }
} }
async setAr(ar, lastAr) { async setAr(ar: {type: any, ratio?: number}, lastAr?: {type: any, ratio?: number}) {
if (this.destroyed) { if (this.destroyed) {
return; return;
} }
@ -157,6 +181,7 @@ class Resizer {
} }
const siteSettings = this.settings.active.sites[window.location.hostname]; const siteSettings = this.settings.active.sites[window.location.hostname];
let stretchFactors: {xFactor: number, yFactor: number, arCorrectionFactor?: number, ratio?: number} | any;
// reset zoom, but only on aspect ratio switch. We also know that aspect ratio gets converted to // reset zoom, but only on aspect ratio switch. We also know that aspect ratio gets converted to
// AspectRatio.Fixed when zooming, so let's keep that in mind // AspectRatio.Fixed when zooming, so let's keep that in mind
@ -224,7 +249,7 @@ class Resizer {
|| this.stretcher.mode === Stretch.Conditional || this.stretcher.mode === Stretch.Conditional
|| this.stretcher.mode === Stretch.FixedSource){ || this.stretcher.mode === Stretch.FixedSource){
var stretchFactors = this.scaler.calculateCrop(ar); stretchFactors = this.scaler.calculateCrop(ar);
if(! stretchFactors || stretchFactors.error){ if(! stretchFactors || stretchFactors.error){
this.logger.log('error', 'debug', `[Resizer::setAr] <rid:${this.resizerId}> failed to set AR due to problem with calculating crop. Error:`, stretchFactors?.error); this.logger.log('error', 'debug', `[Resizer::setAr] <rid:${this.resizerId}> failed to set AR due to problem with calculating crop. Error:`, stretchFactors?.error);
@ -255,15 +280,15 @@ class Resizer {
); );
} else if (this.stretcher.mode === Stretch.Hybrid) { } else if (this.stretcher.mode === Stretch.Hybrid) {
var stretchFactors = this.stretcher.calculateStretch(ar.ratio); stretchFactors = this.stretcher.calculateStretch(ar.ratio);
this.logger.log('info', 'debug', '[Resizer::setAr] Processed stretch factors for hybrid stretch/crop. Stretch factors are:', stretchFactors); this.logger.log('info', 'debug', '[Resizer::setAr] Processed stretch factors for hybrid stretch/crop. Stretch factors are:', stretchFactors);
} else if (this.stretcher.mode === Stretch.Fixed) { } else if (this.stretcher.mode === Stretch.Fixed) {
var stretchFactors = this.stretchFactors.calculateStretchFixed(ar.ratio) stretchFactors = this.stretcher.calculateStretchFixed(ar.ratio)
} else if (this.stretcher.mode === Stretch.Basic) { } else if (this.stretcher.mode === Stretch.Basic) {
var stretchFactors = this.stretcher.calculateBasicStretch(); stretchFactors = this.stretcher.calculateBasicStretch();
this.logger.log('info', 'debug', '[Resizer::setAr] Processed stretch factors for basic stretch. Stretch factors are:', stretchFactors); this.logger.log('info', 'debug', '[Resizer::setAr] Processed stretch factors for basic stretch. Stretch factors are:', stretchFactors);
} else { } else {
var stretchFactors = {xFactor: 1, yFactor: 1}; stretchFactors = {xFactor: 1, yFactor: 1};
this.logger.log('error', 'debug', '[Resizer::setAr] Okay wtf happened? If you see this, something has gone wrong', stretchFactors,"\n------[ i n f o d u m p ]------\nstretcher:", this.stretcher); this.logger.log('error', 'debug', '[Resizer::setAr] Okay wtf happened? If you see this, something has gone wrong', stretchFactors,"\n------[ i n f o d u m p ]------\nstretcher:", this.stretcher);
} }
@ -272,6 +297,10 @@ class Resizer {
this.stretcher.chromeBugMitigation(stretchFactors); this.stretcher.chromeBugMitigation(stretchFactors);
var translate = this.computeOffsets(stretchFactors); var translate = this.computeOffsets(stretchFactors);
console.log("aspect ratio will be set. stretch factors:", stretchFactors, "translate:", translate);
this.applyCss(stretchFactors, translate); this.applyCss(stretchFactors, translate);
} }
@ -279,7 +308,7 @@ class Resizer {
toFixedAr() { toFixedAr() {
// converting to fixed AR means we also turn off autoAR // converting to fixed AR means we also turn off autoAR
this.setAr({ this.setAr({
ar: this.lastAr.ar, ratio: this.lastAr.ratio,
type: AspectRatio.Fixed type: AspectRatio.Fixed
}); });
} }
@ -296,7 +325,7 @@ class Resizer {
return this.lastAr; return this.lastAr;
} }
setStretchMode(stretchMode, fixedStretchRatio){ setStretchMode(stretchMode, fixedStretchRatio?){
this.stretcher.setStretchMode(stretchMode, fixedStretchRatio); this.stretcher.setStretchMode(stretchMode, fixedStretchRatio);
this.restore(); this.restore();
} }
@ -326,7 +355,7 @@ class Resizer {
} }
resetPan() { resetPan() {
this.pan = {}; this.pan = {x: 0, y: 0};
this.videoAlignment = this.settings.getDefaultVideoAlignment(window.location.hostname); this.videoAlignment = this.settings.getDefaultVideoAlignment(window.location.hostname);
} }
@ -334,7 +363,7 @@ class Resizer {
// relativeMousePos[X|Y] - on scale from 0 to 1, how close is the mouse to player edges. // relativeMousePos[X|Y] - on scale from 0 to 1, how close is the mouse to player edges.
// use these values: top, left: 0, bottom, right: 1 // use these values: top, left: 0, bottom, right: 1
if(! this.pan){ if(! this.pan){
this.pan = {}; this.pan = {x: 0, y: 0};
} }
if (this.settings.active.miscSettings.mousePanReverseMouse) { if (this.settings.active.miscSettings.mousePanReverseMouse) {
@ -386,10 +415,6 @@ class Resizer {
} }
} }
resetPan(){
this.pan = undefined;
}
setZoom(zoomLevel, no_announce) { setZoom(zoomLevel, no_announce) {
this.zoom.setZoom(zoomLevel, no_announce); this.zoom.setZoom(zoomLevel, no_announce);
} }
@ -489,7 +514,7 @@ class Resizer {
const hdiff = this.conf.player.dimensions.height - realVideoHeight; const hdiff = this.conf.player.dimensions.height - realVideoHeight;
if (wdiff < 0 && hdiff < 0 && this.zoom.scale > 1) { if (wdiff < 0 && hdiff < 0 && this.zoom.scale > 1) {
this.conf.player.restore(); this.conf.resizer.restore();
} }
const wdiffAfterZoom = realVideoWidth * stretchFactors.xFactor - this.conf.player.dimensions.width; const wdiffAfterZoom = realVideoWidth * stretchFactors.xFactor - this.conf.player.dimensions.width;
@ -503,7 +528,7 @@ class Resizer {
if (this.pan) { if (this.pan.relativeOffsetX || this.pan.relativeOffsetY) {
// don't offset when video is smaller than player // don't offset when video is smaller than player
if(wdiffAfterZoom >= 0 || hdiffAfterZoom >= 0) { if(wdiffAfterZoom >= 0 || hdiffAfterZoom >= 0) {
translate.x += wdiffAfterZoom * this.pan.relativeOffsetX * this.zoom.scale; translate.x += wdiffAfterZoom * this.pan.relativeOffsetX * this.zoom.scale;
@ -518,7 +543,7 @@ class Resizer {
} }
} }
this.logger.log('info', ['debug', 'resizer'], "[Resizer::_res_computeOffsets] <rid:"+this.resizerId+"> calculated offsets:\n\n", console.log('info', ['debug', 'resizer'], "[Resizer::_res_computeOffsets] <rid:"+this.resizerId+"> calculated offsets:\n\n",
'---- data in ----', '---- data in ----',
'\nplayer dimensions: ', {w: this.conf.player.dimensions.width, h: this.conf.player.dimensions.height}, '\nplayer dimensions: ', {w: this.conf.player.dimensions.width, h: this.conf.player.dimensions.height},
'\nvideo dimensions: ', {w: this.conf.video.offsetWidth, h: this.conf.video.offsetHeight}, '\nvideo dimensions: ', {w: this.conf.video.offsetWidth, h: this.conf.video.offsetHeight},

View File

@ -1,6 +1,9 @@
import Stretch from '../../../common/enums/stretch.enum'; import Stretch from '../../../common/enums/stretch.enum';
import BrowserDetect from '../../conf/BrowserDetect'; import BrowserDetect from '../../conf/BrowserDetect';
import AspectRatio from '../../../common/enums/aspect-ratio.enum'; import AspectRatio from '../../../common/enums/aspect-ratio.enum';
import VideoData from '../video-data/VideoData';
import Logger from '../Logger';
import Settings from '../Settings';
// računa vrednosti za transform-scale (x, y) // računa vrednosti za transform-scale (x, y)
// transform: scale(x,y) se uporablja za raztegovanje videa, ne pa za približevanje // transform: scale(x,y) se uporablja za raztegovanje videa, ne pa za približevanje
@ -8,8 +11,20 @@ import AspectRatio from '../../../common/enums/aspect-ratio.enum';
// transform: scale(x,y) is used for stretching, not zooming. // transform: scale(x,y) is used for stretching, not zooming.
class Stretcher { class Stretcher {
// internal variables //#region flags
//#endregion
//#region helper objects
conf: VideoData;
logger: Logger;
settings: Settings;
//#endregion
//#region misc data
mode: any;
fixedStretchRatio: any;
//#endregion
// functions // functions
constructor(videoData) { constructor(videoData) {
@ -20,7 +35,7 @@ class Stretcher {
this.fixedStretchRatio = undefined; this.fixedStretchRatio = undefined;
} }
setStretchMode(stretchMode, fixedStretchRatio) { setStretchMode(stretchMode, fixedStretchRatio?) {
if (stretchMode === Stretch.Default) { if (stretchMode === Stretch.Default) {
this.mode = this.settings.getDefaultStretchMode(window.location.hostname); this.mode = this.settings.getDefaultStretchMode(window.location.hostname);
} else { } else {
@ -145,7 +160,7 @@ squeezeFactor: ${squeezeFactor}`, '\nvideo', this.conf.video);
return arCorrectionFactor; return arCorrectionFactor;
} }
calculateStretch(actualAr, playerArOverride) { calculateStretch(actualAr, playerArOverride?) {
const playerAr = playerArOverride || this.conf.player.dimensions.width / this.conf.player.dimensions.height; const playerAr = playerArOverride || this.conf.player.dimensions.width / this.conf.player.dimensions.height;
const streamAr = this.conf.video.videoWidth / this.conf.video.videoHeight; const streamAr = this.conf.video.videoWidth / this.conf.video.videoHeight;
@ -153,7 +168,7 @@ squeezeFactor: ${squeezeFactor}`, '\nvideo', this.conf.video);
actualAr = playerAr; actualAr = playerAr;
} }
var stretchFactors = { var stretchFactors: any = {
xFactor: 1, xFactor: 1,
yFactor: 1 yFactor: 1
}; };

View File

@ -1,19 +1,32 @@
import Debug from '../../conf/Debug'; import Debug from '../../conf/Debug';
import Logger from '../Logger';
import VideoData from '../video-data/VideoData';
// računa približevanje ter računa/popravlja odmike videa // računa približevanje ter računa/popravlja odmike videa
// calculates zooming and video offsets/panning // calculates zooming and video offsets/panning
class Zoom { class Zoom {
// functions //#region flags
//#endregion
//#region helper objects
conf: VideoData;
logger: Logger;
//#endregion
//#region misc data
scale: number = 1;
logScale: number = 0;
scaleStep: number = 0.1;
minScale: number = -1; // 50% (log2(0.5) = -1)
maxScale: number = 3; // 800% (log2(8) = 3)
//#endregion
constructor(videoData) { constructor(videoData) {
this.conf = videoData; this.conf = videoData;
this.logger = videoData.logger; this.logger = videoData.logger;
this.scale = 1;
this.logScale = 0;
this.scaleStep = 0.1;
this.minScale = -1; // 50% (log2(0.5) = -1)
this.maxScale = 3; // 800% (log2(8) = 3)
} }
reset(){ reset(){
@ -41,7 +54,7 @@ class Zoom {
this.conf.announceZoom(this.scale); this.conf.announceZoom(this.scale);
} }
setZoom(scale, no_announce){ setZoom(scale: number, no_announce?){
this.logger.log('info', 'debug', "[Zoom::setZoom] Setting zoom to", scale, "!"); this.logger.log('info', 'debug', "[Zoom::setZoom] Setting zoom to", scale, "!");
// NOTE: SCALE IS NOT LOGARITHMIC // NOTE: SCALE IS NOT LOGARITHMIC