refactor(lint): fix trivial linting errors

This commit is contained in:
Max Baumann
2020-12-12 23:58:34 +01:00
parent 36558f5460
commit e2ef7412a4
16 changed files with 120 additions and 101 deletions

View File

@@ -18,7 +18,16 @@ module.exports = {
sourceType: "module", sourceType: "module",
}, },
plugins: ["react", "@typescript-eslint"], plugins: ["react", "@typescript-eslint"],
rules: {}, rules: {
// TODO: Remove warn rules when not needed anymore
"@typescript-eslint/no-this-alias": "warn",
"no-fallthrough": "warn",
"no-self-assign": "warn",
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/no-empty-interface": "warn",
"@typescript-eslint/ban-types": "warn",
},
settings: { settings: {
react: { react: {
version: "detect", version: "detect",

View File

@@ -51,7 +51,9 @@
"dev": "npm run build:dev && concurrently \"npm run web-run\" \"npm run build:watch\"", "dev": "npm run build:dev && concurrently \"npm run web-run\" \"npm run build:watch\"",
"dev:firefox": "npm run build:dev:firefox && concurrently \"npm run web-run:firefox\" \"npm run build:watch:firefox\"", "dev:firefox": "npm run build:dev:firefox && concurrently \"npm run web-run:firefox\" \"npm run build:watch:firefox\"",
"clean": "rimraf dist", "clean": "rimraf dist",
"test": "npx jest" "test": "npx jest",
"lint": "eslint src",
"lint:fix": "eslint src --fix"
}, },
"repository": { "repository": {
"type": "git", "type": "git",

View File

@@ -23,7 +23,7 @@ class CategoryChooserComponent extends React.Component<CategoryChooserProps, Cat
} }
} }
render() { render(): React.ReactElement {
return ( return (
<table id="categoryChooserTable" <table id="categoryChooserTable"
className="categoryChooserTable"> className="categoryChooserTable">

View File

@@ -29,7 +29,7 @@ class CategorySkipOptionsComponent extends React.Component<CategorySkipOptionsPr
} }
} }
render() { render(): React.ReactElement {
let defaultOption = "disable"; let defaultOption = "disable";
// Set the default opton properly // Set the default opton properly
for (const categorySelection of Config.config.categorySelections) { for (const categorySelection of Config.config.categorySelections) {
@@ -160,7 +160,7 @@ class CategorySkipOptionsComponent extends React.Component<CategorySkipOptionsPr
return elements; return elements;
} }
setColorState(event: React.FormEvent<HTMLInputElement>, preview: boolean) { setColorState(event: React.FormEvent<HTMLInputElement>, preview: boolean): void {
if (preview) { if (preview) {
this.setState({ this.setState({
previewColor: event.currentTarget.value previewColor: event.currentTarget.value

View File

@@ -60,11 +60,11 @@ class NoticeComponent extends React.Component<NoticeProps, NoticeState> {
} }
} }
componentDidMount() { componentDidMount(): void {
this.startCountdown(); this.startCountdown();
} }
render() { render(): React.ReactElement {
const noticeStyle: React.CSSProperties = { const noticeStyle: React.CSSProperties = {
zIndex: this.props.zIndex || (50 + this.amountOfPreviousNotices) zIndex: this.props.zIndex || (50 + this.amountOfPreviousNotices)
} }
@@ -124,19 +124,19 @@ class NoticeComponent extends React.Component<NoticeProps, NoticeState> {
); );
} }
timerMouseEnter() { timerMouseEnter(): void {
if (this.state.countdownManuallyPaused) return; if (this.state.countdownManuallyPaused) return;
this.pauseCountdown(); this.pauseCountdown();
} }
timerMouseLeave() { timerMouseLeave(): void {
if (this.state.countdownManuallyPaused) return; if (this.state.countdownManuallyPaused) return;
this.startCountdown(); this.startCountdown();
} }
toggleManualPause() { toggleManualPause(): void {
this.setState({ this.setState({
countdownManuallyPaused: !this.state.countdownManuallyPaused countdownManuallyPaused: !this.state.countdownManuallyPaused
}, () => { }, () => {
@@ -149,7 +149,7 @@ class NoticeComponent extends React.Component<NoticeProps, NoticeState> {
} }
//called every second to lower the countdown before hiding the notice //called every second to lower the countdown before hiding the notice
countdown() { countdown(): void {
if (!this.props.timed) return; if (!this.props.timed) return;
const countdownTime = this.state.countdownTime - 1; const countdownTime = this.state.countdownTime - 1;
@@ -176,7 +176,7 @@ class NoticeComponent extends React.Component<NoticeProps, NoticeState> {
}) })
} }
pauseCountdown() { pauseCountdown(): void {
if (!this.props.timed) return; if (!this.props.timed) return;
//remove setInterval //remove setInterval
@@ -195,7 +195,7 @@ class NoticeComponent extends React.Component<NoticeProps, NoticeState> {
notice.style.animation = "none"; notice.style.animation = "none";
} }
startCountdown() { startCountdown(): void {
if (!this.props.timed) return; if (!this.props.timed) return;
//if it has already started, don't start it again //if it has already started, don't start it again
@@ -209,7 +209,7 @@ class NoticeComponent extends React.Component<NoticeProps, NoticeState> {
this.countdownInterval = setInterval(this.countdown.bind(this), 1000); this.countdownInterval = setInterval(this.countdown.bind(this), 1000);
} }
resetCountdown() { resetCountdown(): void {
if (!this.props.timed) return; if (!this.props.timed) return;
this.setState({ this.setState({
@@ -221,20 +221,20 @@ class NoticeComponent extends React.Component<NoticeProps, NoticeState> {
/** /**
* @param silent If true, the close listener will not be called * @param silent If true, the close listener will not be called
*/ */
close(silent?: boolean) { close(silent?: boolean): void {
//remove setInterval //remove setInterval
if (this.countdownInterval !== null) clearInterval(this.countdownInterval); if (this.countdownInterval !== null) clearInterval(this.countdownInterval);
if (!silent) this.props.closeListener(); if (!silent) this.props.closeListener();
} }
changeNoticeTitle(title) { changeNoticeTitle(title: string): void {
this.setState({ this.setState({
noticeTitle: title noticeTitle: title
}); });
} }
addNoticeInfoMessage(message: string, message2 = "") { addNoticeInfoMessage(message: string, message2 = ""): void {
//TODO: Replace //TODO: Replace
const previousInfoMessage = document.getElementById("sponsorTimesInfoMessage" + this.idSuffix); const previousInfoMessage = document.getElementById("sponsorTimesInfoMessage" + this.idSuffix);
@@ -270,4 +270,4 @@ class NoticeComponent extends React.Component<NoticeProps, NoticeState> {
} }
} }
export default NoticeComponent; export default NoticeComponent;

View File

@@ -16,7 +16,7 @@ class NoticeTextSelectionComponent extends React.Component<NoticeTextSelectionPr
super(props); super(props);
} }
render() { render(): React.ReactElement {
const style: React.CSSProperties = {}; const style: React.CSSProperties = {};
if (this.props.onClick) { if (this.props.onClick) {
style.cursor = "pointer"; style.cursor = "pointer";

View File

@@ -129,14 +129,14 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
} }
} }
componentDidMount() { componentDidMount(): void {
if (Config.config.audioNotificationOnSkip && this.audio) { if (Config.config.audioNotificationOnSkip && this.audio) {
this.audio.volume = this.contentContainer().v.volume * 0.1; this.audio.volume = this.contentContainer().v.volume * 0.1;
if (this.autoSkip) this.audio.play(); if (this.autoSkip) this.audio.play();
} }
} }
render() { render(): React.ReactElement {
const noticeStyle: React.CSSProperties = { const noticeStyle: React.CSSProperties = {
zIndex: 50 + this.amountOfPreviousNotices zIndex: 50 + this.amountOfPreviousNotices
} }
@@ -301,7 +301,7 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
return elements; return elements;
} }
prepAction(action: SkipNoticeAction) { prepAction(action: SkipNoticeAction): void {
if (this.segments.length === 1) { if (this.segments.length === 1) {
this.performAction(0, action); this.performAction(0, action);
} else { } else {
@@ -341,7 +341,7 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
* *
* @param index * @param index
*/ */
performAction(index: number, action?: SkipNoticeAction) { performAction(index: number, action?: SkipNoticeAction): void {
switch (action ?? this.state.actionState) { switch (action ?? this.state.actionState) {
case SkipNoticeAction.None: case SkipNoticeAction.None:
break; break;
@@ -364,7 +364,7 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
}); });
} }
adjustDownvotingState(value: boolean) { adjustDownvotingState(value: boolean): void {
if (!value) this.clearConfigListener(); if (!value) this.clearConfigListener();
this.setState({ this.setState({
@@ -373,14 +373,14 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
}); });
} }
clearConfigListener() { clearConfigListener(): void {
if (this.configListener) { if (this.configListener) {
Config.configListeners.splice(Config.configListeners.indexOf(this.configListener), 1); Config.configListeners.splice(Config.configListeners.indexOf(this.configListener), 1);
this.configListener = null; this.configListener = null;
} }
} }
openCategoryChooser() { openCategoryChooser(): void {
// Add as a config listener // Add as a config listener
this.configListener = () => this.forceUpdate(); this.configListener = () => this.forceUpdate();
Config.configListeners.push(this.configListener); Config.configListeners.push(this.configListener);
@@ -396,7 +396,7 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
}); });
} }
getCategoryOptions() { getCategoryOptions(): React.ReactElement[] {
const elements = []; const elements = [];
for (const category of Config.config.categorySelections) { for (const category of Config.config.categorySelections) {
@@ -421,7 +421,7 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
return elements; return elements;
} }
categorySelectionChange(event: React.ChangeEvent<HTMLSelectElement>) { categorySelectionChange(event: React.ChangeEvent<HTMLSelectElement>): void {
// See if show more categories was pressed // See if show more categories was pressed
if (event.target.value === "moreCategories") { if (event.target.value === "moreCategories") {
// Open options page // Open options page
@@ -433,14 +433,14 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
} }
} }
unskip(index: number) { unskip(index: number): void {
this.contentContainer().unskipSponsorTime(this.segments[index]); this.contentContainer().unskipSponsorTime(this.segments[index]);
this.unskippedMode(index, chrome.i18n.getMessage("reskip")); this.unskippedMode(index, chrome.i18n.getMessage("reskip"));
} }
/** Sets up notice to be not skipped yet */ /** Sets up notice to be not skipped yet */
unskippedMode(index: number, buttonText: string) { unskippedMode(index: number, buttonText: string): void {
//setup new callback and reset countdown //setup new callback and reset countdown
this.setState(this.getUnskippedModeInfo(index, buttonText), () => { this.setState(this.getUnskippedModeInfo(index, buttonText), () => {
this.noticeRef.current.resetCountdown(); this.noticeRef.current.resetCountdown();
@@ -468,7 +468,7 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
} }
} }
reskip(index: number) { reskip(index: number): void {
this.contentContainer().reskipSponsorTime(this.segments[index]); this.contentContainer().reskipSponsorTime(this.segments[index]);
//reset countdown //reset countdown
@@ -488,7 +488,7 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
} }
} }
afterVote(segment: SponsorTime, type: number, category: string) { afterVote(segment: SponsorTime, type: number, category: string): void {
this.addVoteButtonInfo(chrome.i18n.getMessage("voted")); this.addVoteButtonInfo(chrome.i18n.getMessage("voted"));
if (type === 0) { if (type === 0) {
@@ -508,32 +508,32 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
} }
} }
setNoticeInfoMessageWithOnClick(onClick: (event: React.MouseEvent) => any, ...messages: string[]) { setNoticeInfoMessageWithOnClick(onClick: (event: React.MouseEvent) => any, ...messages: string[]): void {
this.setState({ this.setState({
messages, messages,
messageOnClick: (event) => onClick(event) messageOnClick: (event) => onClick(event)
}); });
} }
setNoticeInfoMessage(...messages: string[]) { setNoticeInfoMessage(...messages: string[]): void {
this.setState({ this.setState({
messages messages
}); });
} }
addVoteButtonInfo(message) { addVoteButtonInfo(message): void {
this.setState({ this.setState({
thanksForVotingText: message thanksForVotingText: message
}); });
} }
resetVoteButtonInfo() { resetVoteButtonInfo(): void {
this.setState({ this.setState({
thanksForVotingText: null thanksForVotingText: null
}); });
} }
closeListener() { closeListener(): void {
this.clearConfigListener(); this.clearConfigListener();
this.props.closeListener(); this.props.closeListener();

View File

@@ -44,7 +44,7 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
}; };
} }
componentDidMount() { componentDidMount(): void {
// Prevent inputs from triggering key events // Prevent inputs from triggering key events
document.getElementById("sponsorTimesContainer" + this.idSuffix).addEventListener('keydown', function (event) { document.getElementById("sponsorTimesContainer" + this.idSuffix).addEventListener('keydown', function (event) {
event.stopPropagation(); event.stopPropagation();
@@ -57,13 +57,13 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
} }
} }
componentWillUnmount() { componentWillUnmount(): void {
if (this.configUpdateListener) { if (this.configUpdateListener) {
Config.configListeners.splice(Config.configListeners.indexOf(this.configUpdate.bind(this)), 1); Config.configListeners.splice(Config.configListeners.indexOf(this.configUpdate.bind(this)), 1);
} }
} }
render() { render(): React.ReactElement {
const style: React.CSSProperties = { const style: React.CSSProperties = {
textAlign: "center" textAlign: "center"
}; };
@@ -215,7 +215,7 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
); );
} }
getCategoryOptions() { getCategoryOptions(): React.ReactElement[] {
const elements = [( const elements = [(
<option value={"chooseACategory"} <option value={"chooseACategory"}
key={"chooseACategory"}> key={"chooseACategory"}>
@@ -245,7 +245,7 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
return elements; return elements;
} }
categorySelectionChange(event: React.ChangeEvent<HTMLSelectElement>) { categorySelectionChange(event: React.ChangeEvent<HTMLSelectElement>): void {
// See if show more categories was pressed // See if show more categories was pressed
if (event.target.value === "moreCategories") { if (event.target.value === "moreCategories") {
// Open options page // Open options page
@@ -259,15 +259,15 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
this.saveEditTimes(); this.saveEditTimes();
} }
setTimeToNow(index: number) { setTimeToNow(index: number): void {
this.setTimeTo(index, this.props.contentContainer().getRealCurrentTime()); this.setTimeTo(index, this.props.contentContainer().getRealCurrentTime());
} }
setTimeToEnd() { setTimeToEnd(): void {
this.setTimeTo(1, this.props.contentContainer().v.duration); this.setTimeTo(1, this.props.contentContainer().v.duration);
} }
setTimeTo(index: number, time: number) { setTimeTo(index: number, time: number): void {
const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index]; const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index];
sponsorTime.segment[index] = sponsorTime.segment[index] =
@@ -302,7 +302,7 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
utils.getFormattedTime(sponsorTime.segment[1], true)]; utils.getFormattedTime(sponsorTime.segment[1], true)];
} }
saveEditTimes() { saveEditTimes(): void {
const sponsorTimesSubmitting = this.props.contentContainer().sponsorTimesSubmitting; const sponsorTimesSubmitting = this.props.contentContainer().sponsorTimesSubmitting;
if (this.state.editing) { if (this.state.editing) {
@@ -369,7 +369,7 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
} }
} }
configUpdate() { configUpdate(): void {
this.forceUpdate(); this.forceUpdate();
} }
} }

View File

@@ -49,7 +49,7 @@ class SubmissionNoticeComponent extends React.Component<SubmissionNoticeProps, S
} }
} }
componentDidMount() { componentDidMount(): void {
// Catch and rerender when the video size changes // Catch and rerender when the video size changes
//TODO: Use ResizeObserver when it is supported in TypeScript //TODO: Use ResizeObserver when it is supported in TypeScript
this.videoObserver = new MutationObserver(() => { this.videoObserver = new MutationObserver(() => {
@@ -61,13 +61,13 @@ class SubmissionNoticeComponent extends React.Component<SubmissionNoticeProps, S
}); });
} }
componentWillUnmount() { componentWillUnmount(): void {
if (this.videoObserver) { if (this.videoObserver) {
this.videoObserver.disconnect(); this.videoObserver.disconnect();
} }
} }
render() { render(): React.ReactElement {
return ( return (
<NoticeComponent noticeTitle={this.state.noticeTitle} <NoticeComponent noticeTitle={this.state.noticeTitle}
idSuffix={this.state.idSuffix} idSuffix={this.state.idSuffix}
@@ -153,7 +153,7 @@ class SubmissionNoticeComponent extends React.Component<SubmissionNoticeProps, S
return elements; return elements;
} }
cancel() { cancel(): void {
this.noticeRef.current.close(true); this.noticeRef.current.close(true);
this.contentContainer().resetSponsorSubmissionNotice(); this.contentContainer().resetSponsorSubmissionNotice();
@@ -161,7 +161,7 @@ class SubmissionNoticeComponent extends React.Component<SubmissionNoticeProps, S
this.props.closeListener(); this.props.closeListener();
} }
submit() { submit(): void {
// save all items // save all items
for (const ref of this.timeEditRefs) { for (const ref of this.timeEditRefs) {
ref.current.saveEditTimes(); ref.current.saveEditTimes();

View File

@@ -149,7 +149,7 @@ const Config: SBObject = {
skipCount: 0, skipCount: 0,
sponsorTimesContributed: 0, sponsorTimesContributed: 0,
submissionCountSinceCategories: 0, submissionCountSinceCategories: 0,
showTimeWithSkips: true, showTimeWithSkips: true,
unsubmittedWarning: true, unsubmittedWarning: true,
disableSkipping: false, disableSkipping: false,
trackViewCount: true, trackViewCount: true,
@@ -314,7 +314,7 @@ function configProxy(): any {
return new Proxy({handler}, handler); return new Proxy({handler}, handler);
} }
function fetchConfig() { function fetchConfig(): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
chrome.storage.sync.get(null, function(items) { chrome.storage.sync.get(null, function(items) {
Config.localConfig = <SBConfig> <unknown> items; // Data is ready Config.localConfig = <SBConfig> <unknown> items; // Data is ready
@@ -453,11 +453,11 @@ function convertJSON(): void {
// Add defaults // Add defaults
function addDefaults() { function addDefaults() {
for (const key in Config.defaults) { for (const key in Config.defaults) {
if(!Config.localConfig.hasOwnProperty(key)) { if(!Object.prototype.hasOwnProperty.call(Config.localConfig, key)) {
Config.localConfig[key] = Config.defaults[key]; Config.localConfig[key] = Config.defaults[key];
} else if (key === "barTypes") { } else if (key === "barTypes") {
for (const key2 in Config.defaults[key]) { for (const key2 in Config.defaults[key]) {
if(!Config.localConfig[key].hasOwnProperty(key2)) { if(!Object.prototype.hasOwnProperty.call(Config.localConfig[key], key2)) {
Config.localConfig[key][key2] = Config.defaults[key][key2]; Config.localConfig[key][key2] = Config.defaults[key][key2];
} }
} }

View File

@@ -18,7 +18,7 @@ class PreviewBar {
timestamps: number[][]; timestamps: number[][];
types: string; types: string;
constructor(parent, onMobileYouTube, onInvidious) { constructor(parent: any, onMobileYouTube: boolean, onInvidious: boolean) {
this.container = document.createElement('ul'); this.container = document.createElement('ul');
this.container.id = 'previewbar'; this.container.id = 'previewbar';
this.parent = parent; this.parent = parent;
@@ -31,7 +31,7 @@ class PreviewBar {
this.setupHoverText(); this.setupHoverText();
} }
setupHoverText() { setupHoverText(): void {
if (this.onMobileYouTube || this.onInvidious) return; if (this.onMobileYouTube || this.onInvidious) return;
const seekBar = document.querySelector(".ytp-progress-bar-container"); const seekBar = document.querySelector(".ytp-progress-bar-container");
@@ -112,7 +112,7 @@ class PreviewBar {
}); });
} }
updatePosition(parent) { updatePosition(parent: any): void {
//below the seek bar //below the seek bar
// this.parent.insertAdjacentElement("afterEnd", this.container); // this.parent.insertAdjacentElement("afterEnd", this.container);
@@ -129,7 +129,7 @@ class PreviewBar {
this.parent.insertAdjacentElement("afterBegin", this.container); this.parent.insertAdjacentElement("afterBegin", this.container);
} }
updateColor(segment, color, opacity) { updateColor(segment: string, color: string, opacity: string): void {
const bars = <NodeListOf<HTMLElement>> document.querySelectorAll('[data-vs-segment-type=' + segment + ']'); const bars = <NodeListOf<HTMLElement>> document.querySelectorAll('[data-vs-segment-type=' + segment + ']');
for (const bar of bars) { for (const bar of bars) {
bar.style.backgroundColor = color; bar.style.backgroundColor = color;
@@ -137,7 +137,7 @@ class PreviewBar {
} }
} }
set(timestamps, types, duration) { set(timestamps: number[][], types: string, duration: number): void {
while (this.container.firstChild) { while (this.container.firstChild) {
this.container.removeChild(this.container.firstChild); this.container.removeChild(this.container.firstChild);
} }
@@ -171,14 +171,14 @@ class PreviewBar {
} }
} }
createBar() { createBar(): HTMLLIElement {
const bar = document.createElement('li'); const bar = document.createElement('li');
bar.classList.add('previewbar'); bar.classList.add('previewbar');
bar.innerHTML = '&nbsp;'; bar.innerHTML = '&nbsp;';
return bar; return bar;
} }
remove() { remove(): void {
this.container.remove(); this.container.remove();
this.container = undefined; this.container = undefined;
} }

View File

@@ -32,7 +32,7 @@ async function init() {
for (let i = 0; i < optionsElements.length; i++) { for (let i = 0; i < optionsElements.length; i++) {
switch (optionsElements[i].getAttribute("option-type")) { switch (optionsElements[i].getAttribute("option-type")) {
case "toggle": case "toggle": {
const option = optionsElements[i].getAttribute("sync-option"); const option = optionsElements[i].getAttribute("sync-option");
const optionResult = Config.config[option]; const optionResult = Config.config[option];
@@ -84,7 +84,8 @@ async function init() {
} }
}); });
break; break;
case "text-change": }
case "text-change": {
const textChangeOption = optionsElements[i].getAttribute("sync-option"); const textChangeOption = optionsElements[i].getAttribute("sync-option");
const textChangeInput = <HTMLInputElement> optionsElements[i].querySelector(".option-text-box"); const textChangeInput = <HTMLInputElement> optionsElements[i].querySelector(".option-text-box");
@@ -95,7 +96,7 @@ async function init() {
textChangeSetButton.addEventListener("click", async () => { textChangeSetButton.addEventListener("click", async () => {
// See if anything extra must be done // See if anything extra must be done
switch (textChangeOption) { switch (textChangeOption) {
case "serverAddress": case "serverAddress": {
const result = validateServerAddress(textChangeInput.value); const result = validateServerAddress(textChangeInput.value);
if (result !== null) { if (result !== null) {
@@ -117,6 +118,7 @@ async function init() {
} }
break; break;
}
} }
Config.config[textChangeOption] = textChangeInput.value; Config.config[textChangeOption] = textChangeInput.value;
@@ -133,7 +135,8 @@ async function init() {
}); });
break; break;
case "private-text-change": }
case "private-text-change": {
const button = optionsElements[i].querySelector(".trigger-button"); const button = optionsElements[i].querySelector(".trigger-button");
button.addEventListener("click", () => activatePrivateTextChange(<HTMLElement> optionsElements[i])); button.addEventListener("click", () => activatePrivateTextChange(<HTMLElement> optionsElements[i]));
@@ -145,7 +148,8 @@ async function init() {
} }
break; break;
case "button-press": }
case "button-press": {
const actionButton = optionsElements[i].querySelector(".trigger-button"); const actionButton = optionsElements[i].querySelector(".trigger-button");
switch(optionsElements[i].getAttribute("sync-option")) { switch(optionsElements[i].getAttribute("sync-option")) {
@@ -155,16 +159,18 @@ async function init() {
} }
break; break;
case "keybind-change": }
case "keybind-change": {
const keybindButton = optionsElements[i].querySelector(".trigger-button"); const keybindButton = optionsElements[i].querySelector(".trigger-button");
keybindButton.addEventListener("click", () => activateKeybindChange(<HTMLElement> optionsElements[i])); keybindButton.addEventListener("click", () => activateKeybindChange(<HTMLElement> optionsElements[i]));
break; break;
case "display": }
case "display":{
updateDisplayElement(<HTMLElement> optionsElements[i]) updateDisplayElement(<HTMLElement> optionsElements[i])
break; break;
case "number-change": }
case "number-change": {
const numberChangeOption = optionsElements[i].getAttribute("sync-option"); const numberChangeOption = optionsElements[i].getAttribute("sync-option");
const configValue = Config.config[numberChangeOption]; const configValue = Config.config[numberChangeOption];
const numberInput = optionsElements[i].querySelector("input"); const numberInput = optionsElements[i].querySelector("input");
@@ -180,6 +186,7 @@ async function init() {
}); });
break; break;
}
case "react-CategoryChooserComponent": case "react-CategoryChooserComponent":
new CategoryChooser(optionsElements[i]); new CategoryChooser(optionsElements[i]);
break; break;
@@ -298,7 +305,7 @@ function invidiousInit(checkbox: HTMLInputElement, option: string) {
* @param checkbox * @param checkbox
* @param option * @param option
*/ */
async function invidiousOnClick(checkbox: HTMLInputElement, option: string) { async function invidiousOnClick(checkbox: HTMLInputElement, option: string): Promise<void> {
return new Promise((resolve) => { return new Promise((resolve) => {
if (checkbox.checked) { if (checkbox.checked) {
utils.setupExtraSitePermissions(function (granted) { utils.setupExtraSitePermissions(function (granted) {
@@ -427,7 +434,7 @@ function activatePrivateTextChange(element: HTMLElement) {
// See if anything extra must be done // See if anything extra must be done
switch (option) { switch (option) {
case "*": case "*": {
const jsonData = JSON.parse(JSON.stringify(Config.localConfig)); const jsonData = JSON.parse(JSON.stringify(Config.localConfig));
// Fix segmentTimes data as it is destroyed from the JSON stringify // Fix segmentTimes data as it is destroyed from the JSON stringify
@@ -435,6 +442,7 @@ function activatePrivateTextChange(element: HTMLElement) {
result = JSON.stringify(jsonData); result = JSON.stringify(jsonData);
break; break;
}
} }
textBox.value = result; textBox.value = result;
@@ -528,7 +536,7 @@ function copyDebugOutputToClipboard() {
.then(() => { .then(() => {
alert(chrome.i18n.getMessage("copyDebugInformationComplete")); alert(chrome.i18n.getMessage("copyDebugInformationComplete"));
}) })
.catch(err => { .catch((err) => {
alert(chrome.i18n.getMessage("copyDebugInformationFailed")); alert(chrome.i18n.getMessage("copyDebugInformationFailed"));
}); });
} }

View File

@@ -38,7 +38,7 @@ class MessageHandler {
} }
//make this a function to allow this to run on the content page //make this a function to allow this to run on the content page
async function runThePopup(messageListener?: MessageListener) { async function runThePopup(messageListener?: MessageListener): Promise<void> {
const messageHandler = new MessageHandler(messageListener); const messageHandler = new MessageHandler(messageListener);
utils.localizeHtmlPage(); utils.localizeHtmlPage();
@@ -233,17 +233,17 @@ async function runThePopup(messageListener?: MessageListener) {
}, onTabs); }, onTabs);
function onTabs(tabs) { function onTabs(tabs) {
messageHandler.sendMessage(tabs[0].id, {message: 'getVideoID'}, function(result) { messageHandler.sendMessage(tabs[0].id, {message: 'getVideoID'}, function(result) {
if (result != undefined && result.videoID) { if (result != undefined && result.videoID) {
currentVideoID = result.videoID; currentVideoID = result.videoID;
loadTabData(tabs); loadTabData(tabs);
} else if (result == undefined && chrome.runtime.lastError) { } else if (result == undefined && chrome.runtime.lastError) {
//this isn't a YouTube video then, or at least the content script is not loaded // this isn't a YouTube video then, or at least the content script is not loaded
displayNoVideo(); displayNoVideo();
} }
}); });
} }
function loadTabData(tabs) { function loadTabData(tabs) {
if (!currentVideoID) { if (!currentVideoID) {
//this isn't a YouTube video then //this isn't a YouTube video then

View File

@@ -63,7 +63,7 @@ class SkipNotice {
); );
} }
close() { close(): void {
ReactDOM.unmountComponentAtNode(this.noticeElement); ReactDOM.unmountComponentAtNode(this.noticeElement);
this.noticeElement.remove(); this.noticeElement.remove();

View File

@@ -51,11 +51,11 @@ class SubmissionNotice {
); );
} }
update() { update(): void {
this.noticeRef.current.forceUpdate(); this.noticeRef.current.forceUpdate();
} }
close() { close(): void {
ReactDOM.unmountComponentAtNode(this.noticeElement); ReactDOM.unmountComponentAtNode(this.noticeElement);
this.noticeElement.remove(); this.noticeElement.remove();

View File

@@ -24,7 +24,7 @@ class Utils {
} }
// Function that can be used to wait for a condition before returning // Function that can be used to wait for a condition before returning
async wait(condition, timeout = 5000, check = 100) { async wait(condition: () => boolean, timeout = 5000, check = 100): Promise<boolean> {
return await new Promise((resolve, reject) => { return await new Promise((resolve, reject) => {
setTimeout(() => reject("TIMEOUT"), timeout); setTimeout(() => reject("TIMEOUT"), timeout);
@@ -51,7 +51,7 @@ class Utils {
* *
* @param {CallableFunction} callback * @param {CallableFunction} callback
*/ */
setupExtraSitePermissions(callback) { setupExtraSitePermissions(callback: (granted: boolean) => void): void {
// Request permission // Request permission
let permissions = ["declarativeContent"]; let permissions = ["declarativeContent"];
if (this.isFirefox()) permissions = []; if (this.isFirefox()) permissions = [];
@@ -79,7 +79,7 @@ class Utils {
* *
* For now, it is just SB.config.invidiousInstances. * For now, it is just SB.config.invidiousInstances.
*/ */
setupExtraSiteContentScripts() { setupExtraSiteContentScripts(): void {
const self = this; const self = this;
if (this.isFirefox()) { if (this.isFirefox()) {
@@ -135,7 +135,7 @@ class Utils {
/** /**
* Removes the permission and content script registration. * Removes the permission and content script registration.
*/ */
removeExtraSiteRegistration() { removeExtraSiteRegistration(): void {
if (this.isFirefox()) { if (this.isFirefox()) {
const id = "invidious"; const id = "invidious";
@@ -193,7 +193,7 @@ class Utils {
} }
} }
localizeHtmlPage() { localizeHtmlPage(): void {
//Localize by replacing __MSG_***__ meta tags //Localize by replacing __MSG_***__ meta tags
const objects = document.getElementsByClassName("sponsorBlockPageBody")[0].children; const objects = document.getElementsByClassName("sponsorBlockPageBody")[0].children;
for (let j = 0; j < objects.length; j++) { for (let j = 0; j < objects.length; j++) {
@@ -204,7 +204,7 @@ class Utils {
} }
} }
getLocalizedMessage(text) { getLocalizedMessage(text: string): string | false {
const valNewH = text.replace(/__MSG_(\w+)__/g, function(match, v1) { const valNewH = text.replace(/__MSG_(\w+)__/g, function(match, v1) {
return v1 ? chrome.i18n.getMessage(v1) : ""; return v1 ? chrome.i18n.getMessage(v1) : "";
}); });
@@ -219,8 +219,8 @@ class Utils {
/** /**
* @returns {String[]} Invidious Instances in regex form * @returns {String[]} Invidious Instances in regex form
*/ */
getInvidiousInstancesRegex() { getInvidiousInstancesRegex(): string[] {
const invidiousInstancesRegex = []; const invidiousInstancesRegex: string[] = [];
for (const url of Config.config.invidiousInstances) { for (const url of Config.config.invidiousInstances) {
invidiousInstancesRegex.push("https://*." + url + "/*"); invidiousInstancesRegex.push("https://*." + url + "/*");
invidiousInstancesRegex.push("http://*." + url + "/*"); invidiousInstancesRegex.push("http://*." + url + "/*");
@@ -229,7 +229,7 @@ class Utils {
return invidiousInstancesRegex; return invidiousInstancesRegex;
} }
generateUserID(length = 36) { generateUserID(length = 36): string {
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = ""; let result = "";
if (window.crypto && window.crypto.getRandomValues) { if (window.crypto && window.crypto.getRandomValues) {
@@ -253,7 +253,7 @@ class Utils {
* @param {int} statusCode * @param {int} statusCode
* @returns {string} errorMessage * @returns {string} errorMessage
*/ */
getErrorMessage(statusCode) { getErrorMessage(statusCode: number): string {
let errorMessage = ""; let errorMessage = "";
if([400, 429, 409, 502, 0].includes(statusCode)) { if([400, 429, 409, 502, 0].includes(statusCode)) {
@@ -310,7 +310,7 @@ class Utils {
* @param address The address to add to the SponsorBlock server address * @param address The address to add to the SponsorBlock server address
* @param callback * @param callback
*/ */
sendRequestToServer(type: string, address: string, callback?: (response: FetchResponse) => void) { sendRequestToServer(type: string, address: string, callback?: (response: FetchResponse) => void): void {
const serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress; const serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress;
// Ask the background script to do the work // Ask the background script to do the work